I'm getting a non-descriptive syntax error on a MYSQL query from PHP. If I "echo" the text of the query and paste it into a MySQL query window, the code works. Here is the SQL for the query, the error code, and the error message...
INSERT INTO ADVERTISEMENTS (`user_id`, `ad_name`, `click_url`, `img_url`, `bg_color`, `start_date`, `end_date`, `timer_delay`, `add_date`) VALUES (2, 'Test New Ad', 'http://www.google.com', 'red_arrow.png', '#000000', '1980-05-11 00:00:00', '2020-05-01 00:00:00', 5, '2013-07-14 22:21:59');
Error Code: 1064
Error Msg: 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 1
Here is the PHP code I am using...
$link = mysqli_connect($UM_Settings["database_options"]["server_name"], $UM_Settings["database_options"]["username"], $UM_Settings["database_options"]["password"], $UM_Settings["database_options"]["database_name"]);
$advertisementNameNew = mysqli_real_escape_string($link, $_POST['advertisementNameNew']);
$destinationURLNew = mysqli_real_escape_string($link, $_POST['destinationURLNew']);
$dropboxUploadFile = mysqli_real_escape_string($link, $_POST['dropboxUploadFile']);
$backgroundColorNew = mysqli_real_escape_string($link, $_POST['backgroundColorNew']);
$bannerStartDateNew = DateStringToMySQL($_POST['bannerStartDateNew']);
$bannerEndDateNew = DateStringToMySQL($_POST['bannerEndDateNew']);
$bannerSetTimerNew = intval($_POST['bannerSetTimerNew']);
$tmpUserID = UM_GetCookie("UM_UserID");
$tmpAddDate = DateStringToMySQL('now');
echo "INSERT INTO ADVERTISEMENTS(`user_id`, `ad_name`, `click_url`, `img_url`, `bg_color`, `start_date`, `end_date`, `timer_delay`, `add_date`) VALUES ($tmpUserID, '$advertisementNameNew', '$destinationURLNew', '$dropboxUploadFile', '$backgroundColorNew', '$bannerStartDateNew', '$bannerEndDateNew', $bannerSetTimerNew, '$tmpAddDate');<br />";
if (!mysqli_query($link, "INSERT INTO ADVERTISEMENTS(`user_id`, `ad_name`, `click_url`, `img_url`, `bg_color`, `start_date`, `end_date`, `timer_delay`, `add_date`) VALUES ($tmpUserID, '$advertisementNameNew', '$destinationURLNew', '$dropboxUploadFile', '$backgroundColorNew', '$bannerStartDateNew', '$bannerEndDateNew', $bannerSetTimerNew, '$tmpAddDate');")) {
printf("Error Code: %s\n", mysqli_errno($link));
echo "<br />";
printf("Error Msg: %s\n", mysqli_error($link));
}
I know that the database connection is working. I am able to select and update tables. I can also insert into other tables with different queries.
I am open to any suggestions.
Thank you in advance for your help!
I see a few errors in your query strings.
First, all your variables are passed as literal strings: "... VALUES ($tmpUserID, '$advertisementNameNew', ..." should be "... VALUES (".$tmpUserID.", '".$advertisementNameNew."', ...".
Second, I see missing quotes around $bannerSetTimerNew.
Third, there is an extra ;.
here's how I would write the query:
if (!mysqli_query($link, "INSERT INTO ADVERTISEMENTS (user_id, ad_name, click_url, img_url, bg_color, start_date, end_date, timer_delay, add_date) VALUES (".$tmpUserID.", '".$advertisementNameNew."', '".$destinationURLNew."', '".$dropboxUploadFile."', '".$backgroundColorNew."', '".$bannerStartDateNew."', '".$bannerEndDateNew."', '".$bannerSetTimerNew."', '".$tmpAddDate."')")) { ...
I didnt test it though.
hope this helps.
I see a ; at the end of the query. Are you sure that should be there?
There are two things
1. Remove the ; from at the end of the query.
2. I hope timer_delay field has datatype "Int" if its a VARCHAR then you will have to include quotes for that field value.
I hope this will help.
Passerby, thank you for your comment. This was my first experience with using mysqli, I changed my query to use the "bind_param" method, and everything works now. For anyone else with a similar problem, here is the corrected code...
$mysqli = new mysqli($UM_Settings["database_options"]["server_name"], $UM_Settings["database_options"]["username"], $UM_Settings["database_options"]["password"], $UM_Settings["database_options"]["database_name"]);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$advertisementNameNew = $_POST['advertisementNameNew'];
$destinationURLNew = $_POST['destinationURLNew'];
$dropboxUploadFile = $_POST['dropboxUploadFile'];
$backgroundColorNew = $_POST['backgroundColorNew'];
$bannerStartDateNew = DateStringToMySQL($_POST['bannerStartDateNew']);
$bannerEndDateNew = DateStringToMySQL($_POST['bannerEndDateNew']);
$bannerSetTimerNew = intval($_POST['bannerSetTimerNew']);
$tmpUserID = UM_GetCookie("UM_UserID");
$tmpAddDate = DateStringToMySQL('now');
/* Prepared statement, stage 1: prepare */
if (!($stmt = $mysqli->prepare("INSERT INTO `ADVERTISEMENTS` (`user_id`, `ad_name`, `click_url`, `img_url`, `bg_color`, `start_date`, `end_date`, `timer_delay`, `add_date`) VALUES (?,?,?,?,?,?,?,?,?)"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$stmt->bind_param("issssssis",$tmpUserID, $advertisementNameNew, $destinationURLNew, $dropboxUploadFile, $backgroundColorNew, $bannerStartDateNew, $bannerEndDateNew, $bannerSetTimerNew, $tmpAddDate)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
$_GET['ad_id'] = $stmt->insert_id;
$stmt->close();
Related
So I am trying to get the variables from the URL (http://example.com/pb.php?id=123&affiliate=abd123&lp1=dun.com&lp2=dun2.com&lp3=dun3.com) and Ive tried this code but I receive this error
Prepare failed: (1136) Column count doesn't match value count at row 1
Fatal error: Call to a member function bind_param() on boolean in /home/recondes/public_html/postback.php on line 25
and also
<?php
define("MYSQL_HOST", "localhost");
define("MYSQL_PORT", "3306");
define("MYSQL_DB", "db");
define("MYSQL_TABLE", "tbl");
define("MYSQL_USER", "user");
define("MYSQL_PASS", "pass");
$mysqli = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASS, MYSQL_DB);
if ($mysqli->connect_errno)
{
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$id = $_GET['id'];
$affiliate = $_GET['affiliate'];
$lp1 = $_GET['lp1'];
$lp2 = $_GET['lp2'];
$lp3 = $_GET['lp3'];
if (!($stmt = $mysqli->prepare("INSERT INTO ".MYSQL_TABLE." VALUES (id, affiliate, lp1, lp2, lp3);")))
{
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
$stmt->bind_param('dds', $id, $affiliate, $lp1, $lp2, $lp3 );
if (!$stmt->execute())
{
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
else
{
printf("%d Row updated, added ".$id." to ".$affiliate." .\n", mysqli_stmt_affected_rows($stmt));
}
?>
Your query doesn't list the columns to be inserted into, so it expects you to supply values for all the table columns. You haven't shown the table schema, but it doesn't have only 5 columns.
You're also missing the placeholders that will get filled in by bind_param(). I suspect the values you listed in VALUES() were intended to be the table columns. So try:
if (!($stmt = $mysqli->prepare("INSERT INTO ".MYSQL_TABLE." (id, affiliate, lp1, lp2, lp3) VALUES (?, ?, ?, ?, ?)")))
Also, in your call to bind_param, the string that specifies the datatypes needs to have as many letters as there are parameters. So it should be:
$stmt->bind_param('dssss', $id, $affiliate, $lp1, $lp2, $lp3 );
Finally, when you get an error in one step, and you print the error message, you should stop this script rather than going on to the next step. It makes no sense to use the prepared statement if prepare() fails.
can it be combine into 1 query?
this is the query that im trying to combine? or is there a better way to relate these to table?
$insert_row = $mysqli->query("INSERT INTO orderlist
(TransactionID,ItemName,ItemNumber, ItemAmount,ItemQTY)
VALUES ('$transactionID','$itemname','$itemnumber', $ItemTotalPrice,'$itemqty')");
$insert_row1 = $mysqli->query("INSERT INTO order
(BuyerName,BuyerEmail,TransactionID)
VALUES ('$buyerName','$buyerEmail','$transactionID')");
when i run these both only one query is functional, so what im trying to do is to make them both works.
im open to any suggestion
The reason why your second query isn't working is because of the use of order and not escaping it; it is a MySQL reserved word:
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
Sidenote: ORDER is used when performing a SELECT... ORDER BY...
https://dev.mysql.com/doc/refman/5.0/en/select.html
Checking for errors would have shown you the syntax error such as:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax near 'order
http://php.net/manual/en/mysqli.error.php
Therefore, wrap it in ticks:
$insert_row1 = $mysqli->query("INSERT INTO `order` ...
or rename your table to something other than a reserved word, say orders for example.
If you wish to combine both queries, you can use multi_query()
http://php.net/manual/en/mysqli.quickstart.multiple-statement.php
Example from the manual:
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
$sql = "SELECT COUNT(*) AS _num FROM test; ";
$sql.= "INSERT INTO test(id) VALUES (1); ";
$sql.= "SELECT COUNT(*) AS _num FROM test; ";
if (!$mysqli->multi_query($sql)) {
echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
do {
if ($res = $mysqli->store_result()) {
var_dump($res->fetch_all(MYSQLI_ASSOC));
$res->free();
}
} while ($mysqli->more_results() && $mysqli->next_result());
?>
I also need to point out that your present code may be open to SQL injection since I do not know if you are escaping your data.
If not, then use prepared statements, or PDO with prepared statements, they're much safer.
try to add IF statement.
if ($insert_row = $mysqli->query("INSERT INTO orderlist(TransactionID,ItemName,ItemNumber, ItemAmount,ItemQTY)VALUES ('$transactionID','$itemname','$itemnumber', $ItemTotalPrice,'$itemqty')"));
{
$insert_row1 = $mysqli->query("INSERT INTO order (BuyerName,BuyerEmail,TransactionID) VALUES ('$buyerName','$buyerEmail','$transactionID')");
}
Hello i have a problem with my query ill keep getting errors from my query
this is my error;
Error: BEGIN; INSERT INTO our_work (id) VALUES ('6'); INSERT INTO
our_work_portf_img (portf_id, img_id) VALUES ('6', '7'); INSERT
INTO our_work_images (img_id, image) VALUES ('7', 'adawd.jpg');
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 our_work (id) VALUES ('6'); INSERT INTO `our_wo'
at line 3
i've tried many things but i noticed one thing if i copy the $query string and i posted the query directly in mysql the problem will not accorded and it works just how i hoped it would.
Does anyone noticed the problem in my query cause im literal out of ideas.
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit_new_img'])){
$pjt_dtls = $_POST['project_details'];
$categories = $_POST['categories'];
$link = $_POST['link'];
$image_path = "adawd.jpg";//$_POST['file']; //$_POST['image'];
$row_id ='6';//++$num_rows['i'];
$image_id ='7'; //++$num_rows['ii'];
$sql = "
BEGIN;
INSERT INTO `our_work`
(`id`)
VALUES
('{$row_id}');
INSERT INTO `our_work_portf_img`
(`portf_id`, `img_id`)
VALUES
('{$row_id}', '{$image_id}');
INSERT INTO `our_work_images`
(`img_id`, `image`)
VALUES
('{$image_id}', '{$image_path}');
COMMIT;
";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
$conn->query($sql) does not work with multi-query like yours
you need to use multi_query instead
also here is nice comment:
Please note that there is no need for the semicolon after the last
query. That wasted more than hour of my time...
Trying to make a prepare statement but for some reason it fails me and i'm getting errno 0 with error (text) being blank. What is causing this? Have been searching the web for a quite while now.
<?php
$dbh = new mysqli("localhost","root","","honeypot");
if ($dbh->connect_errno) {
echo "Connection failed: (" . $dbh->connect_errno . ") " . $dbh->connect_error;
die();
}
//Prepare
if (!($stmt = $dbh->prepare("SELECT tblUsers WHERE UserName = ?"))) {
echo "Prepare failed: (" . $dbh->connect_errno . ") " . $dbh->connect_error;
}
?>
You're getting error 0 because you're printing $dbh->connect_error, but you didn't have an error making the connection. For everything other than the initial connection you should use $dbh->error.
echo "Prepare failed: (" . $dbh->errno . ") " . $dbh->error;
You're getting an error because your query has a syntax error. It should be:
SELECT col1, col2, col3, ... FROM tblUsers WHERE UserName = ?
You're missing the list of columns and the FROM keyword.
Is not giving me any error, I am already linked with server but I am still unable to get it work.
It's still unable to add message, do you see any errors?
function pridaj_tovar() {
if ($link = spoj_s_db()) {
$sql = "INSERT INTO `Auto-Moto`".
"(`Tovar`, `Kategoria`,`Mesto`, `Cena`, `ID`, `Popis`)".
"VALUES".
"('$_POST['nazov']', '$_POST['kategorie']', '$_POST['mesta']',' $_POST['cena']', NULL,'$_POST['popis']')";
$result = mysql_query($sql, $link);
if ($result) {
// unable to add
echo '<p>inserting was successful.</p>'. "\n";
} else {
// unable to add!
echo '<p class="chyba">Nastala chyba pri pridávaní tovaru.</p>' . "\n";
}
mysql_close($link);
} else {
// NEpodarilo sa spojiť s databázovým serverom!
echo '<p class="chyba">NEpodarilo sa spojiť s databázovým serverom!</p>';
}
}
This is how you should handle field and table names with spaces,dashes (etc) :
$sql = "INSERT INTO `Auto-Moto`".
"(`Tovar`, `Kategoria`,`Mesto`, `Cena`, `ID`, `Popis`)".
"VALUES".
"('Something', 'Something1', 'word', '50', NULL, 'anotherword')";
$sql = "INSERT INTO `Auto-Moto`".
"(`Tovar`, `Kategoria`,`Mesto`, `Cena`, `ID`, `Popis`)".
"VALUES". "
('{$_POST['nazov']}', '{$_POST['kategorie']}', '{$_POST['mesta']}','{$_POST['cena']}',
NULL,'{$_POST['popis']}')";
You have several problems in your way of making query.
Firstly, your table name is quite non standard (Auto-Moto) so you might need to add quotes around it.
Secondly, it is always a good practice to add some space on proper locations so you could change:
"VALUES"
with
" VALUES "
But you need to provide which error you have received and your table structure.
You missed a lot of space in your Query :
Copy this :
$sql = "INSERT INTO Auto-Moto ".
"(Tovar, Kategoria, Mesto, Cena, ID, Popis) ".
"VALUES ".
"('Something', 'Something1', 'word', '50', NULL, 'anotherword')";
If you want to see an error message change this line:
$result = mysql_query($sql, $link);
To this:
$result = mysql_query($sql, $link) or die ("Error in query: $query. " . mysql_error());
But you should really learn to use mysqli_* extensions since mysql_* extensions—such as what you are using—will be depreciated in PHP 5.5. So change that to this:
$result = mysqli_query($sql, $link) or die ("Error in query: $query. " . mysqli_error());
And be sure to change any other mysqli_* extensions you code might have in place, such as in the spoj_s_db() function you are calling as the $link for a DB connection.
Additionally, your $sql has a few formatting errors. Try this instead:
$sql = "INSERT INTO Auto-Moto"
. " (Tovar, Kategoria, Mesto, Cena, ID, Popis)"
. " VALUES"
. " ('Something', 'Something1', 'word', '50', NULL, 'anotherword')"
;
Note the spaces in the query around the . " concatenation strings. In your original query the formatting had no spaces at all. Which would cause MySQL to choke on the query.