The code below is giving an error.The query alone is working fine on phpmyadmin directly but but in my php code:
Database Error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\'to\',\' message\',\'from\')' at line.. but i cannot figure out why?
<?php
$con = mysqli_connect("localhost","","","");
if (!$con)
{
echo" Not connected to database";
die('Could not connect: ' . mysqli_error());
}
if(isset($_POST['submit'])){
$username=$_SESSION["username"];
$sql = "INSERT INTO `dbase.mail`(`Date`, `to`, `message`, `from`) VALUES (CURDATE(),\'$_POST[username1]\',\'$_POST[message]\',\'$username\')";
$xy=mysqli_query($con,$sql);
if (!$xy)
{
die('Database Error ' . mysqli_error($con));
}
echo "Your message is stored";
}
Several problems:
You must delimit the database name and table separately.
INSERT INTO `dbase`.`mail` -- RIGHT
not this:
INSERT INTO `dbase.mail` -- WRONG
You don't need to backslash single-quotes inside a double-quoted string.
$string = "that's the way"; -- RIGHT
not this:
$string = "that\'s the way"; -- WRONG
The error message suggests that you are using straight single-quotes to delimit your columns, not back-ticks.
INSERT INTO `dbase`.`mail`(`Date`, `to`, `message`, `from`) -- RIGHT
not this:
INSERT INTO 'dbase.mail'('Date', 'to', 'message', 'from') -- WRONG
You must not interpolate $_POST variables directly into your SQL! This will allow hackers to attack your website easily. See What is SQL injection? and How can I prevent SQL injection in PHP?
This is not the source of the error you asked about in this question, but it's a security practice you must learn how to handle properly before you put your code on the internet. If you were an electrician, this is analogous to safe wiring to prevent fires.