from multi dimensional array to MySQL - php

I have a multidimensional array called $data that is basically data extracted from a table into the array.
This is how I get my array using JS_extractor:
set_include_path(get_include_path() . PATH_SEPARATOR . './library/');
require_once 'JS/Extractor.php';
$extractor = new JS_Extractor(file_get_contents('temp.html'));
$body = $extractor->query("body")->item(0);
$table = $body->query("//table[#class='rstatisztika_tabla']")->item(0);
$data = array();
foreach ($table->query('tr') as $i => $tr) {
if ($i == 0) {
continue;
}
$a = $tr->query('.//a');
$a = $a->item($a->length - 1);
$url = $a->getAttribute('href');
$parsed = parse_url($url);
parse_str($parsed['query'], $query);
$data[] = array(
$a->textContent,
$url,
$query['user'],
);
}
//var_dump($data);
when I actually do
var_dump($data);
I get this:
array(3)
{
[0]=> array(3)
{
[0]=> string(4) "Thad"
[1]=> string(7) "http://localhost/index.php?m=karakterlap&user=91"
[2]=> string(2) "91"
}
[1]=> array(3)
{
[0]=> string(4) "Bill"
[1]=> string(8) "http://localhost/index.php?m=karakterlap&user=110"
[2]=> string(3) "110"
}
[2]=> array(3)
{
[0]=> string(7) "Thadson"
[1]=> string(7) "http://localhost/index.php?m=karakterlap&user=147"
[2]=> string(3) "147"
}
}
I also have a Mysql database table called warlord
CREATE TABLE IF NOT EXISTS `warlord` (
`id` int(5) NOT NULL default '0',
`name` varchar(35) character set utf8 NOT NULL default '',
`active` tinyint(1) NOT NULL default '1',
UNIQUE KEY `id` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `warlord` (`id`, `name`, `active`) VALUES
(2, 'Admin', 0), (100, 'Thadson', 1), (147, 'John', 1);
From the array, I want to add the new users (Thad & Bill) to the warlord table and set them active (1)
I want the user (Thadson), who is also in the array, to stay active (1)
However I want the user (John) who is not in the array, set to inactive (0)
and leave admin who is also not in the array (and is already inactive) inactive (0)
I know this is a very beginners question, but how do I do this?
Thanks

You might want to use array_map function to set a callback function for the multi-array and process it accordingly:
array_map

I saw this and I have tried it:
$data = array();
for($i=0; $i<count($data_array); $i++){
$data_items[$i] = explode(',', $data_array[$i]); // create a multi-dimensional array
$data[] = '( ' .$data_items[$i][2]. ', '.$data_items[$i][0]. ', '. 1 .')';
}
$sql = "INSERT INTO warlord(id, name, active) VALUES ('".$data_items[$i][2]."','".$data_items[$i][0]."','1') ";
...to get the data into my table
I ignore the 2nd elements from the array (The ones that look like this: [1]=> string(7) "user=91") and I try to insert elements [2] and [0] into the table and make the new users active with placing 1 into the active field.
This obviously doesn't do all I need (actually it doesn't do any of it) and I have no idea what I'm doing. This is why I'm asking for help.

If I was to approach this question I would firstly try to organise my arrays (the $data array and also the array from the database) into a similar format (possibly using the id as the array key) so that I could use array_intersect to work out the people in both $data and $database (ie. people who should set active) and array_diff to work out the people in $data and not in $database (ie. the people who need to be added to the database) and then array_diff again (with $database first this time) to work out the people in $database and not in $data (ie. the people who should be set inactive).
Hope this helps put you on the write track. Sorry but I don't have the time to actually write the code for you.

Related

Check if array contains a duplicate value in string with PHP

I want to check if my array contains a duplicate value. I have a form where i pass a Chapter ID with the following method:
<input name="chapter_id[]" type="number" value="<?= $row_chapter_list['chapter_id'] ?>">
To update my database i pick this input and do the update w/o any issues:
if (isset($_POST['chapter_id'])) {
// Update Kapitelnummer
$statement = $pdo->prepare("UPDATE questionaire_chapter SET chapter_id = :chapter_id WHERE id = :id");
$statement->bindParam(":chapter_id", $chapter_id, PDO::PARAM_STR);
$statement->bindParam(":id", $id, PDO::PARAM_INT);
foreach ($_POST['chapter_id'] as $index => $chapter_id) {
$id = $_POST['chapter_inc_id'][$index];
$statement->execute();
}
}
A typical var_dump result looks like:
array(3) { [0]=> string(1) "1" [1]=> string(2) "12" [2]=> string(2) "12" }
In this array example the value "12" is present in two strings. I would like to create a mechanic to count double values and and use the result in a PHP if/else. i want to avoid that the a duplicate chapter ID gets written into my database.
My first try to count the string is this:
print_r(array_count_values($_POST['chapter_id']));
Which gives me a result like this
Array ( [1] => 1 [12] => 2 )
Now i am missing the method to implement a if else to check if the result is not 1.
Any idea how to do this?
You can use array_unique() to get an array where any duplicates has been filtered out. Using that, you can compare it to the original array:
if ($array != array_unique($array)) {
echo "The arrays are not the same, which means that there are duplicates";
}

How to convert a database row into a JSON string of values only in PHP?

I am trying to provide a count of certain sizes of lockers. My SQL statement is:
$sql = "SELECT Concat(`Height`, 'x', `Width`, 'x', `Depth`) as Locker, count(*) from lockers GROUP BY `Height`, `Width`, `Depth` ";
a var_dump in a loop of the rows gives me the following (many more rows are possible):
array(2) { ["Locker"]=> string(8) "15x30x45" ["count(*)"]=> int(6) }
array(2) { ["Locker"]=> string(8) "45x30x45" ["count(*)"]=> int(4) }
I want to obtain a JSON string that looks like this:
{
"SizeList": {
"15x30x45": 6
"45x30x45": 4
}
}
I have tried a lot of different methods (including converting it into an object, but I can't get the value of the size as an index. For example, I get different variations of:
[0]=> string(31) "{"Locker":"15x30x45","count(*)":6}"
[1]=> string(31) "{"Locker":"45x30x45","count(*)":4}"
Any help appreciated...
You could just manually create the object like this:
$sizeList = new stdClass();
foreach ($results as $row) {
$sizeList->{$row['Locker']} = $row['count(*)'];
}
echo json_encode(array('SizeList' => $sizeList));

How do I insert an array of id into database MySQL?

I'm trying to insert an array of IDs into a database table, but at the moment it only inserts 1 row when it's meant to do multiple rows. My array of IDs contains just (filmid) Does anyone know what the problem is?
$pm = "2";
$id = "2";
if($stmt1->execute())
{
$films=array();
foreach($_SESSION['products'] as $key=>$product)
{
array_push($films, $product['filmid']);
$f_id = implode(",", $films);
$stmt2 = $this->conn->prepare("INSERT INTO `filmPurchase` (`fpid`, `payid`, `filmid`, `shopid`, `custid`, `price`) VALUES (NULL, :id, :f_id, :pm, :pm, '8')");
$stmt2->bindParam('pm',$pm);
$stmt2->bindParam('id',$id);
$stmt2->bindParam('f_id',$f_id);
$stmt2->execute();
}
}
I've tried to loop over the array with:
foreach($_SESSION['products'] as $key=>$product)
{
var_dump($key);
var_dump($product);
}
This is what outputted:
int(29) array(4) { ["qty"]=> int(1) ["filmtitle"]=> string(45) "The Lord of
the Rings: The Return of the King" ["filmid"]=> string(2) "29" ["price"]=>
float(6.99) }
If your placeholder is :id and :pm (as in prepare()) then you must use :id in bindParam()
See php documentation

Array Loop with Mysql Insert

I have an array called $columns :
array(3) {
[0]=>
string(8) "Food"
[1]=>
string(6) "Calories"
[2]=>
string(3) "Carbs"
}
array(3) {
[0]=>
string(8) "Food"
[1]=>
string(6) "Calories"
}
Another called values
array(5) {
[0]=>
string(4) "'Fish'"
[1]=>
string(7) "'100'"
[2]=>
string(13) "'0'"
}
array(6) {
[0]=>
string(4) "'Tatoe'"
[1]=>
string(7) "'100'"
}
I have columns in my database that represent all possible columns that an array has.The arrays could have 5,6 more or less columns depending on the item.
I have this code that is suppose to generate the sql statement in this sense :
INSERT INTO MEALS (the columns in that array) VALUES (the values in the value array)
Here is the code :
for($i = 0; $i < count($column); $i++)
{
echo("INSERT INTO 'MEALS` ($column[$i]) VALUES ($values[$i])\n");
}
The problem is for each "MEAL":
n(per column) number of sql queries will be generated.
as such :
INSERT INTO `MEALS` (Food) VALUES ('Fish')
INSERT INTO `MEALS` (Calory) VALUES ('100')
INSERT INTO `MEALS` (Carbs) VALUES ('0')
Instead of it all being on the same query.
INSERT INTO MEALS (Food,Calory,Carbs) VALUES ('Fish','100','0')
So if i insert in the database, 3 rows will be created.
I know i am missing the logic, any help is appreciated
Why aren't you genererating the two parts of your query (1 variable for columns in insert and 1 variable for values) inside your array loop?
Once your loop is done, simply concatenate your strings :
$query = "INSERT INTO 'MEALS' (" . $var_column_list . ") VALUES (" . $var_values_list . ")";
$query = "insert into table(".join($colomn,','). ") values (\"".join($values,'","')."\")";
Try using variant of above according to your need
Try This....
$colums = implode(',', $array_of_colums);
$values = implode(',', $array_of_values);
$query = "INSERT INTO `tableName` (".$colums.") VALUES(".$values.") ";

Joining 2 mysql tables and generating an array

entries and images and have been trying every way I can find to join them to get the below result
entries:
entry_id
name
images:
entry_id
image_url
I'm using php and would like to be able to retrieve all associated image_url rows for a given entry_id and combine them with the other information from the entries table.
So I have something like:
entries:
1, Brian
2, Steve
3, Jane
images:
1, images/brian1.jpg
1, images/brian2.jpg
2, images/steve.jpg
3, images/jane_1.jpg
3, images/jane_2.jpg
3, images/jane_3.jpg
And would like to get an array back something like
array(3) {
[0]=>
array(3) {
["entry_id"]=>
string(1) "1"
["name"]=>
string(5) "Brian"
["images"]=>
array(2) {
["image_url"]=>
string(17) "images/brian1.jpg"
["image_url"]=>
string(17) "images/brian2.jpg"
}
}
[1]=>
array(3) {
["entry_id"]=>
string(1) "2"
["name"]=>
string(5) "Steve"
["images"]=>
array(1) {
["image_url"]=>
string(16) "images/steve.jpg"
}
}
[2]=>
array(3) {
["entry_id"]=>
string(1) "3"
["name"]=>
string(5) "Jane"
["images"]=>
array(3) {
["image_url"]=>
string(18) "images/jane_1.jpg"
["image_url"]=>
string(18) "images/jane_2.jpg"
["image_url"]=>
string(18) "images/jane_3.jpg"
}
}
}
Thank you!
Having tested none of this, I assume you want something like this:
SELECT * FROM entries INNER JOIN images ON images.entry_id = entries.entry_id
Then loop through those results:
$entries = array();
while ($row = mysql_fetch_assoc($data))
{
if (!isset($entries[$row['entry_id']]))
{
$row['images'] = array();
$entries[$row['entry_id']] = $row;
}
$entries[$row['entry_id']]['images'][] = $row['image_url'];
}
Then you can loop through this return:
foreach ($entries as $entry)
{
foreach ($entry['images'] as $image);
// do something interesting
}
That should about do it for you, but you may have to modify some things.
Do you have your database connection code sorted?
I believe your looking for a full outer join. Check this resource for SQL examples for the different joins.
http://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins
The easy way is something like this
select * from entries, images where images.entry_id = entries.entry_id group by entries.entry_y;
making the join is something like this:
SELECT * FROM entries INNER JOIN images ON images.entry_id = entries.entry_id
For display array like that, you cannot use join, try this :
select all data in table entries
foreach table entries, when foreach include table images
Ex:
$q_e = "SELECT * FROM entries";
$result_entry = mysql_query($q_e);
$entries = array();
$images = array();
while($entry = mysql_fetch_array($result_entry)) {
$q_i = "SELECT * FROM `images` WHERE `entry_id` = '".$entry['entry_id']."'";
$result_image = mysql_query($q_i);
while($image = mysql_fetch_array($result_image)) {
$images[] = array(
'image_url' => $image['image_url']
);
}
$entries[] = array (
'entry_id' => $entry['entry_id'],
'name' => $entry['name'],
'images' => $images,
);
}
echo 'pre>';var_dump($entries);

Categories