PHP - MySQL 从表中选择数据,然后更新同一张表 [英] Php - MySQL select data from table, then update the same table
问题描述
这段代码有什么问题?
$sql=mysql_query("SELECT * FROM table WHERE id='$id'");
if($data=mysql_fetch_array($sql))
{
$count=$data['count'];
$new_count=$count+1;
$sqla="UPDATE table SET count='$new_count' WHERE id='$id'";
if(mysql_query($sqla))
{
echo "success";
}
除了 UPDATE 查询外,一切正常.
Everything is working fine except UPDATE query.
当我添加一个
echo $new_count;
它返回正确的值.
推荐答案
首先:
在您的第二个 SQL 查询中:
In your second SQL query:
$sqla="UPDATE table SET count='$new_count'";
您需要指定要更新的行/行.为此,您必须使用 WHERE
子句.
you need to specify, which row/rows you want to update. For this you must use WHERE
clause.
例如:
$sqla="UPDATE table SET count='$new_count' WHERE id='$id'";
作为第二个:
您的条件中缺少 }
,这也可能是问题所在.如果我将您的代码隔开,它看起来像:
You have missing }
in your condition, which can be the problem too. If I will space your code, it will looks like:
$sql=mysql_query("SELECT * FROM table WHERE id='$id'");
if($data=mysql_fetch_array($sql))
{
$count=$data['count'];
$new_count=$count+1;
$sqla="UPDATE table SET count='$new_count' WHERE id='$id'";
if(mysql_query($sqla))
{
echo "success";
}
您的条件(从第二行开始)是否以 }
结尾?
Is your condition (started at second line) ended with }
correctly?
作为第三个:
将 mysql_fetch_array
和 mysql_query
的输出保存到一个变量中,然后在你的条件中使用这个变量:
Save output of mysql_fetch_array
and mysql_query
to a variable and then use this variable in your conditions:
$data = mysql_fetch_array($sql);
if($data) { ...
和
$result = mysql_query($sqla);
if($result) { ...
<小时>
脚注:
不知道您使用的表名是否确实称为table
.
It is unknown whether or not the table name you are using is indeed called table
.
如果是,那么它是一个 MySQL 保留字,需要特别注意,例如将其包裹在刻度中或将其命名为保留字以外的其他名称.
If it is, then that is a MySQL reserved word and it requires special attention, as in wrapping it in ticks or naming it to something other than a reserved word.
即:
SELECT * FROM `table`
和
UPDATE `table`
参考:
这篇关于PHP - MySQL 从表中选择数据,然后更新同一张表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!