更新mySQL查询无效

I have been working on some student management system where student login and register courses, login machanism works fine after login it display student name, id etc and ask to register courses, when student select courses, the selected courses should be updated to database, that submit page need to get student id and courses from previous page and update the database accordingly.

After submitting it only update courses as $fresh :S

Here's submit.php code:

<?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
";
mysql_close($conn);
?>

Variables under single quotes will never be parsed.

Your actual query was like this..

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

So rewrite it like

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

you need to put the php variables in quote

try this sql

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

Remove double quotes of $fresh and try with this.

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

replace it with

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

Here is the idea:

<?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" . "
";
echo "\$corrected_sql output: $corrected_sql";
echo '</pre>';
?>

The output is like this:

$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

You can notice how the difference between single and double quotes. Hope it helps!

try this code of block.

<?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
";
    }
    mysqli_close($conn);
    ?>