我刚刚为mysql数据库写了一个更新查询。问题既不是它显示任何mysql错误也不是更新行。 my_sql_rows总是输出false,这意味着我的tabe中没有更新任何内容 代码如下
if(isset($_POST['update_subject']))
{
$id = $_POST['id'];
$menu_name = $_POST['menu_name'];
$visible = $_POST['visible'];
$position = $_POST['position'];
$content = $_POST['content'];
mysql_query("UPDATE subjects SET menu_name ='$menu_name', visible = $visible, position = $position,
content = '$content' WHERE id = $id ")
or die("updation of '$menu_name' in table subjects failed due to : " . mysql_error ());
if(mysql_affected_rows == 1 ) {
echo "Updation of '$menu_name' in table subjects is done successfully !!! ";
} else {
echo "something went wrong. updation process is halted.";
}
}
它总是让我回答“出了问题。更新过程停止了” 我知道mysql命令已经过时但我仍然想学习。 thanx!
答案 0 :(得分:3)
Ita因为您使用了禁止在if语句中加入括号的禁忌做法,除了需要函数后的括号
if(mysql_affected_rows() == 1 ){
echo "Updation of '$menu_name' in table subjects is done successfully !!! ";
}
else{
echo "something went wrong. updation process is halted.";
}
答案 1 :(得分:2)
mysql_affected_rows
是函数,因此你需要使用括号:
$result = mysql_query($yourquery);
if(mysql_affected_rows($result) === 1) {
// logic
}
现在开始使用弃用垃圾邮件......
ext/mysql
should not be used for new projects:
从PHP 5.5.0开始,不推荐使用此扩展,不建议用于编写新代码,因为将来会删除它。相反,应该使用mysqli或PDO_MySQL扩展。另请参阅MySQL API概述,以便在选择MySQL API时获得进一步的帮助。
答案 2 :(得分:1)
一切事,
UPDATE
查询需要在列值周围添加'
引号(如果它们是字符串)。所以检查查询。
mysql_query("UPDATE subjects SET menu_name ='$menu_name', visible = '$visible', position = '$position', content = '$content' WHERE id = '$id' ")
mysql_affected_rows
是一个函数,所以它必须是
if(mysql_affected_rows() == 1 )
注意:不推荐使用Mysql_ *扩展程序。如果可能,请使用Mysqli
或PDO
。
答案 3 :(得分:1)
如果您想使用PDO +更干净的代码,请尝试:
<?php
try {
$db = new PDO("mysql:host=127.0.0.1;dbname=databasename", 'dbuser', 'dbpassword');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}catch (Exception $e){
die('Cannot connect to mySQL server.');
}
if($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['update_subject'])){
if(!empty($_POST['id'])){
$sql = "UPDATE subjects SET menu_name = :menu_mame,
visible = :visible,
position = :position,
content = :content
WHERE id = :id";
$update = array(':menu_name'=>$_POST['menu_name'],
':visible'=>$_POST['visible'],
':position'=>$_POST['position'],
':content'=>$_POST['content'],
':id'=>$_POST['id']);
$query = $db->prepare($sql);
$query->execute($update);
$affected = $query->rowCount();
if($affected > 0 ){
echo htmlspecialchars($_POST['menu_name'])." updated successfully !!!";
}else{
echo "Something went wrong or no rows were found tobe updated";
}
}
}
?>