I have got this function:
public static function insert_user($user)
{
$con = mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("speakom",$con) or die(mysql_error());
mysql_query("INSERT INTO user (user_ip,user_name,full_name,email_address,password,gender,birthday,banned,role,country)
VALUES('".$user->ip."','".$user->name."','".$user->full_name."','".$user->email."','".$user->password."',".$user->gender.",'".$user->birthday."',".$user->banned.",".$user->role.",'".$user->country."'") or die(mysql_error());
mysql_close($con);
}
And I get this 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 '' at line 2
Where does the error point to ? how do I know where the error is?
You're missing the closing ) from the VALUES ( clause. In general, it's easier to assign your SQL to a variable (which you can output for debugging purposes like this) prior to passing it to mysql_query.
Instead of yelling you should use PDO and prepared statements, here's the answer in PDO style:
$con = new PDO('mysql:host=localhost;dbname=speakom', 'root', ''); // optionally add encoding options
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // enable exception throwing
$stmt = $db->prepare('INSERT INTO user (user_ip, user_name, full_name, email_address, password, gender, birthday, banned, role, country)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
$stmt->execute(array(
$user->ip, $user->name, $user->full_name, $user->email, $user->password,
$user->gender, $user->birthday, $user->banned, $user->role, $user->country,
));
Disclaimer didn't test this, but it should give you a good idea :)
would you run
echo "INSERT INTO user (user_ip,user_name,full_name,email_address,password,gender,birthday,banned,role,country) VALUES('".$user->ip."','".$user->name."','".$user->full_name."','".$user->email."','".$user->password."',".$user->gender.",'".$user->birthday."',".$user->banned.",".$user->role.",'".$user->country."'";
and i advise you to use `user` instead of user
VALUES('".$user->ip."','".$user->name."','".$user->full_name."','".$user->email."','".$user->password."',".$user->gender.",'".$user->birthday."',".$user->banned.",".$user->role.",'".$user->country."'"
You are missing ) at the end. By the way, use PDO or mysqli.
Some of the values you want to insert are not in quote, and you missed the closing ) for VALUES. Try this
mysql_query("INSERT INTO user (user_ip,user_name,full_name,email_address,password,gender,birthday,banned,role,country)
VALUES('$user->ip', '$user->name','$user->full_name', '$user->email', '$user->password', '$user->gender', '$user->birthday', '$user->banned', '$user->role', '$user->country')") or die(mysql_error());
Related
I'm trying to pull information from an HTML form and put this into a database using the following code:
$link = mysqli_connect("localhost", "user", "password", "MyDB");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "INSERT INTO interest (name, email, dob, address)
VALUES ('$fullname', '$email', '$dob' '$addr')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
}else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
It was working, and I've managed to get 2 test runs in, but now I'm getting the following error at the top of my submission page
ERROR: Could not able to execute INSERT INTO MyDB (name, email, dob,
address) VALUES ('test name', 'test#email.com', '2003-02-01'
'address'). Column count doesn't match value count at row 1
I have another variant of this which sends a PHP email, which is the file I'm using to base this database connection on.
There is also an autoincrement on ID column which is set as the primary key in the database if that makes a difference? SQL isn't my strong point unfortunately!
Given the syntax error you have in your query, being a missing comma in '$dob' '$addr'; you are open to an SQL injection and should be using a prepared statement.
Therefore, I am submitting this complementary answer for your own safety.
Here is an example of a prepared statement using the MySQLi API.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect('localhost', 'xxx', 'xxx', 'my_db');
if (!$link) {
die('Connect Error: ' . mysqli_connect_error());
}
// assuming these are the POST arrays taken from your HTML form if you're using one.
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$dob = $_POST['dob'];
$addr = $_POST['addr'];
$sql = ("INSERT INTO interest (name, email, dob, address) VALUES (?, ?, ?, ?)");
$stmt = $link->prepare($sql) or die("Failed Execution");
$stmt->bind_param('ssss', $fullname, $email, $dob, $addr);
$stmt->execute();
echo $stmt->error;
echo "SUCCESS";
exit();
References:
How can I prevent SQL injection in PHP?
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/pdo.prepared-statements
Foonotes:
If using the following failed because of the AI'd column:
$sql = ("INSERT INTO interest (name, email, dob, address) VALUES (?, ?, ?, ?)");
You may also try: (I used id as the AI'd column as an example)
$sql = ("INSERT INTO interest (id, name, email, dob, address) VALUES ('', ?, ?, ?, ?)");
This could be the case, as I have seen this type of SQL failure behaviour before.
You have missed comma here:
VALUES ('$fullname', '$email', '$dob' '$addr')
Thus (as it was clearly said in error text) column count doesn't mach values count.
It should be
VALUES ('$fullname', '$email', '$dob', '$addr')
You missed a comma
$sql = "INSERT INTO interest (name, email, dob, address)
VALUES ('$fullname', '$email', '$dob', '$addr')";
^here
You missed a comma:
VALUES ('$fullname', '$email', '$dob' '$addr')
There are so many questions on SO for failed prepared statements, but I cannot find one which solves my exact problem (or explains it, atleast).
I'm trying to give my users a login-token which is valid for 5 minutes.
When I execute the query through PHPMyAdmin it works just fine:
WORKING QUERY
INSERT INTO LOGGEDIN (userID, loggedInToken, loggedInRefresh) VALUES
(1, "HJKFSJKFDSKLJFLS", ADDTIME(CURTIME(), '00:05:00'));
However, when trying to execute the query through PHP using a prepared statement it fails.
$stmt = $this->conn->prepare("INSERT INTO LOGGEDIN VALUES (userID, loggedInToken, loggedInRefresh) VALUES (?, ?, ADDTIME(CURTIME(), '00:05:00'))");
$stmt->bind_param("is", $userID, $token);
I get the 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 'VALUES (?, ?, ADDTIME(CURTIME(), '00:05:00'))' at line 1
It is the exact same query so I think it's due to how the prepare handles the query.
I've also tried entering the '00:05:00' as a variable because I thought the ' was causing the error but it fails as well.
$five_minutes = '00:05:00';
$stmt->bind_param("iss", $userID, $token, $five_minutes);
When I remove the prepare and use the following query:
$query = "INSERT INTO LOGGEDIN VALUES (userID, loggedInToken, loggedInRefresh) VALUES (" . $userID . ", '" . $token . "', ADDTIME(CURTIME(), '00:05:00'))";
if ($result = $mysqli->query($query)) {
...
It works fine but I would like to keep my code consistent and use a prepared statement everywhere I can.
How can I let this query execute properly using a prepared statement? If all else fails I think I could create the timestamp in PHP and pass it through to the database thus bypassing the whole ADDTIME calculation, but I would like to know what is causing the problem in the first place.
Problems need to be understood, not dodged.
You have a superfluous VALUES on your query:
$stmt = $this->conn->prepare("INSERT INTO LOGGEDIN VALUES (userID, loggedInToken, loggedInRefresh) VALUES (?, ?, ADDTIME(CURTIME(), '00:05:00'))");
^^
Remove that:
$stmt = $this->conn->prepare("INSERT INTO LOGGEDIN (userID, loggedInToken, loggedInRefresh) VALUES (?, ?, ADDTIME(CURTIME(), '00:05:00'))");
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 'Order, Name, URL, UserName, Password, SiteName, Notes) VALUES ('','','','','',' at line 1
The sql is exactly the same as a working insert query; apart from the field/table names.
Here is the code:
<?php
$con = mysqli_connect('HOST', 'USER', 'PASS','DATABASE');
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
$sql="INSERT INTO RemoteLinks (Order, Name, URL, UserName, Password, SiteName, Notes) VALUES('$_POST[Order]','$_POST[Name]','$_POST[URL]','$_POST[UserName]','$_POST[Password]','$_POST[SiteName]','$_POST[Notes]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
header('Location: ' . $_SERVER['HTTP_REFERER']);
mysqli_close($con);
?>
Not too sure why this isnt working as its working in a similar query. Thanks for any help, its appreciated.
ORDER is a reserved word used in order by clause - surround with backticks "`"
Update
Here is a list of Reserved Words in MySQL.
You'd generally want to avoid using backticks to escape those reserved words, because backticks decrease portability of the code. So, you might need to learn those and use other words for column names, tables, databases, etc.
IMPORTANT
You should definitely use mysqli_prepare() and mysqli_stmt_bind_param()!
You need to use back ticks ` for reserved colum names (Order) and Prepare SQL statement for execution and bind params to prevent sql injection:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$insertQuery = 'INSERT INTO RemoteLinks (`Order`, Name, URL, UserName, Password, SiteName, Notes) '.
'VALUES (?, ?, ?, ?, ?, ?, ?)';
if ($stmt = $mysqli->prepare($insertQuery))
{
$stmt->bind_param(
"sssssss",
$_POST['Order'],
$_POST['Name'],
$_POST['URL'],
$_POST['UserName'],
$_POST['Password'],
$_POST['SiteName'],
$_POST['Notes']);
$stmt->execute();
$stmt->close();
}
$mysqli->close();
?>
This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
I'm having a few issues with MySQLi queries. I have read the docs for PHP several times and have encountered the same error. I am new to MySQLi but have used MySQL.
Here is the error I am receiving after submitting the post data:
[22-Mar-2014 23:41:17 UTC] PHP Fatal error: Call to a member function bind_param() on a non-object in /home/ponypwna/public_html/Changelist/cpanel.php on line 32
Here is my code for overviewing:
<?php
$MysqlUsername = "*****";
$MysqlPassword = "*****";
$MysqlHostname = "localhost";
$MysqlDatabase = "ponypwna_mane";
/* Establishing Connection here */
$mysqli = new mysqli($MysqlHostname, $MysqlUsername, $MysqlPassword, $MysqlDatabase) or die("Mysql Error: " . $mysqli->error);
//Did we post it?
if (isset($_POST['insertChange'])) {
#Fetching Post Data
$change = $_POST['change'];
$state = $_POST['state'];
$appliesto = $_POST['appliesto'];
$progress = $_POST['progress'];
$completiondate = $_POST['completiondate'];
$contributor = $_POST['contributor'];
#Preparing Query
$insertChange = $mysqli->prepare("INSERT INTO changelist (change, state, appliesto, progress, completiondate, contributor) VALUES (?, ?, ?, ?, ?, ?)");
$insertChange->bind_param('sssiss', $change, $state, $appliesto, $progress, $completiondate, $contributor);
#Executing Prepared Query
$insertChange->execute();
#Close statement and function
$insertChange->close();
}
?>
We are all dumb :)
Upon second look, I seem to be receiving this error from MySQL
(after adding a few debugging tools I was able to see this 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 'change,
state, appliesto, progress, completiondate, contributor) VALUES (?, ?,
?' at line 1
"change" is a reserved keyword in MYSQL. https://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Add `` arround change (it is a good idea to wrap every column name - there are various reserved keywords):
$insertChange = $mysqli->prepare("INSERT INTO changelist (`change`, state, appliesto, progress, completiondate, contributor) VALUES (?, ?, ?, ?, ?, ?)");
New Answer
It seems the error is being caused due to an error in your sql syntax.
When you do:
$insertChange = $mysqli->prepare("INSERT INTO changelist (change, state, appliesto, progress, completiondate, contributor) VALUES (?, ?, ?, ?, ?, ?)");
and when here is an error in the syntax, $insertChange is set to false and so it has no method called bind_param() as per the documentation here
Return Values
mysqli_prepare() returns a statement object or FALSE if an error occurred.
So a fix would be to copy-past the sql into an phpMyAdmin or whatever and replace the ? with actual data and run it to see if it works. Maybe one of your columns are missing, spelling error?
I am working on a PHP code that would read data from XML store it in MySQL. So far I came to point where I read data from XML file and echo it on website. Here is the code:
<?php
//mysql connection
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("bet_sql") or die(mysql_error());
$xml = simplexml_load_file('http://cachepricefeeds.williamhill.com/openbet_cdn?action=template&template=getHierarchyByMarketType&classId=46&marketSort=MR&filterBIR=N');
foreach ($xml->response->williamhill->class->type as $type) {
$type_attrib = $type->attributes();
$type_attrib['id'];
$type_attrib['name'];
foreach ($type->market as $event) {
$event_attrib = $event->attributes();
$event_attrib['id'];
$event_attrib['name'];
$event_attrib['date'];
$event_attrib['url'];
foreach ($event->participant as $participant) {
$participant_attrib = $participant->attributes();
$participant_attrib['name'];
$participant_attrib['oddsDecimal'];
}
}
mysql_query("INSERT INTO games (type_id, type_name, event_id, event_name, event_url, participant_name, participant_odds)
VALUES ($type_attrib[id], $type_attrib[name], $event_attrib[id], $event_attrib[name], $event_attrib[url], $participant_attrib[name], $participant_attrib[oddsDecimal]) ")
or die(mysql_error());
}
?>
What am I doing wrong with mysql_query? I am geting this message:
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 'Jupiler League, 134465843, Zulte-Waregem v Genk - 75 Minutes Betting, ' at line 2
Thanks for help!
This is a prime example of why you should use a prepared statement to do this. Not only is it faster than running the same INSERT statement over and over, it would avoid the escaping problems and gets you off the obsolete mysql_query function.
I had to guess what datatypes were for bind_param
$msyqli = new mysqli('localhost'...); //Your connection credentials here
$sql = 'INSERT INTO games (type_id, type_name, event_id, event_name, event_url, participant_name, participant_odds)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)';
$prep = $mysqli->prepare($sql);
foreach ($xml->response->williamhill->class->type as $type) {
//Truncated the other code out for example
$prep->bind_param('isissss', $type_attrib[id], $type_attrib[name], $event_attrib[id],
$event_attrib[name], $event_attrib[url], $participant_attrib[name], $participant_attrib[oddsDecimal]);
$prep->execute();
}
Problems with insert query are
Array keys are given without single quotes which will cause warnings
Values are not properly escaped. it may be the main reason of syntax error.
mysql_query("INSERT INTO games (type_id, type_name, event_id, event_name,
event_url, participant_name, participant_odds)
VALUES ($type_attrib['id'], $type_attrib['name'], $event_attrib['id'],
$event_attrib['name'], $event_attrib['url'], $participant_attrib['name'],
$participant_attrib['oddsDecimal'])"
) or die(mysql_error());