有人能解释一下为什么我在下面的脚本中没有得到结果吗:
当我在phpmyadmin中运行查询时,它返回正确的结果(id
),但运行下面的php脚本时,它会回显"No row found!";
<?php
if(isset($_SESSION['word'])) {
$word = $_SESSION['word']."<br>";
echo $word;
$query = ("SELECT id FROM customer WHERE mobil = $word");
if (!$query) {
die('Invalid query: ' . mysql_error());
}
else {
$results = mysql_query($query);
while ($row = mysql_fetch_assoc($results)) {
echo '<pre>', print_r($row), '<pre>';
}
if (!$row) {
echo "No row found!";
}
}
}
?>
您的查询无效,应该是这样的:
$query = mysql_query("YOUR QUERY");
此外,您不应该使用Mysql_,因为它已被弃用,很快就会被删除请改用PDO或MySQLI。你可以在这里找到更多信息:
为什么不应该';我在PHP中使用mysql_*函数吗?
尝试这个
$results = mysqli_query($query);
if(mysqli_num_rows($results)>0){
while ($row = mysqli_fetch_assoc($results)) {
echo '<pre>', print_r($row), '<pre>';
}
else{
echo "No row found!";
}
}
试试这个:
$query = ('SELECT id FROM `customer` WHERE mobil = "$word" ');
应该是
<?php
require_once("db_connect.php");
if(isset($_SESSION['word'])) {
$word = $_SESSION['word']."<br>"; //Getting word here
$query = "SELECT id FROM customer WHERE mobil = $word";
$result = mysqli_query($db,$query); //$db holds the database connection
if (!$result)
{
die('Invalid query: ' . mysqli_error($db));
}
else
{
$result_rows = mysqli_num_rows($result); //Getting the no. of rows
if($result_rows!=0) // If any record present,the below code executes
{
while ($row = mysqli_fetch_assoc($result))
{
echo '<pre>', print_r($row), '<pre>';
}
}
else
{
echo "No rows found"; // If no record found,this prints.
}
}
}
?>
数据库连接(db_connect.php):
$db = mysqli_connect("localhost","username","password","database_name");
注意:Mysql已折旧。您应该使用Mysqli或PDO。
您的查询是错误的。
更改此项:
$query = ("SELECT id FROM customer WHERE mobil = $word");
收件人:
$query = ("SELECT id FROM customer WHERE mobil = '".$word."'");
但是您的代码存在许多安全问题。
更新并解决我上面的脚本运行得很好,这要归功于@CodingAnt(他问:这个mobil字段包含什么数据类型?)-我检查了数据库,结果发现mobil被设置为VARCHAR而不是INT。把它改为INT,现在一切都正常了。