PHP script looping string - php

I have a string, I need to put this information into a database.
I'm not sure of the best way to manipulate the string to use with an insert script. my skill level is very low. I've read a bit about looping but dont know how or where to begin.
Is there a better way to manipulate the string to make db insert easier?
Many thanks
<?php
$date = $_SESSION['date'];
$string="UnAllocated,SUSY MCGRANAHAN,R,null,null;
UnAllocated,BERNADINE WASHER,A,null,null;
UnAllocated,DAVID KEHRER,R,null,null";
/*
I have been trying to break it down in the following way.
$new = preg_split("[;]", $string);
$x1=(explode(',', $new[1]));
$x2=(explode(',', $new[2]));
I would like to insert it into the following table
INSERT INTO table ("date, team, name, driver, car
values
('$date' ,'$x1[0]', '$x1[1]', '$x1[2]', '$x1[3]'),
('$date' ,'$x2[0]', '$x2[1]', '$x2[2]', '$x2[3]')");
*/
Table
| date | team | name | driver | car |
---------------------------------------------------------
| cur | unallocated | SUSY.. | A | null |
| cur | unallocated | BERN...| R | null |

You can use below code to insert into your database table.
<?php
$string="UnAllocated,SUSY MCGRANAHAN,R,null,null;
UnAllocated,BERNADINE WASHER,A,null,null;
UnAllocated,DAVID KEHRER,R,null,null";
$arr = explode(';', $string);
foreach($arr as $row){
$arr_row = explode(',', trim($row)); // Converting each line to array which can be used as values.
print_r($arr_row);
// Write your insert statement into your database.
// e.g INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
}
Now you can use $arr_row[0], $arr_row[1] ... and so on to build your sql.

Related

How to insert entirely json object to table

Suppose I have a table like the following:
id| name | family
---+------+---------
1 | iman | marashi
2 | mike | ...
3 | john | ...
4 | |
and I also have an Json object to insert to the table like the following:
{"name ":"will","family":"smith"}
How can I insert together an Json object to a table given that the fields of the table and the keys of the Json object are the same?
Without having to parsing the Json object.
I don't want to use this method:
$name = $data["name"];
$family = $data["family"];
If you're using PDO, you can provide an associative array to fill in the parameters of a query.
$query = $conn->prepare("INSERT INTO yourTable (name, family) VALUES (:name, :family)");
$data = json_decode($json_object, true);
$query->execute($data);
I think that Barmar provided the correct answer if you are running PDO.
For the sake a completeness, you could also do this purely with MySQL, using json_extract() to read directly from the json string given as parameter:
insert into mytable (name, family) values(
json_unquote(json_extract(:js, '$.name')),
json_unquote(json_extract(:js, '$.family'))
);
Demo on DB Fiddle:
create table mytable (
id int auto_increment primary key,
name varchar(50),
family varchar(50)
):
insert into mytable (name, family) values(
json_unquote(json_extract('{"name":"will","family":"smith"}', '$.name')),
json_unquote(json_extract('{"name":"will","family":"smith"}', '$.family'))
);
select * from mytable;
id | name | family
-: | :--- | :-----
1 | will | smith

API-call JSON into MySQL

I'm working on a research project where we want to insert a JSON file (from an API-call) into a mysql database. I found multiple examples but I don't know where to begin because there are multiple objects and arrays. A second problem is that the columns and rows are separate arrays (I think?).
Our goal is to fill (daily, hourly, etc) a database that looks likes this (it is an example and we do have multiple items):
-----------------------------------
| Date | Value2 | Value3 | Value4 |
-----------------------------------
| 01-01-2015 | 123 | 1234 | 12345 |
-----------------------------------
| 02-01-2015 | 343443 | 4w3543422 | fref4rw4 |
-----------------------------------
| 03-01-2015 | 234422r | wrfrw3434 | 2432rfr42324 |
-----------------------------------
Question is how can I get those values from the JSON (which isn't static: sometimes there will be seven days, sometimes less and sometimes more)? Where to begin?
Code from #Marmik did the trick!
<?php
$array = json_decode($json_data,true);
$sql_inserts = array();
foreach($array['reportitem']['rows']['r'] AS $row)
{
$sql_inserts[] = "('".$row[c][0]."','".$row[c][1]."','".$row[c] [2]."','".$row[c][3]."')";
}
$insert_values = implode("'",$sql_inserts);
$sql = "INSERT INTO table_name (date,Value2,Value3,Value4) $insert_values ;";
?>
I think using foreach loop after decoding the JSON to PHP Array it can be worked out.
<?php
$array = json_decode($json_data,true);
$sql_inserts = array();
foreach($array['reportitem']['rows']['r'] AS $row)
{
$sql_inserts[] = "('".$row[c][0]."','".$row[c][1]."','".$row[c][2]."','".$row[c][3]."')";
}
$insert_values = implode("'",$sql_inserts);
$sql = "INSERT INTO table_name (date,Value2,Value3,Value4) $insert_values ;";
?>
And this SQL statement is created by JSON array's data.

how to use one mysql query, update data without duplicate?

id | title | text
1 | aa |
2 | aa |
3 | aa |
I have some data from json data, i am not sure how many datas have duplicate in it.
$json = '[{"a":"1","b":"bb"},{"a":"2","b":"cc"},{"a":"3","b":"bb"}]';
$array = json_decode($json);
foreach($array as $key){
UPDATE table SET text = '".$key->b."' WHERE id = '".$key->a."' and title='aa'");
}
For example, as this situation, $key->b has 2 data bb from the json data, I only want update the first one and check if bb has already in the database, then ignore update.
id | title | text
1 | aa | bb
2 | aa | cc
3 | aa | <-ignore updtae, left the data empty
I know there have an easy way, first select * from table where text != '$key->a' for check, but this will cost 2 mysql query and make one more foreach, so
how to use one mysql query, update data without duplicate?
many thanks.
If your database is MySQL, maybe you can use the ON DUPLICATE KEY UPDATE.
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
I suggest using an array to store all the values of b you have used so far and only run the UPDATE if the value didn't exist yet.
$json = '[{"a":"1","b":"bb"},{"a":"2","b":"cc"},{"a":"3","b":"bb"}]';
$usedValues = array();
$array = json_decode($json);
foreach($array as $key){
if(!isset(usedValues[$key->b])) {
mysql_query("UPDATE table SET text = '".$key->b."' WHERE id = '".$key->a."' and title='aa'");
usedValues[$key->b] = true;
}
}
EDIT: If your database already has values for text this may still produce duplicates, but you could do a SELECT DISTINCT ´text´ and populate the $usedValues array with them.

get $_POST name and value in php foreach loop to build a long string

I need to put alot of radio button values into the database, so I post 300 values to a processing page, where I need to sort things out a bit.
I want to be able to differentiate between each radio buttons value and name (when posted) so I can insert them into the database. This is my code: (but maybe i need a jagged array?)
VALUE:
foreach ($_POST as $key => $value)
{
$value = $value.',';
}
POST NAME: ???
foreach ($_POST[name]?? as ??? => $postname)
{
$postname = $postname.',';
}
Then I need to differentiate between the value and name and put in the correct columns in the database:
mysql_query("INSERT INTO tabke SELECT '$longstring' or die(mysql_error());;
I don't know why you want to insert using SELECT, as this construct is to insert from already existing table data. You can, however, insert multiple VALUES with a single statement. You'd need to do :
// you should filter out values from your $_POST...
$ignoredFields = array('submit', ...);
$fields = array_intersect_key($_POST, array_flip($ignoredFields));
$values = array();
foreach ($fields as $key => $value) {
$key = mysql_real_escape_string($key);
$value = mysql_real_escape_string($value);
$values[] = "'{$key}', '{$value}'";
}
// creation the insert string
$query = 'INSERT INTO `tabke` (`key`,`value`) VALUES ('.implode(,'),(', $values).')';
$result = mysql_query($query);
** Note ** : I suppose that your table tabke look something like
+---------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| key | varchar(64) | NO | | NULL | |
| value | text | NO | | NULL | |
+---------+------------------+------+-----+---------+----------------+
As long as your query does not extend max_allowed_packet, this will work just fine. In case your data exceed that size, you can simply use array_chunk and iterate through the chunks and building the INSERT with each chunks.
It's going to be $key, but there will only be one post per distinct radio "Group", also you should be sanitizing your inputs for SQL injection.

MySQL escaped strings problem

In some PHP code, I have an mysql_real_escape_string()'d term, like foo\'s. I search that in my database (where it is also stored as foo\'s) like so:
mysql_query("SELECT * FROM coupons WHERE retailerName LIKE '%" . $searchTerm . "%'");
The query should look like this without variables:
SELECT * FROM coupons WHERE retailerName LIKE '%foo\'s%'
If I search f, fo, or foo, then the search works. But if I search foo's then the search doesn't work (keep in mind that the actual query takes an escaped string, so everything should match up).
Perhaps the interface from you program to mysql (JDBC or similar) is adding extra escape characters to your string. If the same mechanism is not what put the data into the database, try doing an insert to see how the data gets stored.
Mysql can handle the query through it's own interface
mysql> describe test_table;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| col1 | varchar(20) | YES | | NULL | |
| col2 | varchar(20) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.01 sec)
mysql> insert into test_table (col1, col2) values ('col1value', 'foo\'s');
Query OK, 1 row affected (0.04 sec)
mysql> select * from test_table where col2 like '%foo\'s%';
+-----------+-------+
| col1 | col2 |
+-----------+-------+
| col1value | foo's |
+-----------+-------+
1 row in set (0.00 sec)
If it's stored as foo\'s in DB, then there are 2 options - either you are double-escaping (i.e., using mysql_real_escape_string() twice), or you are escaping values that "something" (e.g., magic quotes) has already slashed.
Check if you have magic_quotes_gpc enabled.
Here's PHP5.3 code for stripping "magic quotes" automatically (can be used in config file). For older PHP, callback function would look differently, but you should get the idea from this.
// remove slashes, if they are being automatically added
if ( get_magic_quotes_gpc () ) {
$stripslashes = function($value) use(&$stripslashes) {
if ( is_array($value) ) {
return array_map($stripslashes, $value);
}
return stripslashes($value);
};
$_GET = array_map($stripslashes, $_GET);
$_POST = array_map($stripslashes, $_POST);
$_COOKIE = array_map($stripslashes, $_COOKIE);
unset($stripslashes);
}

Categories