MySQL "INSERT INTO"-error: which quotation do I have to use? - php

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

Related

insert value from one table into another whilst doing a double insert

Not sure that this is even possible. I am inserting values into two tables at the same time using multi_query. That works fine. One of the tables has an auto increment column and I need to take the last auto incremented number and insert it into the second table so like this: insert into table 1 then take the last inserted number from column X and insert it along with other data into table 2. I have played around with using SELECT LAST and INSERT INTO but so far its just doing my head in. The insert statements looks like this:
$sql= "INSERT INTO tbleClients (riskClientId, riskFacility, riskAudDate) VALUES ('$riskclient2', '$facility2', '$riskdate2');";
$sql .="SELECT LAST(riskId) FROM tbleClients;";$sql .="INSERT INTO tblRiskRegister (riskId) SELECT riskId FROM tbleClients ;";
$sql .= "INSERT INTO tblRiskRegister (riskAudDate, riskClientId, riskSessionId, RiskNewId) VALUES ('$riskdate2', '$riskclient2', '$sessionid', '$risknewid')";
Individually they all produce results but I need it to happen simultaneously. I did toy with the idea of doing them all separately but figure thats not very efficient. Any pointers would be appreciated.
$sql= "INSERT INTO tbleClients (riskClientId, riskFacility, riskAudDate) VALUES ('$riskclient2', '$facility2', '$riskdate2');";
After executing the above query, using mysqli_insert_id(), which gives you the last insert id.
So below query is useless.
$sql .="SELECT LAST(riskId) FROM tbleClients;";
$sql .="INSERT INTO tblRiskRegister (riskId) SELECT riskId FROM tbleClients ;";
You can insert last_insert_id in above query.
Unable to find the relation between above & below query.
$sql .= "INSERT INTO tblRiskRegister (riskAudDate, riskClientId, riskSessionId, RiskNewId) VALUES ('$riskdate2', '$riskclient2', '$sessionid', '$risknewid')";

Using On Duplicate Key Update with an array

I'm relatively new to MYSQL and am having trouble combining idea I have read about. I have a form generated from a query. I want to be able to insert or update depending on whether there is currently a matching row. I have the following code which works for inserting but I;m struggling with the On DUPLICATE UPDATE part I keep getting a message saying there is an error in my syntax or unexpeted ON depending on how I put the ' .
require_once("connect_db.php");
$row_data = array();
foreach($_POST['attendancerecordid'] as $row=>$attendancerecordid) {
$attendancerecordid=mysqli_real_escape_string($dbc,$attendancerecordid);
$employeeid=mysqli_real_escape_string($dbc,($_POST['employeeid'][$row]));
$linemanagerid=mysqli_real_escape_string($dbc,($_POST['linemanagerid'][$row]));
$abscencecode=mysqli_real_escape_string($dbc,($_POST['abscencecode'][$row]));
$date=mysqli_real_escape_string($dbc,($_POST['date'][$row]));
$row_data[] = "('$attendancerecordid', '$employeeid', '$linemanagerid', '$abscencecode', '$date')";
}
if (!empty($row_data)) {
$sql = 'INSERT INTO attendance (attendancerecord, employeeid, linemanagerid, abscencecode, date) VALUES '.implode(',', $row_data)
ON DUPLICATE KEY UPDATE abscencecode = $row_data[abscencecode];
echo $sql;
$result = mysqli_query ($dbc, $sql) or die(mysqli_error ($dbc));
}
The various echo statements are showing that the correct data is coming through and my select statement was as expected before I added in the ON DUPLICATE statement.
You need to fix the way the sql statement is constructed via string concatenation. When you create an sql statement, echo it and run it in your favourite mysql manager app for testing.
$sql = 'INSERT INTO attendance (attendancerecord, employeeid, linemanagerid, abscencecode, date) VALUES ('.implode(',', $row_data).') ON DUPLICATE KEY UPDATE abscencecode = 1'; //1 is a fixed value yiu choose
UPDATE: Just noticed that your $row_data array does not have named keys, it just contains the entire new rows values as string. Since you do bulk insert (multiple rows inserted in 1 statement), you have to provide a single absencecode in the on duplicate key clause, or you have to execute each row in a separate insert to get the absence code for each row in a loop.

updating the mysql table if query store_num exits

Everyone!
I am working on application using php and mysql. Basically, initially, I am inserting the new data entries using html form into the database where store# is my primary key. For now I can not update the existing store# (as its my primary key) and get a message saying "Duplicate entry for store 967 (example)".
I want to update the "store" table if entery exists. Here is my code posted below, but I am getting another error message
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 '['967'],address=['500 kipling avenue 1'],dsm_name=['n/a'],phone=['416-967-' at line 1
I am not sure if I am using the if conditional at right spot.
**$sql = "INSERT INTO `stores`(`store_num`, `address`, `dsm_name`, `phone`, `router_type`, `high_speed_pri`, `dsl_log`, `dsl_pass`, `secondary_conn`, `sec_dsl`, `sec_pass`) VALUES ('$store' , '$address', '$dsm', '$phone', '$router', '$highspeedpr', '$dsllog', '$dslpas', '$secondary_conn' , '$secdsl' , '$sec_pass')";
$mysqli_query = "SELECT * from 'stores' WHERE $store = 'store_num'";
if ($mysqli_query == TRUE){
$sql = "UPDATE `stores` SET `store_num`=['$store'],`address`=['$address'],`dsm_name`=['$dsm'],`phone`=['$phone'],`router_type`=['$router'],`high_speed_pri`=['$highspeedpr'],`dsl_log`=['$dsllog'],`dsl_pass`=['$dslpas'],`secondary_conn`=['$secondary_conn'],`sec_dsl`=['$secdsl'],`sec_pass`=['$sec_pass'] WHERE 1";
}
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>**
Replace instead of Insert
Since your update statement includes all the same fields as Insert, you can simply use a REPLACE Statement. As stated on the linked documentation:
REPLACE works exactly like INSERT, except that if an old row in the
table has the same value as a new row for a PRIMARY KEY or a UNIQUE
index, the old row is deleted before the new row is inserted. See
Section 13.2.5, “INSERT Syntax”.
So, changing the code to the following should work:
$sql = "REPLACE INTO `stores`(`store_num`, `address`, `dsm_name`, `phone`, `router_type`, `high_speed_pri`, `dsl_log`, `dsl_pass`, `secondary_conn`, `sec_dsl`, `sec_pass`) VALUES ('$store' , '$address', '$dsm', '$phone', '$router', '$highspeedpr', '$dsllog', '$dslpas', '$secondary_conn' , '$secdsl' , '$sec_pass')";
Error Reason
Your problem is with the syntax in the update statement. What is store_num, is it a number or a string?
You should change your syntax to not include the square brackets in the actual mysql query.
If $Store is Number:
=['$store'], to =$store
If $Store is Text:
=['$store'], to ='$store'
Final Recommendation
Even better though will be use prepared statements which are also secure and avoid against SQL injection attacks.
You can do this logic with a single query, using on duplicate key update. First, you have to define store_num as a unique key, if it is not already a unique or primary key:
CREATE UNIQUE INDEX idx_stored_storenum on stores(store_num);
Then use this insert:
INSERT INTO `stores`(`store_num`, `address`, `dsm_name`, `phone`, `router_type`, `high_speed_pri`,
`dsl_log`, `dsl_pass`, `secondary_conn`, `sec_dsl`, `sec_pass`
)
VALUES ('$store' , '$address', '$dsm', '$phone', '$router', '$highspeedpr',
'$dsllog', '$dslpas', '$secondary_conn' , '$secdsl' , '$sec_pass')
ON DUPLICATE KEY UPDATE address = values (address),
dsm_name = values(dsm_name),
. . .
sec_pass = values(sec_pass);
Your particular problem is the square braces, which MySQL doesn't recognize.

Why do I get a 500 error? (MySQL php)

<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

Cannot insert data into mysql table via php

I'm sure this question has been asked a thousand times but after an hour of truly trying many examples on the web, I have failed to insert new data into my table. I have tried many methods as I said, the one I'm about to post is most recent. If anyone knows why my code is failing it would save so much stress. I have only so far managed to insert data via phpmyadmin. The database is called "test" and the table is called "getting". Please note that "key" is auto incremented.
Thank you
$username='****';
$password='****';
$database='test';
$con= mysql_connect("localhost",$username,$password);
mysql_select_db("test",$con);
mysql_query("INSERT INTO getting (Key, Date, amount, tax, Extra)
VALUES ('', 'sept 26 2008', '35653', '46', '454')");
You should try
put keywords between backticks
format date as YYYY-MM-DD
don't use quotes for numbers
use NULL for auto-increment keys (you could also remove it from INSERT)
perform error checking
Try this query
$res = mysql_query(
"INSERT INTO getting (`Key`, `Date`, amount, tax, Extra)
VALUES (NULL, '2008-09-26', 35653, 46, 454)");
if (!$res) {
die('Invalid query: ' . mysql_error());
} else {
// Do here what you need
}
mysql_query("INSERT INTO getting (Key, Date, amount, tax, Extra)
VALUES ('', 'sept 26 2008', '35653', '46', '454')") or die(mysql_error());
What does it say after execution? If there is an error in request - you will see it.
my guess would have been "4. use NULL for auto-increment keys" by marco too
I belive if the 'key' filed is autoincremented you may not even bother mentioning it in your insert statement.
Something like this
INSERT INTO getting (Date, amount, tax, Extra)
VALUES ('sept 26 2008', '35653', '46', '454')

Categories