scarecrow scarecrow - 2 months ago 11
MySQL Question

unepected syntax error for mariadb(xampp)

<?php

// 1. create a database connection

$dbhost = "localhost" ;
$dbuser = "widget_cms";
$dbpass = "secretpassword";
$dbname = "widget_corp";

$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);

// test if connection occured
if(mysqli_connect_errno())
{
die("database connection failed:". mysqli_connect_error() .
" " . mysqli_connect_errno() . " " );
}


?>

<?php
//often these are $_POST values through a web form.
// 2. Perform the database query

$id = 5;
$menu_name = "delete me";
$position = 4;
$visible = 1;

$query = "UPDATE subjects SET ";
$query .= "menu_name = '{ menu_name}', ";
$query .= "position = {$position}, ";
$query .= "visible = {$visible}, ";
$query .= "WHERE id = {$id} ";

$result = mysqli_query($connection, $query);

if ($result)
{
//success
//redirect to somepage.php
echo "success!";
}
else
{
//failure
//$message = "subjet update failed.";
die("database query failed. " . mysqli_error($connection));
}
?>

<DOCTYPE HTML>
<head>
<title> databases </title>
</head>

<body>



</body>

</html>


<?php
// 5. close the database connection
mysqli_close($connection);
?>


When i try to run this page in firefox,this is the error that pops up.
And i don't know how to solve it. please help!

"database query failed. You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE id = 5' at line 1"

TYSM. :)

Answer

things need to change:-

1.

if (mysqli_connect_error()) {
  die('Database connection failed: '  . mysqli_connect_error()); // remove second  mysqli_connect_error()
}

2.

 $query .= "menu_name = '{ $menu_name}', "; // $ missed

3.

$query .= "visible = {$visible} "; // remove trailing `,`

Note:- This is not the end, lot of improvement can be done in your code.