Richard Richard - 5 months ago 8
SQL Question

PHP/MYSQL edit profile function - wrong query syntax?

I am trying to allow a user to edit their user descriptions on their profiles. I am coming upon this error however and cannot understand why. As far as i looked at different answers on stack overflow i am using the correct syntax for the query but it still returns false where it should save what the user wrote in the form:

'use near WHERE user_id=1' at line 4'


I am not experienced enough yet to be able to understand every sql syntax error. I am trying to learn both php and sql so a lot of detail is more than welcome for the explanation.

Here is the query to save you time looking for it in the code:

$id = $_SESSION['user_id'];
$descrip =$_SESSION['user_description'];

//Save changes

$sql ='UPDATE users
SET user_description='.mysqli_real_escape_string($link,$descrip).'
WHERE user_id='.mysqli_real_escape_string($link, $id);


This is the editdetail.php file.

<?php
include 'connect.php';
include 'header.php';

?>
<?php
// default Avatar picture if "avatar" column empty.
if(empty($_POST['user_avatar']) )
{
$avatar = 'Images/default.jpg';
}
else
{
$avatar = $_POST['user_avatar'];
}
if(empty($_POST['user_description']) )
{
$description = 'Edit your description to let people know more about you!';
}
else
{
$description = $_POST['user_description'];
}
// check if user is signed in
if(!isset($_SESSION['signed_in']))
{
//the user is not signed in.
echo '<a href="/Latest_try/signin.php">Sign in</a> to view your profile.';
}
else
{
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
echo '<div id="LeftCol"><div id="Photo"> <img src="'.$avatar.'" width="205" height="205"></div>
<div id="ProfileOptions"> Usersince: '.$_SESSION["user_date"].'<br/>
<a href="editavatar.php">Edit avatar</a></div></div>
<div id="rightpart"> <div id="Info">
<span><a href="editdetails.php">Edit Details</a></span>
<p><strong>Username: '.$_SESSION["user_name"].' </strong></p>
<p><strong>Email: '.$_SESSION["user_email"].' </strong></p>
<p><strong><u>Description</u>: </strong></p>
<p> '.$description.' </p>
<form method="post" action="">
<br /><u>Edit description</u>:<br /><br /><textarea name="user_description" /></textarea><br />
<input type="submit" value="Update description" />
</form>
</form>
</div>
</div>
</html>';
}
else
{
$id = $_SESSION['user_id'];
$descrip =$_SESSION['user_description'];
//Save changes
$sql ='UPDATE
users
SET user_description='.mysqli_real_escape_string($link,$descrip).'
WHERE user_id='.mysqli_real_escape_string($link, $id);


$result = mysqli_query($link,$sql);
if(!$result)
{
//something went wrong, display the error
echo 'Error' . mysqli_error($link);
}
else
{
echo 'Description updated.';
}
}
}

Answer

You have to use single quotes arround strings in mysql:

 "UPDATE
            users 
        SET user_description='".mysqli_real_escape_string($link,$descrip)."'
        WHERE user_id=".$id;

But much more better is to learn about prepared Statements.

Comments