在WHERE子句中使用变量 [英] Using a variable in the WHERE Clause

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

问题描述

我是MySQL和PHP的新手.我有一个HTML表单,我想将1变量从该表单传递到我的PHP代码,然后在数据库上运行查询,以获取将变量保存在序列"列下的记录.当我对要查找的序列"进行硬编码时,我可以很好地运行它,但是当我尝试使用变量时,我得到了一个错误.

I am a newbie in MySQL and PHP. I have a HTML form where I would like to pass 1 variable from to my PHP code and then run a query on my database for the record that holds that variable under the column 'Serial'. I can run it fine when I hard code the 'serial' that I want to look up but when I try with the variable I get an error.

任何帮助将不胜感激!或者是更好的方法.

Any help would greatly be appreciated! Or a better way to do this.

这是我的错误:Unknown column 'amg002' in 'where clause'

这是我的代码;

$serial= $_POST['Serial'];
echo $serial;

//Connect To Database

$link = mysql_connect($hostname,$username, $password) OR DIE ('Unable to connect to database! Please try again later.');
echo "Connected to MySQL<br />";

//Select the database - 'SiteInfo'

// Collects data from "SiteInfo" table

//****This is where I am running into the error*** 

$sql = 'SELECT * FROM `SiteInfo` WHERE `Serial` ='.$serial; 

// This works!!!

//$sql = 'SELECT * FROM `SiteInfo` WHERE `Serial` ="amg002";';   

$data = mysql_query($sql)
or die(mysql_error());

// puts the "SiteInfo" info into the $info array

$info = mysql_fetch_array( $data );

//Print out the contents of the entry

echo "Site Name: ".$info['SiteName'] . "<br /";
Print "Serial Number: ".$info['Serial'] . "<br />";
Print "Location: ".$info['Location'] . "<br />";

// Close the database connection

mysql_close($link); 
echo "Connection Closed. <br />";

推荐答案

我同意其引用问题,但这是我的代码的外观.

I agree its a quote issue, but here is how my code would look.

  $sql = 'SELECT * FROM SiteInfo WHERE Serial = "' . $serial . '"';

  $sql = "SELECT * FROM 'SiteInfo; WHERE 'Serial' = \"$serial\"";      

这篇关于在WHERE子句中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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