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());
Related
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.
I am trying to insert data into a database after the user clicks on a link from file one.php. So file two.php contains the following code:
$retrieve = "SELECT * FROM catalog WHERE id = '$_GET[id]'";
$results = mysqli_query($cnx, $retrieve);
$row = mysqli_fetch_assoc($results);
$count = mysqli_num_rows($results);
So the query above will get the information from the database using $_GET[id] as a reference.
After this is performed, I want to insert the information retrieved in a different table using this code:
$id = $row['id'];
$title = $row['title'];
$price = $row['price'];
$session = session_id();
if($count > 0) {
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
The first query $retrieve is working but the second $insert is not. Do you have an idea why this is happening? PS: I know I will need to sanitize and use PDO and prepared statements, but I want to test this first and it's not working and I have no idea why. Thanks for your help
You're not executing the query:
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
it needs to use mysqli_query() with the db connection just as you did for the SELECT and make sure you started the session using session_start(); seeing you're using sessions.
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
$results_insert = mysqli_query($cnx, $insert);
basically.
Plus...
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
If that still doesn't work, then MySQL may be complaining about something, so you will need to escape your data and check for errors.
http://php.net/manual/en/mysqli.error.php
Sidenote:
Use mysqli_affected_rows() to check if the INSERT was truly successful.
http://php.net/manual/en/mysqli.affected-rows.php
Here's an example of your query in PDO if you'req planning to use PDO in future.
$sql = $pdo->prepare("INSERT INTO table2 (id, title, price, session_id) VALUES(?, ?, ?, ?");
$sql->bindParam(1, $id);
$sql->bindParam(2, $title);
$sql->bindParam(3, $price);
$sql->bindParam(4, $session_id);
$sql->execute();
That's how we are more safe.
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 used this code
<?php
$conn = new PDO("mysql:host=localhost;dbname=CU4726629",'CU4726629','CU4726629');
$sql="INSERT INTO review (username, movie_name, ratings) VALUES ("$_POST['username']","$_POST['moviename']","$_POST['ratings']")";
header('Location: reviews.php');
?>
but it keeps giving me this error
Parse error: syntax error, unexpected T_VARIABLE in
/home/4726629/public_html/check_login.php on line 5
Take this for an example:
<?php
// insert some data using a prepared statement
$stmt = $dbh->prepare("insert into test (name, value) values (:name, :value)");
// bind php variables to the named placeholders in the query
// they are both strings that will not be more than 64 chars long
$stmt->bindParam(':name', $name, PDO_PARAM_STR, 64);
$stmt->bindParam(':value', $value, PDO_PARAM_STR, 64);
// insert a record
$name = 'Foo';
$value = 'Bar';
$stmt->execute();
// and another
$name = 'Fu';
$value = 'Ba';
$stmt->execute();
// more if you like, but we're done
$stmt = null;
?>
You just wrote a string in your above code:
$sql="INSERT INTO review (username, movie_name, ratings) VALUES ("$_POST['username']","$_POST['moviename']","$_POST['ratings']")";
Above answers are correct, you will need to concat the strings to form a valid sql query. you can echo your $sql variable to check what is to be executed and if is valid sql query or not. you might want to look in to escaping variables you will be using in your sql queries else your app will be vulnerable to sql injections attacks.
look in to
http://php.net/manual/en/pdo.quote.php
http://www.php.net/manual/en/pdo.prepare.php
Also you will need to query you prepared sql statement.
look in to http://www.php.net/manual/en/pdo.query.php
A couple of errors:
1) you have to concat the strings!
like this:
$sql="INSERT INTO review (username, movie_name, ratings)
VALUES (".$_POST['username'].",".$_POST['moviename'].",".$_POST['ratings'].")";
2) you are not using the PDO at all:
after you create the "insert" string you must query the db itself, something like using
$conn->query($sql);
nb: it is pseudocode
3) the main problem is that this approach is wrong.
constructing the queries in this way lead to many security problems.
Eg: what if I put "moviename" as "; drop table review;" ??? It will destroy your db.
So my advice is to use prepared statement:
$sql="INSERT INTO review (username, movie_name, ratings)
VALUES (?,?,?)";
$q = $conn->prepare($sql);
$fill_array = array($_POST['username'], $_POST['moviename'], $_POST['ratings']);
$q->execute($fill_array);
You forgot dots:
$sql="INSERT INTO review (username, movie_name, ratings)
VALUES (".$_POST['username'].",".$_POST['moviename'].",".$_POST['ratings'].")";
and fot the future for now your variables are not escaped so code is not secure
String in a SQL-Statment need ', only integer or float don't need this.
$sql="INSERT INTO review (username, movie_name, ratings) VALUES ('".$_POST['username']."','".$_POST['moviename']."','".$_POST['ratings']."')";
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());