PHP Array duplicates: every string key has numeric key - php

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.

Related

Foreach loop from array and how to contain it

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();
}

Updating multiple rows in mysql using php for a json array?

I have a json array which needs to be parsed in such a way that I can update multiple rows in one mysql query.
This is my json array:
[{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1000"}
,{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1001"}
,{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1003"}]
I am trying a update query something like this:-
$query="UPDATE urd_voucher_table SET voucher_status ='$status', doc_no = '$docNo' WHERE voucher_id ='$vc_id'";
I want to know how can I parse the above json in order to get individual values for voucher_status, doc_no and voucher_id.
Any help is appreciated.Thank you.
Use json_decode()
Decode the JSON and loop over the decoded array.
<?php
$json = '[{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1000"},{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1001"},{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1003"}]';
$arr = json_decode($json, TRUE); // Observe the second parameter. If it is TRUE, associative array will be returned irrespective of what json is.
if (! empty($arr)) {
foreach ($arr as $elem) {
extract($elem);
$query="UPDATE urd_voucher_table SET voucher_status ='$voucher_status', doc_no = '$doc_no' WHERE voucher_id ='$voucher_id'";
// Add your code here.
}
}
Reference of extract()
use json_decode() it will return an associative array with key, value pair like :
$strJson = '[{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1000"},{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1001"},{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1003"}]';
$arr = json_decode($strJson);
will return:
Array ( [0] => stdClass Object ( [doc_no] => ADV103 [voucher_status] => closed [voucher_id] => URDV1000 ) [1] => stdClass Object ( [doc_no] => ADV103 [voucher_status] => closed [voucher_id] => URDV1001 ) [2] => stdClass Object ( [doc_no] => ADV103 [voucher_status] => closed [voucher_id] => URDV1003 ) )
now using loop you can fetch data & insert/update database.
You need to decode the json string into an array, loop through the results and run the update query. Please see my example below...
$rows = json_decode('[{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1000"},{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1001"},{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1003"}]');
foreach ($rows as $row) {
$query="UPDATE urd_voucher_table SET voucher_status ='{$row['voucher_status']}', doc_no = '{$row['doc_no']}' WHERE voucher_id ='{$row['voucher_id']}'";
// ... Run query etc..
}
First use json_encode() and then iterate result array in foreach. Like following:
$jsonString = '[{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1000"},{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1001"},{"doc_no":"ADV103","voucher_status":"closed","voucher_id":"URDV1003"}]';
$json_decoded = json_decode($jsonString);
foreach($json_decoded as $index=>$val){
$status = $val->voucher_status;
$docNo = $val->doc_no;
$vc_id = $val->voucher_id;
$query="UPDATE urd_voucher_table SET voucher_status ='$status', doc_no = '$docNo' WHERE voucher_id ='$vc_id'";
//execute query here
}
More info on http://www.geeksengine.com/database/data-manipulation/bulk-insert.php
Follow these steps
decode json
apply foreach loop per record
Built and concat data for this part for each record in JSON
for e.g. (a,e,r),(br,t,y),(t,y,c);
Hard code this part in query "Insert into table (c1,c2,c3) VALUES "
And attche data that was created in step 3.
Final query will be
Insert into table (c1,c2,c3) VALUES . STEP 3

convert PDO resultset array to accessible Array PHP

I am using PDO statement like below
$sql1 = "select food_typename from foodtypes WHERE 1";
$statement1 = $pdo->prepare($sql1);
$statement1->execute();
$results1 = $statement1->fetchAll(PDO::FETCH_ASSOC);
print_r($results1);
I am getting output as below:
Array
(
[0] => Array
(
[food_typename] => Punjabi
)
[1] => Array
(
[food_typename] => Indian
)
)
I want it be like
Array('Punjabi','Indian')
Any suggestions please?
If you're running PHP >= 5.5
$results = array_column($results1, 'food_typename');
If you're running earlier versions of PHP,
$results = array_map(
$results1,
function($value) {
return $value['food_typename'];
}
);
Though I don't really understand why you can't work with the original array in the first place
You can use array_map but foreach works just as well and actually runs faster than array_map for cases like this:
// Set a test array.
$results1 = array();
$results1[] = array('food_typename' => 'Punjabi');
$results1[] = array('food_typename' => 'Indian');
// Set the final reults in an array.
$results_final = array();
foreach ($results1 as $results1_value) {
$results_final[] = $results1_value['food_typename'];
}
// Dump the line array for debugging.
echo '<pre>';
print_r($results_final);
echo '</pre>';
And the output of that would be:
Array
(
[0] => Punjabi
[1] => Indian
)
The query way:
SELECT GROUP_CONCAT(food_typename), 1 AS dummy
FROM foodtypes
GROUP BY dummy
Then you need to retrieve the first field of the only record you will get back from mysql, and turn it into an array: see return group_concat data as array

preg_match_all array insert into mysql database loop not working properly

I'm trying to preg_match_all the first 12 digit number found in a mysql field, and insert that number in another field, looping through all results from the Select statement.
I have the following, which puts only the first result it finds in all the fields, so every field3 gets the same 12 digit number inserted, that 12 digit number being from the lowest unique ID field found by the Select statement. Any help with this would be greatly appreciated.
<?php
$query = mysql_query("SELECT * FROM `dbase`.`table` WHERE field1 IS NOT NULL AND field3 IS NULL");
$regexp ='/[0-9]{12}/';
while ($row = mysql_fetch_assoc($query)){
$result=($row["field1"]);
preg_match_all($regexp,$result,$matches,PREG_PATTERN_ORDER);
foreach($matches[0] as $match => $where){
$id=($row["field2"]);
$sql="UPDATE `dbase `.`table ` set field3 = $where WHERE field2 = '$id'";
mysql_query($sql);
}
}
?>
I added
print_r( $matches );
and the output was an array with one result, the number being place in all the fields:
Array
(
[0] => Array
(
[0] => 290970571788
)
)
The curly bracket change fixed the print_r output to show the the list of 12 digit numbers in this format (only first two are shown):
Array
(
[0] => Array
(
[0] => 151104658286
)
)
Array
(
[0] => Array
(
[0] => 271249191324
)
)
Thanks for that.
Utilizing the answers and suggestions given here, I've edited the code to show the final working version. The last big issue was getting the 2nd select statement to use the array result, properly looping and inserting each value in the proper row. Also cleaned up the 1st select statement and changed from preg_set_order to preg_pattern_order.
It shouldn't be
{while ($row = mysql_fetch_assoc($query))
}
but
while ($row = mysql_fetch_assoc($query)) {
}
You don't want to create code block with while statement but you want to provide code block for it.
And also you're using same WHERE condition in SELECT and UPDATE so it'll update all selected rows with same value (all will match that condition).

How to get data from database by using $query->result() in codeigniter without foreach loop?

I have just started using CodeIgniter and want to get data from database using $query->result(), but without a foreach loop. Here is my current code:
$this->db->select('m_name');
$query1 = $this->db->get("marchant_details",1);
$rows1 = $query1->result();
However, I don't want to use a foreach loop like this, to retrieve the data:
foreach($query1->result() as $rows1)
{
$name[] = $rows1->m_name;
}
Can anyone offer an alternative solution?
I just did a quick search. I'm going to sleep, but can you try something like this:
$query->result_array();
If it doesn't work, I'll check tomorrow.
source: user-guide Maybe it will come handy.
There are two assumptions: either I misunderstood the question or the others did.
The point: by passing 1 as second parameter to $this->db->get(); method, it sets LIMIT 1 to the query and you'll get only 1 row as result.
So, why should you need to use a loop on a single row db result?
If you use $query->result(); the result would be something like:
Array
(
[0] => stdClass Object
(
[m_name] => Foo
)
)
To get the m_name value you can do the following:
$result = $query->result();
echo $result[0]->m_name;
By any reason, if you need a numeric array contains the value (as you did it in your loop) you can simply do it by $name[] = $result[0]->m_name;.
And if you use $query->result_array(); the result would be something like:
Array
(
[0] => Array
(
[m_name] => Foo
)
)
To get the m_name value you can do the following:
$result = $query->result_array();
echo $result[0]['m_name'];
But if you stop limiting the query, there are multiple rows in your query result, you can use rows1 = $query1->result_array(); instead. and array_map() to manipulate the elements of the given array:
$rows1 = $query1->result_array();
// `$row1` will be something like this:
Array
(
[0] => Array
(
[m_name] => Foo
)
[1] => Array
(
[m_name] => Bar
)
[2] => Array
(
[m_name] => Baz
)
)
Use array_map() to manipulate the result array:
function getName($array) {
return $array['m_name'];
}
$array = array_map("getName", $rows1);
print_r($array);
If you are using PHP v5.3+ you do the following:
$array = array_map(function($array) {
return $array['m_name'];
}, $rows1);
Well there is the official page in the CodeIgniter User Guide for generating DB query results depicting variations like
$row = $query->first_row()
$row = $query->last_row()
$row = $query->next_row()
$row = $query->previous_row()
If you work with CodeIgniter, its charm is that it effectively quite nicely documented.
I would assume you can go further down the abstraction layers if that's what you want, respectively you can not use the DB class but the class of your choice as custom library or whatever.
Why then are you not happy with the given possibilities, respectively how do you want to generate your query results?
you can do like this
$data=array();
$this->db->select('m_name');
$query1 = $this->db->get("marchant_details",1);
$data['name'] = $query1->result_array();
return $data;
and for more information
result_array(); // For multiple rows
row_array(); // For one row

Categories