Foreach loop from array and how to contain it - php

I've been struggling with this problem for a week now and i don't have any more option but to ask a question here in stackoverflow.
I'm currently using PHP Spout for reading rows of a xlsx file and the array looks like this
Array
(
[Name] => abcd1234
[Address] => abcd1234
[Number] => abcd1234
)
Array
(
[Name] => abcd1234
[Address] => abcd1234
[Number] => abcd1234
)
Array
(
[Name] => abcd1234
[Address] => abcd1234
[Number] => abcd1234
)
The foreach loop looks like this
// Number of sheet in excel file
foreach ($reader->getSheetIterator() as $sheet) {
// Number of Rows in Excel sheet
foreach ($sheet->getRowIterator() as $row) {
// It reads data after header. In the my excel sheet,
// header is in the first row.
if ($count1 > 1) {
// Data of excel sheet
$data['Name'] = $row[0];
$data['Address'] = $row[1];
$data['Number'] = $row[2];
//Here, You can insert data into database.
//print_r($data);
//$sql = mysqli_query($connection, "INSERT INTO address(Name, Address, Number) VALUES ('$row[0]', '$row[1]', '$row[2]')");
foreach ($data as $key => $value) {
$value = trim($value);
if (empty($value)){
echo $output = "Row ".$count1." Column ".$key." is empty <br/>";
}
}
}
$count1++;
}
}
I have a problem where i need to loop all arrays and find the missing rows on each columns which i manage to do and now i need to ignore or count the duplicate values on rows. I tried doing array_unique but it did not work on the array i was using.
I also tried to insert my array into another array but i also had problems inserting into. I probably have issues with declaring my array but i'm still having some problems. How do i ignore the duplicates on multiple different arrays or how do i merge all the separate arrays into one array inside a foreach loop? Sorry i'm kinda new to arrays in php and thank you if someone is reading this.
Edit: The output that i was aiming for is to count the number of missing values inside an array/row from the xlsx file. Which is just like on the foreach loop in the example code. Example:
Row 213 Column Name is empty
Row 214 Column Name is empty
Row 214 Column Address is empty
This is what it looks like when i echo the missing values on rows from a xlsx file.
Now i need to validate if the xlsx file has duplicate rows. My first initial idea was to either echo rows with duplicate values i.e
Row 213 Column Name is has duplicates
Row 214 Column Name is has duplicates
Row 214 Column Address is empty
But everything got complicated which led me to try and use array_unique but also had problems because the way the array is being presented by the xlsx file.

As suggested in a comment on your question, use prepared statements.
As for a solution to your problem, when the SQL query executed and inserts the data successfully, add the unique identifier to an array. Before inserting new data into the database, check to see if the unique identifier is already in the array of inserted values. I'm on my phone, otherwise I'd provide an example. But that should help.

I hope this will get you going:
$data = array();
foreach ($sheet->getRowIterator($startRow = 2) as $row) {
$data[] = array('Name' => $row[0], 'Address' => $row[1], 'Number' => $row[2])
}
$names = array_column($data, 'Name');
$addresses = array_column($data, 'Address');
$numbers = array_column($data, 'Number');
$unique_names = array_unique($names);
$unique_addresses = array_unique($addresses);
$unique_numbers = array_unique($numbers);
$dup_names = array_diff($names, $unique_names);
$dup_addresses = array_diff($names, $unique_addresses);
$dup_numbers = array_diff($names, $unique_numbers);
And once you get to inserting into your database, here's how you use a prepared statement:
$stmt = $connection->prepare("INSERT INTO address(Name, Address, Number) VALUES (?, ?, ?)");
foreach ($data as $row) {
$stmt->bind_param('sss', $row['Name'], $row['Address'], $row['Number']);
$stmt->execute();
}

Related

PHP Array duplicates: every string key has numeric key

I'm trying to get an array with utf-8 values from an MS-SQL query.
Nearly everything works fine, except that the result array looks like this:
Array (
[id] => 1;
[0] => 1; // this is redundant
[countryName] => england;
[1] => england; // this is redundant
)
I don't want the duplicate numeric keys. Why are they even created? The code which is leading to this result is:
# execute the query
foreach ($pdoConnection->query($sqlStatement) as $row) {
// encode row in utf8 so json works and save row in array
$output[] = array_map('utf8_encode', $row);
}
Thanks for any idea how that can be solved.
You need to fetch as associative. Follow this example:
$stmt = $this->db->prepare('SELECT title, FMarticle_id FROM articles WHERE domain_name =:domain_name');
$stmt->bindValue(':domain_name', $domain);
$stmt->execute();
$article_list = $stmt->fetchAll(PDO::FETCH_ASSOC);
Reference: PDOStatement::fetchAll
Try replacing this line,
foreach ($pdoConnection->query($sqlStatement, PDO::FETCH_ASSOC) as $row)
That flag is for getting associative records.

Insert an array with multiple values, some of which are an array on its own to database

ISSUE
Hello, I have multiple PHP Arrays with multiple values that I am inserting to a SQL database from an XML file. Some of those values are an array on its own (Multi-dimensional array) but the value only gets stored as "Array", none of the sub-values get passed.
EXAMPLE ARRAY
[0] => Array
(
[A] => This is the Title
[B] => This is the Description
[C] => Array
(
[0] => Value 1
[1] => Value 2
[2] => Value 3
)
)
I have no problems inserting single values, so A and B will get inserted without a problem. But C will only get inserted as "Array".
INSERTION CODE
// This is the PHP array that contains multiple items
$Items
// There can be multiple Arrays in this XML so i have to loop through each one
foreach($Items as $Item => $value) {
$result = $mysqli->query("INSERT INTO database_name (A, B, C)
VALUES ('$value[A]', '$value[B]', '$value[C]');");
}
I want to serialize the [C] and put it in a single column. But if i do it in the foreach loop like this serialize("$value[C]") only "Array" gets passed to the value. I am a bit lost.
I will appreciate any help I can get.
Check each value as an array. If yes, serialize it else use as it is. Check below code, it might help you
// This is the PHP array that contains multiple items
$Items
// There can be multiple Arrays in this XML so i have to loop through each one
foreach($Items as $Item => $value) {
$A = is_array($value[A]) ? serialize($value[A]) : $value[A];
$B = is_array($value[B]) ? serialize($value[B]) : $value[B];
$C = is_array($value[C]) ? serialize($value[C]) : $value[C];
$result = $mysqli->query("INSERT INTO database_name (A, B, C)
VALUES ('$A', '$B', '$C');");
$A=$B=$C='';
}
Make empty temporary variables each time to hold new values.
The easiest and fastest way to serialize (and de-serialize later when needed) is using JSON. Your query would then become:
$result = $mysqli->query("INSERT INTO database_name (A, B, C)
VALUES ('$value[A]', '$value[B]', '" . json_encode($value[C]) . "');");
You should use prepared statement for mysqli and json_encode to serialize values:
foreach($Items as $Item => $value) {
$stmt = $mysqli->prepare("INSERT INTO database_name (A, B, C)
VALUES (? , ?, ?)")
$stmt->bind_param("sss", json_encode($value[A]), json_encode($value[B]), json_encode($value[C]));
$stmt->execute();
or if you are sure that only C value is array:
foreach($Items as $Item => $value) {
$stmt = $mysqli->prepare("INSERT INTO database_name (A, B, C)
VALUES (? , ?, ?)")
$stmt->bind_param("sss", $value[A], $value[B], json_encode($value[C]));
$stmt->execute();
You are referencing the Array object when call $value[C]
Loop over the [C] to get its contents:
foreach($items as $item) {
foreach($item as $itemDeep) {
// do stuff
}
}

Script inserts the same values to the database

When I run this code, I get some fields updated to my MySQL table but for some reason it is all the same value.
$query = $this->Connection_model->get_custom_db('sender')->get($sender_table);
foreach ($query->result() as $row) {
$data = array(
$sender_row => $row->$sender_row
);
$this->Connection_model->get_custom_db('receiver')->update($receiver_table, $data);
}
print_r($data) returns:
Array (
[Strasse] => Pantherstr. ) Array (
[Strasse] => Minimalweg ) Array (
[Strasse] => Blankeneser Weg )
How can I fix this?
Looks like a $ to many in $row->sender_row:
$query = $this->Connection_model->get_custom_db('sender')->get($sender_table);
foreach ($query->result() as $row) {
$data = array(
$sender_row => $row->sender_row
);
$this->Connection_model->get_custom_db('receiver')->update($receiver_table, $data);
}
What you will find is happening is that in all of your Rows, the Strasse fields will be getting set to
Pantherstr, then to Minimalweg then to Blankeneser Weg.
So what you are seeing is the Final Value that is being written to ALL Rows.
I do not see where your Where is. If you want to update a particular row or rows, you need to identify those rows. Else ALL rows will be getting updated each time through your loop.

How to remove numbers from an 2d array php

I've got an 2d array that stores data from my database table then puts it in a json file. And since I'm not calling my column names because it is dynamic, the array is adding it's incrementation (numbers) automatically with the table cell detail, I don't want this.
Here is the json file example
{"0":"1","Fix":"1","1":"Sunday, May 11, 2014","Date":"Sunday, May 11, 2014","2":"FT","Time":"FT","3":"Cardiff City","Home":"Cardiff City","4":"1-2","Score":"1-2","5":"Chelsea","Away":"Chelsea","6":"Cardiff City Stadium (27,716)","Stadium":"Cardiff City Stadium (27,716)"}
I attempted to remove it in php like this
//Select everything in table
$query = mysql_query("SELECT * FROM ".$tablename);
//Storing the data into one arrays witk the ey => value
while($r=mysql_fetch_array($query)){
//Store the data as a 2d array
$json[] = $r;
}
foreach ($json as $key => $value) {
# code...
if(preg_match('/[0-9]/', $key)){
unset($json[$key]);
}else{
}
}
//Display the JSOn data
$o = fopen($tablename.'.json', 'w');
echo fwrite($o, json_encode($json));
fclose($o);
use MYSQL_ASSOC as a second parameter of the mysql_fetch_array() function.

Build string from array omitting empty or NULL values in PHP

I am trying to build an array from a list of URL parameters to transact with a database. Basically I have several functions that do different things. (Insert, Update, etc) so depending on what it is specifically trying to do it may not need ALL columns in the database at all times.
So say I have these 5 potential parameters that might get passed: id,gr,bl,yw,re
If I am inserting a new row all 5 coulmns need some sort of value. If I am say updating the bl column then I only pass the id and bl parameters.
So I am doing this to build the query string(not actual code just example):
foreach($_GET as $key => $value) {
$key = strtolower($key);
if (preg_match($acceptedGETS,$key)) $$key = $value;
}
$table_col = array (
'p_id' => $_GET['id'],
'p_gr' => $_GET['gr'],
'p_bl' => $_GET['bl'],
'p_yw' => $_GET['yw'],
'p_re' => $_GET['re']);
$vstring = implode(',' , $table_col);
Now this works perfectly, as long as ALL variable keys have a value (or not NULL). My question is, how can I build a string from an array, but exclude the keys that don't get passed values. Right now if keys are missing values I get this for example:
URL: http://www.mysite.com/myscript.php?id=4&re=9 would get me:
4,,,,9
when I need to just get 4,9
Thanks!
Use $get = array_filter($_GET) and it will get rid of empty or null values.
Try
$vstring = "";
$acceptedGETS = array("id", "gr", "bl", "yw", "re");
$values = array();
foreach ($_GET as $key => $value)
{
$k = strtolower($key);
if (!in_array($k, $acceptedGETS))
continue;
$values[$k] = $value;
}
$vstring = implode(",", $values);
Here is another way using just filter_input_array and set of filters
$args = array(
'id' => FILTER_VALIDATE_INT,//if it is an integer
'gr' => FILTER_SANITIZE_STRIPPED,//in case it is a string
'bl' => FILTER_SANITIZE_STRIPPED,
'yw' => FILTER_SANITIZE_STRIPPED,
're' => FILTER_SANITIZE_STRIPPED,
);
//Filter array values to avoid bad data if nothing found NULL returned
$myInputs = filter_input_array(INPUT_GET, $args);
//if it is an array join it with coma
if(is_array($myInputs))
$myInputs = implode(',', $myInputs);

Categories