2013-04-10 59 views
0

嗨,给大家的程序员。如果输入值低于db中的值,我想在我的数据库中禁用表更新。代码看起来不错,但更新总是执行。这是我的代码:使用PHP进行检查应该完成表更新

$sql="UPDATE student SET _id_year='$_year' WHERE _index='$_index'"; 
$check1="SELECT _id_year FROM student WHERE _index='$_index'"; 

if('$_year'>'$check1') 
{ 
mysqli_query($con,$sql); 
} 

注:_id_year和_index是从DB值,并$_year$_index输入值。 $con是连接到数据库。

+1

您当然需要先学习基础知识。为什么不尝试一些教程?至少从数据库获取数据。 – 2013-04-10 15:24:15

回答

2

首先执行您的选择查询并获得$check1。然后比较。

$qry = "SELECT _id_year FROM student WHERE _index='$_index'"; 
$exec = mysqli_query($con,$qry); 
$result = mysqli_fetch_object($result); 
$check1 = $result->_id_year ; 

而且,你不必使用单引号。试试这个,

if($_year > $check1) 
{ 
    mysqli_query($con,$sql); 
} 
+0

这个答案toooooooo hasty – 2013-04-10 15:23:11

+0

@YourCommonSense实现并编辑答案 – 2013-04-10 15:26:41

+0

我不知道为什么,但就像在我的情况下,更新始终执行... – 2013-04-10 16:07:13

0

你应该先执行$check1查询,得到它的结果,然后将它与你比较$_year变量

-1

这是因为你的PHP的报价领域它不应该被qouted的总是正确的

if($_year>$check1) 
{ 
mysqli_query($con,$sql); 
} 
1

使用SafeMysql为你写的代码将几乎相同,但它实际上运行这些查询,也使其安全

$check=$db->getOne("SELECT _id_year FROM student WHERE _index=?s",$_index); 

if($_year > $check) 
{ 
    $db->query("UPDATE student SET _id_year=?s WHERE _index=?s",$_year,$_index); 
}