更新mySQL查询无效

时间:2014-02-15 10:51:49

标签: php mysql sql database

我一直在做一些学生管理系统,学生登录和注册课程,登录机制在登录后工作正常,显示学生姓名,身份证等,并要求注册课程,当学生选择课程时,所选课程应更新为数据库,提交页面需要从上一页获取学生ID和课程,并相应地更新数据库。

提交后,只更新课程为$ fresh:S

这是submit.php代码:

<?php
$dbhost = 'localhost';
$dbuser = 'username';
$dbpass = '123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}

$fresh = $_REQUEST["fresh"]; 
$user_id= $_REQUEST["user_id"]; 


$sql = 'UPDATE courses
    SET fresh="$fresh"
    WHERE user_id=$user_id';

mysql_select_db('registrations');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
?>

6 个答案:

答案 0 :(得分:3)

试试这段代码。

<?php
    $dbhost = 'localhost';
    $dbuser = 'username';
    $dbpass = '123';
    $database='registrations';
    $conn = mysqli_connect($dbhost, $dbuser, $dbpass,$database);
    if (!$conn || $conn==null) die('Could not connect: ' . mysqli_error($conn));

    $fresh = $_REQUEST["fresh"]; 
    $user_id= $_REQUEST["user_id"]; 


    $sql = "UPDATE courses
        SET fresh='$fresh'
        WHERE user_id=$user_id";

    $retval = mysqli_query($conn, $sql);
    if(! $retval )
    {
      die('Could not update data: ' . mysqli_error($conn));
    }
    else{
    echo "Updated data successfully\n";
    }
    mysqli_close($conn);
    ?>

答案 1 :(得分:1)

这是一个想法:

<?php
$fresh = "test_string";
$user_id = 1;

$sql = 'UPDATE courses SET fresh="$fresh" WHERE user_id=$user_id';

$corrected_sql = "UPDATE courses SET fresh='$fresh' WHERE user_id=$user_id";

echo '<pre>';
echo "\$sql output: $sql" . "\n";
echo "\$corrected_sql output: $corrected_sql";
echo '</pre>';
?>

输出如下:

$sql output: UPDATE courses SET fresh="$fresh" WHERE user_id=$user_id
$corrected_sql output: UPDATE courses SET fresh='test_string' WHERE user_id=1

您可以注意到单引号和双引号之间的区别。希望能帮助到你!

答案 2 :(得分:0)

永远不会解析单引号下的变量。

您的实际查询是这样的..

$sql = 'UPDATE courses SET fresh="$fresh" WHERE user_id=$user_id';
       ^----- This one                        This one ---------^

所以重写它就像

$sql = "UPDATE `courses`
    SET `fresh`='$fresh'
    WHERE `user_id`=$user_id";

答案 3 :(得分:0)

你需要将php变量放在quote

试试这个sql

$sql = "UPDATE courses
    SET fresh='$fresh'
    WHERE user_id='$user_id'";

答案 4 :(得分:0)

删除$ fresh的双引号并尝试使用此功能。

$sql = "UPDATE courses
    SET fresh='$fresh'
    WHERE user_id=$user_id";

答案 5 :(得分:0)

'UPDATE courses
    SET fresh="$fresh"
    WHERE user_id=$user_id';

替换为

"UPDATE `courses`  SET `fresh`='$fresh'  WHERE `user_id`='$user_id' ";