MYSQL Syntax error in php but sql is valid - php

I'm trying to start a transaction is mysql and insert data into the database. The database source sql can be found on github here. Here is the error:
Error: START TRANSACTION; INSERT INTO Books(Title, PublicationDate,
PurchaseDate, Description, LocationID, GenreID) VALUES('Simple
Genius', '2008-4-1','2009-5-7','','Hardbook Library','Fiction'); SET
#bookid = LAST_INSERT_ID(); INSERT INTO BookAuthors(FirstName,
MiddleName, LastName) VALUES('David', '', 'Baldacci'); SET #authorid =
LAST_INSERT_ID(); INSERT INTO AuthorsInBooks(AuthorID, BookID)
VALUES(#authorid, #bookid); COMMIT; 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 'INSERT INTO Books(Title,
PublicationDate, PurchaseDate, Description, LocationID,' at line 3
Near 'INSERT INTO Books(Title, PublicationDate, PurchaseDate, Description, LocationID,' doesn't make sense to me because it is missing GenreID after LocationID. Am i missing something? When I copy and paste this code into phpmyadmin it works fine. My php version is 5.4.
Here is php code:
$sql = "
START TRANSACTION;
INSERT INTO Books(Title, PublicationDate, PurchaseDate, Description, LocationID, GenreID)
VALUES('".$Title."', '".$YearWritten."','".$YearPurchased."','".$Description."','".$Location."','".$Genre."');
SET #bookid = LAST_INSERT_ID();
INSERT INTO BookAuthors(FirstName, MiddleName, LastName)
VALUES('".$AuthFirstName."', '".$AuthMiddleName."', '".$AuthLastName."');
SET #authorid = LAST_INSERT_ID();
INSERT INTO AuthorsInBooks(AuthorID, BookID)
VALUES(#authorid, #bookid);
COMMIT;
";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);

mysqli_query() can only execute 1 query, if you want to execute multiple queries, you need:
if (mysqli_multi_query($conn, $sql)) {

In response to your comment "Can I see an example of what you mean #eggyal ?":
// mysqli provides API calls for managing transactions
mysqli_autocommit($conn, false);
// parameterise variables - NEVER concatenate them into dynamic SQL
$insert_book = mysqli_prepare($conn, '
INSERT INTO Books
(Title, PublicationDate, PurchaseDate, Description, LocationID, GenreID)
VALUES
(?, ?, ?, ?, ?, ?)
');
// bind the variables that (will) hold the actual values
mysqli_stmt_bind_param(
$insert_book,
'siisss', // string, integer, integer, string, string, string
$Title, $YearWritten, $YearPurchased, $Description, $Location, $Genre
);
// execute the statement (you can change the values of some variables and
// execute repeatedly without repreparing, if so desired - much faster)
mysqli_stmt_execute($insert_book);
// mysqli provides API calls for obtaining generated ids of inserted records
$book_id = mysqli_insert_id($conn);
// ... etc ...
// use the API call to commit your transaction
mysqli_commit($conn);
// tidy up
mysqli_stmt_close($insert_book);
Note that I've not included above any error detection/handling, which you'd certainly want to include in any real-world code.

Related

Errors inserting values (such as URLs) into MySQL database WITH a URL

I am working on my website and I can't access myPhpAdmin right now, so I tried making a script for inserting values for a search thing. However, when I visit the link, website.com/search/create.php?l=link&d=description&t=title, I get an error. This one
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 'link, description, title)' at line 1
Here's what my script looks like.
$link = "https://website.com";
$description = "The homepage of the site";
$title = "Home";
// sql to create table
$sql = "INSERT INTO search (link, description, title) VALUES (".$link.", ".$description.", ".$title.")";
if (mysqli_query($conn, $sql)) {
echo "it's working";
} else {
echo "it's not working?" . mysqli_error($conn);
}
replace
$sql = "INSERT INTO search (link, description, title) VALUES ('".$link."', '".$description."', '".$title."')";
instead of :
$sql = "INSERT INTO search (link, description, title) VALUES (".$link.", ".$description.", ".$title.")";
you are trying to insert a string without '
it seems you are missing single quotation in SQL query, try the following:-
$sql = "INSERT INTO search (link, description, title) VALUES ('".$link.", '".$description."', '".$title."')";
Just Change the Query syntax in your code and check it ... Hope your error should be resolve.
// sql to create table
$sql = "INSERT INTO search (link, description, title) VALUES ('$link', '$description', '$title')";
Your code for inserting data into database table is wrong (assuming you already executed database connection query ($conn) and have 'search' table on database).
$sql = "INSERT INTO search (link, description, title) VALUES ('$link', '$description', '$title')";
You don't have to put concatenate operator ('.') inside your SQL query as you are not concatenating PHP and markup texts.

insert...on duplicate key update does not work with php, but works directly on MySQL

$sql = "SET #tag_name = '$tag_value',
#tag_link = '$tag_link',
#user_value = '$user_value';
INSERT INTO urls_unis
(tag_name, tag_link, user_data)
VALUES
(#tag_name, #tag_link, #user_value)
ON DUPLICATE KEY UPDATE
tag_name = #tag_name,
tag_link = #tag_link,
user_data = #user_value;
";
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
The above code is returning this:
ERROR: Could not able to execute
SET #tag_name = 'View history', #tag_link = 'zNIL', #user_value = '/w/index.php?title=Non-volatile_random-access_memory&action=history'; INSERT INTO urls_unis (tag_name, tag_link, user_data) VALUES (#tag_name, #tag_link, #user_value) ON DUPLICATE KEY UPDATE tag_name = #tag_name, tag_link = #tag_link, user_data = #user_value; .
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 'INSERT INTO urls_unis (tag_name, tag_link, user_data) VALUES (#tag_name,' at line 4
When I copy and paste the mysql query to phpmyadmin to execute it, it works fine. No errors were returned.
How come, and how can I solve this?
You can't run multiple querylines in a single query. You need to run them separately or use mysqli_multi_query(). You can avoid all that by just using your variables, without going through the route of setting the MySQL variables first.
Better yet, you would use a prepared statement instead of injecting your variables directly into the query. Because you're using the values twice, and that MySQLi doesn't support named placeholders, we have to bind each variable twice.
$sql = "INSERT INTO urls_unis (tag_name, tag_link, user_data)
VALUES
(?, ?, ?)
ON DUPLICATE KEY UPDATE
tag_name = ?,
tag_link = ?,
user_data = ?;";
$stmt = $link->prepare($sql);
$stmt->bind_param("ssssss", $tag_value, $tag_link, $user_value,
$tag_value, $tag_link, $user_value);
if ($stmt->execute()){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql<br />";
echo $stmt->error;
}
$stmt->close();
When should I use prepared statements?

mysqli prepared statement with ADDTIME CURTIME fails

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'))");

SQL INSERT fails even if the new row is in the DB?

I'm using mysqli in a PHP class.
I have this query to be executed:
INSERT INTO notifications (userid, content, uniq, link) VALUES (48, "[2014-07-30] Nomid has edited the post \"Somepost\"", "934512e1e9314d9c602a02a26114a625", "http://website/somepost")
It fails, showing the error:
You have an error in your query etc. to use near '"[2014-07-30] Nomid has edited the post \"Somepost\"", "934512e1e9314d9"'
But if I look in the DB, the new row is present.
The parameters are escaped using mysqli_real_escape_string():
$msg = $this->escape($msg);
$uniqid = $this->escape($uniqid);
$sql = "INSERT INTO notifications (userid, content, uniq, link) VALUES ($userid, \"$msg\", \"$uniqid\", \"$link\")";
// die($sql);
$this->query($sql);
I tried to check query execution with $mysqli->affected_rows and !$result of mysqli_query().
The fields types are
INT (11) for userid,
TEXT for content,
TINYTEXT for uniq and
TINYTEXT for link.
All of the TEXT fields have collation "utf8_general_ci".
I didn't create the table.
The strange thing is that if I look in the database, the query was successfully executed...
Why is this happening?
you sql should be like
$userid = $this->escape($userid);
$msg = $this->escape($msg);
$uniqid = $this->escape($uniqid);
$link = $this->escape($link);
$sql = "INSERT INTO notifications (userid, content, uniq, link) VALUES ('$userid', '$msg', '$uniqid', '$link')";

PHP - XML to MySQL

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());

Categories