在where子句中使用php变量时,MySQL查询无法正常工作 [英] MySQL query not working while using php variable in where clause

查看:54
本文介绍了在where子句中使用php变量时,MySQL查询无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是PHP和MySQL的新手.我正在尝试制作一个简单的搜索表单,我希望使用该表单基于在表单中输入的输入文本来显示数据库的结果. 我的代码是这样的:

I'm new to PHP and MySQL. I am trying to make a simple search form using which I would want to show the results from the database based on the input text entered in the form. My code is like this:

Form.php

<!DOCTYPE html>
<html lang="en">
<html>
<head>
<title>test</title>
</head>
<body>
<form action="search.php" method="GET" id="form">
Name: <input type="text" name="name" >
Age:<input type="text" name="age">
Search<input type="submit" name="submit" id="Search" Value="Search">

</form>

</body>
</html>

Connect.php

Connect.php

  <?php
  $connect = mysql_connect('localhost','$user','$password'); 

  if(!$connect){
die('Could not connect'.mysql_error() );  
  }

  $db_selected = mysql_select_db('test');  

  if(!$db_selected){
die('wrong'.mysql_error() );
  }

  ?>

Search.php

Search.php

 <?php
  include("includes/connect.php");

  $name=$_GET['name'];


  echo $name;

  $query = "SELECT * FROM `cats` WHERE name='\$name'";
  $results= mysql_query($query);


  if (!empty($results)){
echo "query successful" ;
exit;
   }
  $row=mysql_fetch_assoc($results);
  echo "Age:".$row['age'];
  echo "Name:".$row['name'];
 ?>

echo $names正确输出结果,echo "query successful"也正确. 但是

The echo $names ouputs the result correctly and so does echo "query successful". However the

echo "Age:".$row['age']; 
echo "Name:".$row['name'];

仅echo是字符串部分,查询似乎未获取任何结果.

only echo's the string part and the query does not seem to fetch any results.

我尝试将mysql_fetch_asso c更改为mysql_fetch_array,但是它也不执行任何操作.谁能告诉我我在做什么错.我的数据库表有两列两行.

I tried changing the mysql_fetch_assoc to mysql_fetch_array, but it does not do anything either. Could anyone tell me what am i doing wrong here. My DB table has two columns and two rows.

推荐答案

您正在通过执行\$来转义变量中的$. 试试:

You're escaping the $ in the variable by doing \$. Try:

$query = "SELECT * FROM `cats` WHERE name='$name'";

编辑

来自下面的讨论.

undefined index的问题是,实际上您正在使用$row['age']的事实是,数据库中的列名是Age.因此,在引用该项目时必须使用$row['Age']. name也是如此.

The problem with the undefined index is the fact that you are using $row['age'] when really, the column name in the database is Age. Therefore you must use $row['Age'] when referring to the item. The same goes for name.

这篇关于在where子句中使用php变量时,MySQL查询无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆