用于指定信息的PHP搜索数据库

时间:2014-02-13 20:22:41

标签: php mysql database

我有一个mysql数据库,并且已经使用我的PHP脚本成功连接到它。但是我试图获取一个变量并在数据库中搜索字符串(在这种情况下名称为'Alec')如果名称Alec在数据库中,我想打印它。什么都没有在屏幕上打印,是的,Alec在数据库中。谢谢你的帮助。

$db=mysqli_connect("database","uid","pass", "name");

if (mysqli_connect_errno()){
  echo "no connection: " . mysqli_connect_error();
}
//create table in db
$table="CREATE TABLE people(firstName CHAR(30),lastName CHAR(30),age INT)";
//exc  table query
if(mysqli_query($db,$table)){
    echo "Created  people table " . mysqli_error($db);
} else { 
    echo "No.";
}

//make submission to table
mysqli_query($db,"INSERT INTO people (firstName, lastName, age) VALUES ('Alec', 'Marks',24)");

$result=mysql_query($db,"SELECT * FROM people WHERE firstName="Alec"");

while($it = mysqli_fetch_array($result)){
    echo $it['firstName'];
}

?>

3 个答案:

答案 0 :(得分:2)

启用error_reporting到E_ALL。继续阅读documentation。在此之后,你知道会发生什么。

答案 1 :(得分:1)

Alec不是变量。 还要注意使用mysqli_而不是mysql_来进行查询。

这是一个PHP错误。你应该有这样的东西

$db=mysqli_connect("database","uid","pass", "name");

if (mysqli_connect_errno()){
  echo "no connection: " . mysqli_connect_error();
}
//create table in db
$table="CREATE TABLE people(firstName CHAR(30),lastName CHAR(30),age INT)";
//exc  table query
if(mysqli_query($db,$table)){
    echo "Created  people table " . mysqli_error($db);
} else { 
    echo "No.";
}

//make submission to table
mysqli_query($db,"INSERT INTO people (firstName, lastName, age) VALUES ('Alec', 'Marks',24)");
$name = "Alec";
$result=mysqli_query($db,"SELECT * FROM people WHERE firstName='".$name."'");

while($it = mysqli_fetch_array($result)){
    echo $it['firstName'];
}

?>

以下是我改变的内容:

$name = "Alec";
$result=mysql_query($db,"SELECT * FROM people WHERE firstName='".$name."'");

答案 2 :(得分:0)

包装varchar有一个小问题。

应该是:

$result = mysql_query($db, "SELECT * FROM people WHERE firstName='$name'");

提示:在执行mysql命令以检查错误并打印错误时,我也会高度推荐。

例如:

mysqli_query($db,$table) or die(mysql_error());