Send array from js to php to SQL database - php

I hope I'm missing something easy here.
I have an array created in js, say: var ids = [1,2,3,4,5];
Now I want this array to populate a column in my SQL database table.
I have the pipeline setup for adding single elements to my table like this:
request is sent via ajax:
$.ajax({
type: "POST",
url: "some.php",
data: {
ids: ids,
}
});
some.php receives the data (connection, etc. is set up):
$ids = $_POST['ids'];
SQL is used to insert single values to the column COL_ID
$sql = "INSERT INTO `mydb`.`dbtable`(`COL_ID`) VALUES ('$ids)";
This pipeline works for single values (e.g. of ids = 2 but fails for an array.
What I'd want is for COL_ID to contain each array element as a row
| COL_ID |
|-------- |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
I suspect it's in the SQL query. Any help is welcome.

First, use prepared statements, don't insert post data directly into a database query. Using post data directly means you are vulnerable to sql injection attacks.
As #DanielReed indicated, the correct format is
INSERT INTO table_name (column_list) VALUES (value_list_1), (value_list_2), (value_list_3);
You can build this dynamically:
$ids = $_POST['ids'];
// Make sure we get the correct number of ? for prepared statements
$params = str_repeat('(?), ', count($ids));
// Strip the trailing space and comma
$params = substr($params, 0, -2);
$sql = 'INSERT INTO `mydb`.`dbtable`(`COL_ID`) VALUES ' . $params;
Now you can use $sql as your query and $ids as the values for the prepared statement. This prevents sql injection.

PHP receives it as an array.
SQL Syntax wants it in the following syntax:
INSERT INTO table_name (column_list)
VALUES
(value_list_1),
(value_list_2),
...
(value_list_n);
So what you could do is:
$sql = "INSERT INTO `mydb`.`dbtable`(`COL_ID`) ";
foreach($ids as $value){
$sql .= "(".$value.") ";
}

Related

How to insert json object into mysql table

There are many examples around which parse the JSON and then insert the respective fields into MySQL table.
My case is different in a way that I am creating a json at runtime.
my table looks like this:
mysql> describe turkers_data;
+-----------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+----------+------+-----+---------+-------+
| id | char(36) | NO | PRI | NULL | |
| sentences | json | NO | | NULL | |
+-----------+----------+------+-----+---------+-------+
2 rows in set (0.00 sec)
based on the input received, I build a json using json_encode method in php, which I alredy validated on jsonlint and it is of course valid.
example json:
{
"opening": "[\"John arrived at Sally's house to pick her up.\",\"John and Sally were going to a fancy restaurant that evening for a dinner.\",\"John was little nervous because he was going to ask Sally to marry him.\"]",
"first_part": "[\"aa\",\"bb\"]",
"first_mid": "[\"Waiter shows John and Sally to their table.\"]",
"mid_part": "[\"cc\",\"dd\"]",
"mid_late": "[\"John asks Sally, \\\"Will you marry me?\\\"\"]",
"last_part": "[\"ee\",\"ff\",\"gg\"]"
}
I use following code to insert into mysql table using mysqli
$opening = array("John arrived at Sally's house to pick her up.", "John and Sally were going to a fancy restaurant that evening for a dinner.", "John was little nervous because he was going to ask Sally to marry him.");
$mid_early = array("Waiter shows John and Sally to their table.");
$mid_late = array('John asks Sally, "Will you marry me?"');
$json_data->opening = json_encode($opening);
$json_data->first_part = json_encode($jSentence_1);
$json_data->first_mid = json_encode($mid_early);
$json_data->mid_part = json_encode($jSentence_2);
$json_data->mid_late = json_encode($mid_late);
$json_data->last_part = json_encode($jSentence_3);
$data = json_encode($json_data);
echo($data);
$sql = "INSERT INTO turkers_data (id, sentences)
VALUES ($id, $data)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
but it does not work, i get the 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 '"opening":"[\"John arrived at Sally's house to pick her up.\",\"John and Sally w' at line 2
I do not know what is wrong. I could not find much information on how to do this, I read that it is not recommended to have json data dumped as it is into mysql table, but in my case i am unsure of how many sentences are going to there. Also, I believe this serves the purpose for the time being, I plan to just get that JSON from mysql back and process the data in python.
Also pardon me for using json, JSON, MySQL, mysql, I do not know the standard yet.
You are having a problem with your SQL insert because you have this:
$sql = "INSERT INTO turkers_data (id, sentences) VALUES ($id, $data)";
There is no escaping of quotes on $data, and the $data is not wrapped in single quotes either.
You should build this as a prepared statement and bind the params which will do all that for you:
$sql = "INSERT INTO turkers_data (id, sentences) VALUES (?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ss', $id, $data );
$stmt->execute();
The above assumes you are using mysqli, and not PDO. If its PDO, this is syntax for PDO method:
$sql = "INSERT INTO turkers_data (id, sentences) VALUES (?,?)";
$stmt = $conn->prepare($sql);
$stmt->execute(array($id, $data));
EDIT
Last ditch effort (AND ILL-ADVISED), if your php and mysql do not support prepared statements (it should!), then you can resort to the old method of wrapping and escaping your fields in the sql build string:
$sql = "INSERT INTO turkers_data (id, sentences)
VALUES (
'". $conn->real_escape_string($id) ."',
'". $conn->real_escape_string($data) ."'
)";
But this is NOT ADVISED! If at all costs you should try to get prepared statements to work, or upgrade your PHP, or mysqli extensions.

SQL : INSERT if no exist and UPDATE if exist

I have a program that can perform inserts and updates to the database, I get the data from API.
This is sample data when I get:
$uname = $get['userName'];
$oname = $get['offerName'];
$visitdata= $get['visits'];
$convdata = $get['conversion'];
I save this data to database sql. (sucess) this is a sample:
$sql = "INSERT INTO data_tester(username_data, name_offer_data, visit_data, conversion_data) VALUES('$uname','$oname', '$visitdata', '$convdata')";
Sample data in database table
id | username_data | name_offer_data | visit_data | conversion_data
1 | MOJOJO | XXX AU | 177 | 13
2 | MOJOJO | XX US | 23 | 4
Now, I want to save data $uname, $oname, $visitdata, $convdata if NOT EXIST and UPDATE $visitdata, $convdata where $uname, $oname if EXIST
How to run the code with a simple query.
Please give me an example.
Thank you.
The feature you are looking for is called UPSERT and it is the part of SQL-2008 Standard. However not all DBMS-s implement it and some implement it differently.
For instance on MySQL you can use:
INSERT ... ON DUPLICATE KEY UPDATE
syntax (link to docs)
or
REPLACE INTO
syntax (link to docs).
These methods require you to have a proper PRIMARY KEY: (username_data name_offer_data) in your case.
Some PHP frameworks support this feature too provided you are using ActiveRecord (or similar) class. In Laravel it is called updateOrCreate and in Yii it is called save(). So if you are using a framework try to check its documentation.
If you are using neither framework nor modern DBMS you have to implement the method yourself. Run SELECT count(*) from data_tester WHERE username_data = ? AND name_offer_data = ?, check if it returned any rows and call an appropriate UPDATE/INSERT sql
it's simple, try this:
if(isset($get['userName'])){
$sql = "SELECT * FROM data_transfer WHERE userName = ".$userName.";";
$result = connection()->query($sql);
$rs = mysqli_fetch_array($result);
connection()->close();
//if is not void, means that this username exists
if ($rs != ''){
mysqli_free_result($result);
//InsertData
}
else{
mysqli_free_result($result);
//UpdateData
}
*chech that you have to use your PrimaryKey on where clause to ensure there are only one of this. if you use an ID and you don't get it by $_GET, you'll have to modify something to ensure non-duplicated data. For example, checking that userName cannot be duplicated or something similar
You can simply use replace into command instead of insert into command.
$sql = "REPLACE INTO data_tester(username_data, name_offer_data, visit_data, conversion_data) VALUES('$uname','$oname', '$visitdata', '$convdata')";
It is one of mysql good and useful feature. I used it many times.
Please ensure there is a unique key on column username_data, if so Mysql's ON DUPLICATE KEY UPDATE is suitable for this case, the SQL statement is like that:
$sql = "INSERT INTO data_tester(username_data, name_offer_data, visit_data,
conversion_data) VALUES('$uname','$oname', '$visitdata', '$convdata')
ON DUPLICATE KEY UPDATE username_data = '$uname', name_offer_data =
'$oname', visit_data = '$visitdata', conversion_data = '$convdata'"

SQL - Inserting data where values are an array

I want to be able to add an array of strings to a table so that each string is a new row (in PHP).
This is it in psuedo-code:
$Array = "10000,10001,10002,10003";
$Data = "ImportantData";
mysqli_query($db, "INSERT INTO MyTable(`id`,`data`) VALUES($Array, $Data)");
So that a previously empty table would look like:
id | data
------------------------
10000 | ImportantData
10001 | ImportantData
10002 | ImportantData
10003 | ImportantData
In an update script, with those rows already established, I could just say:
mysqli_query($db, "UPDATE MyTable SET data = $Data WHERE `id` IN($Array));
However I want it to create rows, not just update old ones.
Is there any way I can do this?
Just create a foreach loop on $Array, and insert the data. I assume you want to update it if it exists as it makes little sense to create a new record with the same PK, so use the following (assumes you are using PHP PDO
INSERT INTO MyTable (id,data) VALUES (:id,:data) ON DUPLICATE KEY UPDATE data=:data;
Use REPLACE INTO:
REPLACE INTO table SET id = 10001, data = 'new important data';
MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/replace.html

What is the best way to loop through string and insert into mysql column?

I have a variable which displays the following string:
$item_value = itemOne,itemTwo,itemThree
I would like to take this string and have insert each item as a separate row entry for a single column. Additionally, I need it to insert an auto increment key value for each entry. So to complete this example, here is what I would want the mysql table to look like when complete:
ID || item_value || comments
----------------------------------------
1 || itemOne || --------------
2 || itemTwo || --------------
3 || itemThree || --------------
My feeling is that I need to explode the string around the comma and then insert it into the table. I have attempted this but am having some issues getting each item as separate row entries. Any assistance is much appreciated.
For the auto-increment i suggest letting the database handle it, for mysql just declare it with AUTO_INCREMENT on the id field, for postgres you can set the data type to serial, as for separating each line use the php explode function
here's a little example
<?php
$dbh = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');
$query = "INSERT into my_table (item_value) VALUES (?)";
$data = 'itemOne,itemTwo,itemThree,itemFour';
$st = $dbh->prepare($query);
foreach(explode(',', $data) as $r) {
// user array($r) for php 5.3 or lower
$st->execute([$r]);
}
This uses PDO which is the recommended method for handling database connections
Something like this should split them up and give the option for insertion in the db:
<?php
$item_value = 'itemOne,itemTwo,itemThree';
$item_array = explode(",",$item_value);
foreach($item_array as $key => $value){
// insert into the db here
$query = "INSERT INTO table_name set item_value = '".mysql_real_escape_string($value)."', ID = '".($key + 1)."'";
// however you choose to connect and insert into the database goes here :)
}
?>

pdo - prepared statement loses data?

I have a query (PHP, Mysql) a table named 'table' that looks like this:
id | name
-------------
6 | abc
10| xxx
52| def
And a query:
$ids = '5,62'
$name = $pdo -> prepare('SELECT id, name FROM table WHERE id IN ( :ids )');
$name -> bindValue(':ids', $ids, PDO::PARAM_STR);
$name -> execute();
$name = $name->fetchAll(PDO::FETCH_ASSOC);
print_r($nazwa);
I would expect to get a result like
id | name
-------------
6 | abc
52| def
Unofrtunately i get only:
id | name
-------------
6 | abc
As if second value would be ignored. If I change the query to:
$name = $pdo -> prepare('SELECT id, name FROM table WHERE id IN (' $ids ')');
It all goes right. Can you tell me why prepared statement doesnt take under consideration imploded table with commas?
Because the comment field does not allow to write that well, here an answer that is merely a comment:
Let's say you have two IDs:
$name = $pdo->prepare('SELECT id, name FROM table WHERE id IN ( :id1, :id2 )');
Let's say you have three IDs:
$name = $pdo->prepare('SELECT id, name FROM table WHERE id IN ( :id1, :id2, :id3 )');
You see the pattern? You have as many values as you have IDs. Formulate the prepare statement as well as perform the bind statements accordingly to the number of IDs you have.
So the answer is: You need to change your code so that it actually reflects the number of IDs you want to handle. The MySQL server will not magically interpret a comma-separated list inside a string as multiple IDs. Instead you need to tell the server about each single ID.

Categories