Submit Multi-Dimensional Array to mySQL - php

I have a mySQL table with the fields:
preview_url
large_url
And I have an object that I submit with the following structure:
var $urls = {largeImg:[],preview:[]}
$urls.largeImg values have to be inserted into 'large_url' and
$urls.preview_url values have to be inserted into 'preview_url'
$urls.largeImg[0] has to go in the same mysql table row as $urls.preview[0],
$urls.largeImg[1] into the same row as $urls.preview[1] and so on.
my php:
$urls = $_POST['urls'];
function cache_urls($urls){
global $db;
foreach($urls as $url){
$sql = "INSERT INTO cache ";
$sql .= "(preview_url, large_url) ";
$sql .= "VALUES (";
$sql .= "'" . db_escape($db, $url['preview']) . "', ";
$sql .= "'" . db_escape($db, $url['largeImg']) . "'";
$sql .= ");";
$result = mysqli_query($db, $sql);
}
And then I also tried this:
foreach($urls as $url){
foreach($url as $key => $value){
$sql = "INSERT INTO cache ";
$sql .= "(preview_url, large_url) ";
$sql .= "VALUES (";
if($key==="preview"){
$sql .= "'" . db_escape($db, $value) . "', ";
}
if($key==="largeImg"){
$sql .= "'" . db_escape($db, $value) . "'";
}
$sql .= ");";
$result = mysqli_query($db, $sql);
}
}
So I assume the SQL bit must be wrong but I'm really at the end of my knowledge! Any help much appreciated.

You should do it like this way,
$sql = "INSERT INTO cache (preview_url, large_url) values";
foreach($urls["largeImg"] as $index => $large_url){
$preview_url = $urls["preview"][$index];
$sql .= "('" . db_escape($db,$preview_url) . "','" . db_escape($db,$large_url) . "'),";
}
$sql = rtrim($sql,",");

Related

How to fix syntax error in PHP when statement works fine in MySQL?

I'm using PHP/MySQL to store data collected from a web page. I'm getting
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 narrative_photos VALUES (`filename`, `narrative_id`) VALUES ('ash_02
When I take the statement produced by PHP and paste it into the MySQL console, the statement works fine.
Here's the PHP code:
foreach ($files['pictures']['final_name'] as $key => $final_name) {
$sql .= "INSERT INTO narrative_photos ";
$sql .= "(`filename`, `narrative_id`) ";
$sql .= "VALUES (";
$sql .= "'" . db_escape($db, $final_name) . "', ";
$sql .= "'LAST_INSERT_ID()'); ";
}
It produces something that looks like this:
INSERT INTO narrative_photos VALUES (`filename`, `narrative_id`) VALUES ('ash_020819-140257.png', 3);
If I paste that into MySQL it works. But if I comment out the PHP code and substitute:
$sql .= "INSERT INTO narrative_photos VALUES (`filename`, `narrative_id`) VALUES ('ash_020819-140257.png', 3);";
it continues to throw the MySQL error.
I've been playing with this for a couple of hours and I can't figure out where my mistake is. I would appreciate a second set of eyes. Thanks!
EDIT: Here's the entire function for context.
function insert_narrative($narrative, $files) {
global $db;
$sql = "INSERT INTO narratives ";
$sql .= "(date, positive_thing, what_you_did, goals, plan, entered_by, library_id) ";
$sql .= "VALUES (";
$sql .= "'" . db_escape($db, $narrative['sqldate']) . "', ";
$sql .= "'" . db_escape($db, $narrative['positive_thing']) . "', ";
$sql .= "'" . db_escape($db, $narrative['what_you_did']) . "', ";
$sql .= "'" . db_escape($db, $narrative['goals']) . "', ";
$sql .= "'" . db_escape($db, $narrative['plan']) . "', ";
$sql .= "'" . db_escape($db, $narrative['entered_by']) . "', ";
$sql .= "'" . db_escape($db, $_SESSION['library_id']) . "'";
$sql .= "); ";
if (!empty($files['pictures']['final_name'])) {
foreach ($files['pictures']['final_name'] as $key => $final_name) {
$sql .= "INSERT INTO narrative_photos ";
$sql .= "(`filename`, `narrative_id`) ";
$sql .= "VALUES (";
$sql .= "'" . db_escape($db, $final_name) . "', ";
$sql .= "LAST_INSERT_ID()); ";
}
}
$result = mysqli_query($db, $sql);
if ($result) {
return true;
} else {
echo mysqli_error($db);
db_disconnect($db);
exit;
}
}
EDIT #2:
I just realized that independent of the syntax error my approach isn't going to work because that LAST_INSERT_ID is probably going to pick up the ids for each of those inserts instead of just using the id from the main table. I've modified the function but I'm still getting a syntax error at SET #narrative_id. Here's the code.
$sql = "INSERT INTO narratives ";
$sql .= "(date, positive_thing, what_you_did, goals, plan, entered_by, library_id) ";
$sql .= "VALUES (";
$sql .= "'" . db_escape($db, $narrative['sqldate']) . "', ";
$sql .= "'" . db_escape($db, $narrative['positive_thing']) . "', ";
$sql .= "'" . db_escape($db, $narrative['what_you_did']) . "', ";
$sql .= "'" . db_escape($db, $narrative['goals']) . "', ";
$sql .= "'" . db_escape($db, $narrative['plan']) . "', ";
$sql .= "'" . db_escape($db, $narrative['entered_by']) . "', ";
$sql .= "'" . db_escape($db, $_SESSION['library_id']) . "'";
$sql .= "); ";
$sql .= "SET #narrative_id = LAST_INSERT_ID()";
if (!empty($files['pictures']['final_name'])) {
foreach ($files['pictures']['final_name'] as $key => $final_name) {
$sql .= "INSERT INTO narrative_photos ";
$sql .= "(`filename`, `narrative_id`) ";
$sql .= "VALUES (";
$sql .= "'" . db_escape($db, $final_name) . "', ";
$sql .= "#narrative_id); ";
}
}
If you're trying to make one query to insert all the values, you need to not include the INSERT part of the query each time, just adding a new set of values instead. You could use something like this. Note that LAST_INSERT_ID() should not be enclosed in quotes, as that will insert the literal string "LAST_INSERT_ID()" instead of the value.
$sql = "INSERT INTO narrative_photos (`filename`, `narrative_id`) VALUES ";
$values = array();
foreach ($files['pictures']['final_name'] as $final_name) {
$values[] = "('" . db_escape($db, $final_name) . "', LAST_INSERT_ID())";
}
$sql .= implode(', ', $values);
Notes
I'm assuming that you actually want all of these filenames to end up with the same value in narrative_id, which is going to link back to another table.
Although from the look of it these values have been filtered already (I presume they are actual system filenames), the code is still potentially vulnerable to SQL injection. This question and this question offer some good advice as to how you can use prepared statements with arrays of parameters.
I don't understand why you concatenating each line to a variable instead of just doing an entire statement. Also, in your examples you have used VALUES twice which is incorrect. I can't understand why you are creating the SQL statement inside a loop but you never execute it, which you need to. I don't know what API you are using but here's an example.
if (isset($files['pictures']['final_name'])) {
foreach ($files['pictures']['final_name'] as $key => $final_name) {
$sql = "INSERT INTO narrative_photos (`filename`, `narrative_id`)
VALUES ('".db_escape($db, $final_name)."', LAST_INSERT_ID())";
if (!$mysqli->query($sql)) {
echo "SQL failed: (".$mysqli->errno.") ".$mysqli->error;
}
}
} else {
echo "final name does not exist";
}

Convert "INSERT" MySQL query to Postgresql query

I`m stuck for some time to fix this trouble. I followed this article https://www.sitepoint.com/creating-a-scrud-system-using-jquery-json-and-datatables/
to create SCRUD System. But I stuck when I need to add a new record to PostgreSQL.
The working MySQL part of the code is:
$db_server = 'localhost';
$db_username = 'root';
$db_password = '123456';
$db_name = 'test';
$db_connection = mysqli_connect($db_server, $db_username, $db_password, $db_name);
$query = "INSERT INTO it_companies SET ";
if (isset($_GET['rank'])) { $query .= "rank = '" . mysqli_real_escape_string($db_connection, $_GET['rank']) . "', "; }
if (isset($_GET['company_name'])) { $query .= "company_name = '" . mysqli_real_escape_string($db_connection, $_GET['company_name']) . "', "; }
if (isset($_GET['industries'])) { $query .= "industries = '" . mysqli_real_escape_string($db_connection, $_GET['industries']) . "', "; }
if (isset($_GET['revenue'])) { $query .= "revenue = '" . mysqli_real_escape_string($db_connection, $_GET['revenue']) . "', "; }
if (isset($_GET['fiscal_year'])) { $query .= "fiscal_year = '" . mysqli_real_escape_string($db_connection, $_GET['fiscal_year']) . "', "; }
if (isset($_GET['employees'])) { $query .= "employees = '" . mysqli_real_escape_string($db_connection, $_GET['employees']) . "', "; }
if (isset($_GET['market_cap'])) { $query .= "market_cap = '" . mysqli_real_escape_string($db_connection, $_GET['market_cap']) . "', "; }
if (isset($_GET['headquarters'])) { $query .= "headquarters = '" . mysqli_real_escape_string($db_connection, $_GET['headquarters']) . "'"; }
$query = mysqli_query($db_connection, $query);
I managed to write this and it fails to work for PostgreSQL:
$conn_string = "dbname=test user=postgres password=123456";
$query = "INSERT INTO it_companies VALUES ";
if (isset($_GET['rank'])) { $query .= "('" . pg_escape_string($db_connection, $_GET['rank']) . "', "; }
if (isset($_GET['company_name'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['company_name']) . "', "; }
if (isset($_GET['industries'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['industries']) . "', "; }
if (isset($_GET['revenue'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['revenue']) . "', "; }
if (isset($_GET['fiscal_year'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['fiscal_year']) . "', "; }
if (isset($_GET['employees'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['employees']) . "', "; }
if (isset($_GET['market_cap'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['market_cap']) . "', "; }
if (isset($_GET['headquarters'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['headquarters']) . "');"; }
$query = pg_query($db_connection, $query);
The message I gets from the system is: "Add request failed: parsererror"
The Edit and remove functions are working well.
I follow to build this clause from the PGSQL site example:
INSERT INTO films VALUES
('UA502', 'Bananas', 105, '1971-07-13', 'Comedy', '82 minutes');
Any what I`m doing wrong? Thanks!
UPDATE
The echo of the query and the error was the id column. In Mysql code there was no problem with the ID colum. Why when i use pgsql it does?:
INSERT INTO it_companies (rank,company_name,industries,revenue,fiscal_year,employees,market_cap,headquarters)
VALUES ('1', 'asd', 'asd', '1', '2000', '2', '3', 'asdf');
Warning: pg_query(): Query failed: ERROR: duplicate key value violates unique constraint "it_companies_pkey" DETAIL: Key (company_id)=(2) already exists. in C:\WEB\Apache24\htdocs\datatableeditor\data.php on line 121
{"result":"error","message":"query error"
,"data":[]}
UPDATE2
The working code with one bug:
$query = "INSERT INTO it_companies (rank,company_name,industries,revenue,fiscal_year,employees,market_cap,headquarters) VALUES ";
if (isset($_GET['rank'])) { $query .= "('" . $_GET['rank'] . "', "; }
if (isset($_GET['company_name'])) { $query .= "'" . $_GET['company_name'] . "', "; }
if (isset($_GET['industries'])) { $query .= "'" . $_GET['industries'] . "', "; }
if (isset($_GET['revenue'])) { $query .= "'" . $_GET['revenue'] . "', "; }
if (isset($_GET['fiscal_year'])) { $query .= "'" . $_GET['fiscal_year'] . "', "; }
if (isset($_GET['employees'])) { $query .= "'" . $_GET['employees'] . "', "; }
if (isset($_GET['market_cap'])) { $query .= "'" . $_GET['market_cap'] . "', "; }
if (isset($_GET['headquarters'])) { $query .= "'" . $_GET['headquarters'] . "') RETURNING company_id;"; }
echo $query;
After this query, the message "Add request failed: parsererror" is still there. But after a manual refresh of the page, the new data is saved. Any idea why this message apears and not loading the data automatically?
UPDATE 3 - Success
I forgot to remove echo $query; from the code causing the error message.
All works now. Thanks for the help to all! :)
You need a little more work in your query string building.
You only add the open parenthesis ( if rank is present
You only add the closing parenthesis ) if headquarters is present.
Also you need specify what field column get which value, otherwise you end with headquarter name into the fiscal_year field. If columns are not specified the values are add it on the same order as define on the table.
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);
And as other have comment check the $query to see what you have.

Escape String in SQL Server using PHP

Whenever I implement this code, I no longer get an error while using a single quote, but the hexstring get's written to the database instead of being converted back to the original characters.
function mssql_escape($data) {
if(is_numeric($data))
return $data;
$unpacked = unpack('H*hex', $data);
return '0x' . $unpacked['hex'];
}
mssql_query('
INSERT INTO sometable (somecolumn)
VALUES (' . mssql_escape($somevalue) . ')
');
This is what I'm trying to do. $suggestTest is the variable I'm using the escape function on.
$nomDept = $_POST['nomDept'];
$subSupervisor = $_POST['subSupervisor'];
$suggestion = $_POST['suggestion'];
$suggestTest = mssql_escape($suggestion);
if ($subSupervisor == "Yes") {
$query = "INSERT INTO dbo.emp_recog (nomDept, nomSuggestion, subSupervisor) VALUES (";
$query .= "'" . $nomDept . "', ";
$query .= "'" . $suggestTest . "', ";
$query .= "'" . $subSupervisor . "');";
$res = mssql_query($query);
}
I've also tried omitting the single quotes around the variable like so
if ($subSupervisor == "Yes") {
$query = "INSERT INTO dbo.emp_recog (nomDept, nomSuggestion, subSupervisor) VALUES (";
$query .= "'" . $nomDept . "', ";
$query .= $suggestTest ", ";
$query .= "'" . $subSupervisor . "');";
$res = mssql_query($query);
}
If you use prepare to build your SQL statement, you do not need to escape the variables.

mysqli_multi_query command out of sync error - not inserting into DB

I am trying to use the mysqli_multi_query function on the code below but being hit with this error:
Commands out of sync; you can't run this command now
// add call stats to incoming nodes
$sql = "INSERT INTO `" . node_name_formatter($i_route) . "` ";
$sql .= " (`timeperiod`, ";
$sql .= " `exchange_id`, ";
$sql .= " `calls_in`) ";
$sql .= "VALUES ('" . date('Y-m-d H:i:s', $time) . "', ";
$sql .= " '$exchange_id', ";
$sql .= " '1') ";
$sql .= "ON DUPLICATE KEY UPDATE ";
$sql .= " `calls_in` = `calls_in`+1;";
// add call stats to outgoing nodes
$sql .= "INSERT INTO `" . node_name_formatter($o_route) . "` ";
$sql .= " (`timeperiod`, ";
$sql .= " `exchange_id`, ";
$sql .= " `calls_out`) ";
$sql .= "VALUES ('" . date('Y-m-d H:i:s', $time) . "', ";
$sql .= " '$exchange_id', ";
$sql .= " '1') ";
$sql .= "ON DUPLICATE KEY UPDATE ";
$sql .= " `calls_out` = `calls_out`+1";
// echo $sql . '<br><br>';
mysqli_multi_query($connection, $sql) or die(mysqli_error($connection));
I am doing this query just as it says on the php manual. Also is it better to use this function or to carry out 2 seperate queries the normal mysqli_query way?
Update as
// add call stats to incoming nodes
$sql = "INSERT INTO `" . node_name_formatter($i_route) . "` ";
$sql .= " (`timeperiod`, ";
$sql .= " `exchange_id`, ";
$sql .= " `calls_in`) ";
$sql .= "VALUES ('" . date('Y-m-d H:i:s', $time) . "', ";
$sql .= " '$exchange_id', ";
$sql .= " '1') ";
$sql .= "ON DUPLICATE KEY UPDATE ";
$sql .= " `calls_in` = `calls_in`+1;";
// add call stats to outgoing nodes
$sql .= "INSERT INTO `" . node_name_formatter($o_route) . "` ";
$sql .= " (`timeperiod`, ";
$sql .= " `exchange_id`, ";
$sql .= " `calls_out`) ";
$sql .= "VALUES ('" . date('Y-m-d H:i:s', $time) . "', ";
$sql .= " '$exchange_id', ";
$sql .= " '1') ";
$sql .= "ON DUPLICATE KEY UPDATE ";
$sql .= " `calls_out` = `calls_out`+1;";
// echo $sql . '<br><br>';
mysqli_multi_query($connection, $sql) or die(mysqli_error($connection));
you have to loop through the result using mysqli_next_result to get result of each query.
Check here for more about the error Commands out of sync

php database insert function

I am going through an article in nettuts.com and it is about building a twitter clone and there is a function in the code that does standard inserts into the database.Here is the code
private function insert($table, $arr){
$query = "INSERT INTO" . $table . " (";
$pref = "";
foreach ($arr as $key => $value) {
$query .= $pref . $key;
$pref = ", ";
}
$query .= ") VALUES (";
$pref = "";
foreach ($arr as $key => $value) {
$query .= $pref. "'" . $value . "'";
$pref = ", ";
}
$query = .= ");";
return $this->db->query($query);
}
what I am having trouble understanding is the $pref variable.Can someone explain its purpose to me?
It's a way of having commas only in between the values in VALUES('like','this','and','this')
because $pref is still set to "" the first time it's value and the key is appended to $query they will always have a comma before the value except the first one:
$query .= $pref . $key;
$pref = ", ";
you could also use the implode() function http://php.net/manual/en/function.implode.php to create a string from the $arr array!
implode(", ", array_keys($arr));
Silly mistake in your code
$query = "INSERT INTO" . $table . " (";
Need to space after INTO
$query = "INSERT INTO " . $table . " (";
$query .= ") VALUES (";
$query .= ");";

Categories