I am using a logbook to track all user interaction.
When trying to save the search of an page to my MySQL database I get this error: You have an error in your SQL syntax; is MySQL seeing this as extra columns now?
$sql_lgb = "INSERT INTO logboek
(
omschrijving,
zoek,
sort,
soort,
user_id
)
VALUES
(
'".$omschrijving."',
'".$zoek_opdr."',
'".$sort_name."',
'pagina bezocht',
'".$_SESSION['user_id']."'
)
";
// resultaat van query
if(!$res_lgb = mysqli_query($mysqli, $sql_lgb)) { include('includes/error_database.php'); die; }
This is the output of the query:
INSERT INTO logboek ( omschrijving, zoek, sort, soort, user_id ) VALUES ( 'Pagina Manuals bezocht', ' (bedrijf LIKE 'torza' OR bedrijf LIKE 'thure' OR bedrijf LIKE 'mb' ) AND (naam LIKE '%%') ', 'naam', 'pagina bezocht', '1' )
The values you are sending to the database has multiple quotations ' in "zoek" value.
To avoid such errors you need to escape them \'.
Or even better use PDO with prepared statements.
Related
I really do not understand why the query below is giving a error.
$sql = "INSERT INTO telefoonnotitie
(
verzoek_id,
klant_id,
contact_id,
offerte,
order,
factuur,
bestelling,
bericht,
gemaakt_id,
gemaakt,
user_id
)
VALUES
(
'".$verzoek_id."',
'".$klant_id."',
'".$contact_id."',
'".$offerte."',
'".$order."',
'".$factuur."',
'".$bestelling."',
'".$bericht."',
'".$_SESSION['user_id']."',
NOW(),
'".$_SESSION['user_id']."'
)
";
The error is '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, factuur, bestelling, bericht, ' at line 7'
The output of this query is
INSERT INTO terugbellen ( verzoek_id, klant_id, contact_id, offerte,
order, factuur, bestelling, bericht, gemaakt_id, gemaakt, user_id )
VALUES ( '1', '472', '1127', '', '', '6161003', '', 'Dit is een
testbericht', '1', NOW(), '1' )
Any suggestions?
order is a SQL key-word. Wrap that column name in back ticks, like this:
$sql = "INSERT INTO telefoonnotitie
(
verzoek_id,
klant_id,
contact_id,
offerte,
`order`,
factuur,
bestelling,
bericht,
gemaakt_id,
gemaakt,
user_id
)
VALUES
Suggestion, you should really use Prepared Statements instead of concatenating your queries to eliminate the risk of SQL Injection attacks.
I have a relational insert which works like a charm in mysql, but when I put in into a query in PHP, nothin' doin'. Can someone help?
$qry = "
INSERT into orders
( customerid, date, order_status )
VALUES
( '$customerid', '$date', $order_status );
INSERT into order_items
( orderid, isbn, item_price, quantity )
VALUES
( LAST_INSERT_ID(), '12345', 5, 1 )
";
when I remove the second insert, it works as advertised in PHP. I am running EasyPHP5.3.
Thanks!
Unless you are using mysqli_multi_query() you cannot run more than one query at a time in PHP. So you'll need to break that query into two queries or use the previously mentioned function.
Hope this work for you
$qry = "
INSERT into orders
( customerid, date, order_status )
VALUES
( '$customerid', '$date', $order_status )";
$qry.=" INSERT into order_items
( orderid, isbn, item_price, quantity )
VALUES
( LAST_INSERT_ID(), '12345', 5, 1 )
";
$mysqli->multi_query($query)
OK, so SQL and PHP may have some common grounds but they still have differences.
If you want to perform multiple queries, at time it might result into an error in PHP because PHP needs to send a request to SQL before it executes the query and one request is to one query. (I think meehee).
If you were to transfer your code to PHP this is the code, I guess you already know how to setup a connection between your php file and your database right, if not feel free to ask or update your question. But this is how to do your code in PHP:
<?php
$sqlOrders = "INSERT INTO orders (customer_id, date, order_status)
VALUES
('$customer_id','$date','$customer_status')";
$sqlOrderItems = "INSERT INTO order_items (orderid, isbn, item_price, quantity)
VALUES
(LAST_INSERT_ID(), '12345', 5, 1)";
After that you need to call this command for this is the request.
if(!mysqli_query($link <--- connection to your database,$sqlOrders)){
die('Error: ' . mysqli_error($link));
}
if(!mysqli_query($link,$sqlOrderItems)){
die('Error: ' . mysqli_error($link));
}
?>
I'm making a search engine based on the API of Faroo.com (http://www.faroo.com/hp/api/api.html) for a school project. I would like to index the index of Faroo, so that users (in my situation, children) can vote up or vote down individual results.
What my (PHP)-script is like:
Look in the MySQL-database if the query exists.
yes => load the results from the database and show them to the user
no => load the results from Faroo, show those results to the user and store them in the database
My database looks like this:
I'm getting all the data stored in the columns from the Faroo API, except for the 'id'-column.
The last part (of storing the Faroo-data in the database) is where it goes wrong:
for($x=0; $x<$tel; $x++){
$sql = "INSERT INTO queries (`id`, `query`, `title`, `url`, `domain`, `kwic`, `votes`) VALUES (NULL, $q, $titles[$x], $urls[$x], $domains[$x], $kwics[$x], 0);";
echo '<br />'.$x.'e query: #'.$sql.'#';
if(!$resultaat = $db->query($sql)){
die('De query kon niet worden uitgevoerd: [' . $db->error . ']');
}
$resultaat = mysqli_fetch_array($resultaat);
}
$tel is a variable which counts the number of results I get from Faroo. It gets defined before this piece of code.
When I run this code, I am getting a nice MySQL-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 'States Bureau of Mines - Wikipedia, the free encyclopedia,
www.wikipedia.org' at line 1
I've searched, and searched, but I couldn't find what the SQL-error is. I think it has something to do with the strange characters in the strings, or maybe my quotation is false?
Kind regards,
Max
I think you need to use single quotes ' for varchar columns, so change as follow
$sql = "INSERT INTO queries (`id`, `query`, `title`, `url`, `domain`, `kwic`, `votes`) VALUES (NULL, '$q', '$titles[$x]', '$urls[$x]', '$domains[$x]', '$kwics[$x]', 0)";
You also have an extra double quote at the end of the query which i removed, you won't need singles quotes for columns id and votes since they are integer fields
<html>
<head>
HTML CODE
<?
$username="xxxxxx";
$password="xxxxxx";
$database="xxxxxx";
mysql_connect(localhost,$username,$password);
$escape = "INSERT INTO monster VALUES ('',$_POST["name"],$_POST["soort"])";
$escape2 = "DELETE monster FROM monster LEFT OUTER JOIN (
SELECT MIN( ID ) AS ID, NAME, PREF
FROM monster
GROUP BY NAME, PREF
) AS KeepRows ON monster.ID = KeepRows.ID
WHERE KeepRows.ID IS NULL";
$query=mysql_real_escape_string($escape);
$query2=mysql_real_escape_string($escape2);
#mysql_select_db($database) or die("MySQL error: Kan inte ansluta till databasen.");
mysql_close();
?>
</body>
</html>
Every time i run this(from another file, containing the name and soort post's) I get an 500 internal server error. First I figured that the queries may be the problem, but they don't even get executed. However, i tried to escape the queries. But still error.
What is wrong with this code? (note: $escape2 is some code i found that removes duplicates in the database. But i don't really know how to format it so that it can be used through php.)
Use something like below...
$query = "INSERT INTO monster VALUES ('', '".$_POST["name"]."', '".$_POST["soort"]."')";
Please do not insert values without escaping.
problem in insert into statement
it should be
$escape = "INSERT INTO monster VALUES ('',".$_POST['name'].",".$_POST['soort'].")";
it is preferable to write colums name while writing insert queries
if column contains string values like VARCHAR or TEXT then use quoted_printable_decode
pass null if column is autoincrement
insert statment
$escape = "INSERT INTO monster (col1, col2, col3) VALUES (NULL,'".$_POST['name']."',".$_POST['soort'].")";
or
$escape = "INSERT INTO monster (col2, col3) VALUES ('".$_POST['name']."',".$_POST['soort'].")";
It looks like you need something like this:
$query = "INSERT INTO monster VALUES ('', '".$_POST["name"]."', '".$_POST["soort"]."')";
Also I would suggest to use prepared statements because it is bad experience to build queries.
First of all I have cool proposition for you. What do you say about some advanced PHP? One step further into great world of safe PHP + MySQL apps?
Introducting to you a PDO. (I know this is not answer to your question but you can consider it). Example of use on your queries:
$db = new PDO('mysql:host=localhost;dbname='.$database, $username, $password);
$insertQuery = $db->prepare('INSERT INTO monster VALUES ("", :name, :soort)');
$deleteQuery = $db->prepare('DELETE monster FROM monster LEFT OUTER JOIN (
SELECT MIN( ID ) AS ID, NAME, PREF
FROM monster
GROUP BY NAME, PREF
) AS KeepRows ON monster.ID = KeepRows.ID
WHERE KeepRows.ID IS NULL');
//to execute query:
$deleteQuery->execute();
//or with params:
$insertQuery->execute(array(
':name' => $_POST['name'],
':soort' => $_POST['soort'],
));
Cool, huh? There is more... Now according to your problem it could be everything (as we don't have error log) but my guess is:
Try to use <?php instead of <?
$escape = "INSERT INTO monster VALUES ('',{$_POST["name"]},{$_POST["soort"]})";
EDIT:
As you provided error log - now I'm sure that problem is in $escape query. It's because you used $escape = " <- and then $_POST["name"] so there was a collision of " (if I can say so).
Try this:
Whenever you insert string type of values in the database using query it has to pass in the quote format. So you just need to change your insert query here.
$query = "INSERT INTO monster VALUES ('', '".$_POST["name"]."', '".$_POST["soort"]."')";
write query like this.
-
Thanks
my sql insert query is not working in my program. I have print the query and then copy paste that code in mysql tab of the phpmyadmin, then it works perfectly. Any body please help me.
if ($_FILES["thumbnailimage"]["size"]>0 )
{
$thumbnailkey = generateUniqueKey($tbl_uploads,"upload_key",12);
$fkey = generateUniqueKey($tbl_uploads,"file_key",24);
$folderkey = generateUniqueKey($tbl_uploads,"folderkey",28);
$fname = substr($_FILES['thumbnailimage']['name'],0,strpos($_FILES['thumbnailimage']['name'],"."));
$ext = getExtension($_FILES['thumbnailimage']['name']);
$insertnewupload = "INSERT INTO ".$tbl_uploads." (upload_key,file_key,file_name,file_type,ext,folderkey,user_id,status,pkey) VALUES ";
$insertnewupload.="('".$thumbnailkey."','".$fkey."','".$fname."','1','".$ext."','".$folderkey."','".$_SESSION['user_id']."','0','".$productkey."')";
echo "<br>1=>".$insertnewupload;
// $db->connect();
$exec_insertnewitem = mysql_query($insertnewupload);
This is the printed out put
INSERT INTO tbl_uploads (upload_key,file_key,file_name,file_type,ext,folderkey,user_id,status,pkey) VALUES ('f958c38e5c31','9b6bd5118ec4a8456bcc46df','sunil','1','jpg','1c1a536fbdde4f24a219ada4c1c9','7','0','3b593aff92ce')
You are quoting numeric values, you should aim for. I've added backticks around the field names also (I can't recall if 'status' is reserved)
INSERT INTO `tbl_uploads` (
`upload_key`,
`file_key`,
`file_name`,
`file_type`,
`ext`,
`folderkey`,
`user_id`,
`status`,
`pkey`
)
VALUES (
'f958c38e5c31',
'9b6bd5118ec4a8456bcc46df',
'sunil',
'1',
'jpg',
'1c1a536fbdde4f24a219ada4c1c9',
7,
0,
'3b593aff92ce'
)
So the following replacement for the line specifying values will suffice
$insertnewupload = "INSERT INTO `".$tbl_uploads."` (`upload_key`,`file_key`,`file_name`,`file_type`,`ext`,`folderkey`,`user_id`,`status`,`pkey`) VALUES ";
$insertnewupload.="('".$thumbnailkey."','".$fkey."','".$fname."','1','".$ext."','".$folderkey."',".$_SESSION['user_id'].",0,'".$productkey."')";
As an addition, there'll probably be a few comments stating you should be using mysqli_ functions or PDO instead of mysql_. At present you're potentially vulnerable to SQL injection with such a method of making a query.
Could be severy reasons... did you check that you connect to the correct database ? Maybe add the database name before "tbl_uploads", e.g. "mybase.tbl_uploads"
Always make practice to write mysql query like this.
$query = "INSERT INTO tablename (`upload_key`,`file_key`,`file_name`,`file_type`,`ext`,`folderkey`,`user_id`,`status,pkey`) VALUES ('f958c38e5c31','9b6bd5118ec4a8456bcc46df','sunil','1','jpg','1c1a536fbdde4f24a219ada4c1c9','7','0','3b593aff92ce')";
$check = mysql_query($query);
check if var_dump($check);returns true or false..