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

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

Related

merge two columns into an array

I want to merge two of my columns (yanlis_cevaplar, cevap_icerik) into an array and this code here gives me only one column in array when I print it (yanlis_cevaplar).
How do I fix it?
$cevaplar = "SELECT yanlis_cevaplar FROM cevaplar";
$cevap_sonuc = $conn->query($cevaplar) or die(mysqli_error($conn));
$cevap1 = array(); //create empty array
while ($row = $cevap_sonuc->fetch_array()) { //loop to get all results
$cevap1[] = $row; //grab everything and store inside array
}
$cevaplar2 = "SELECT cevap_icerik FROM cevaplar";
$cevap_sonuc2 = $conn->query($cevaplar) or die(mysqli_error($conn));
$cevap2 = array(); //create empty array
while ($row = $cevap_sonuc2->fetch_array()) { //loop to get all results
$cevap2[] = $row; //grab everything and store inside array
}
$tumcevaplar = array_merge($cevap1, $cevap2);
print_r($tumcevaplar);
Instead of making multiple queries, you can just fetch all the columns you want in one single query:
$cevaplar = "SELECT yanlis_cevaplar, cevap_icerik FROM cevaplar";
$cevap_sonuc = $conn->query($cevaplar) or die(mysqli_error($conn));
// Now you can fetch all the rows straight away without any loop.
// The MYSQLI_ASSOC will return each row as an associative array
$result = $cevap_sonuc->fetch_all(MYSQLI_ASSOC);
print_r($result);
This will result in something like this:
Array
(
[0] => Array
(
[yanlis_cevaplar] => some value
[cevap_icerik] => some value
)
[1] => Array
(
[yanlis_cevaplar] => some value
[cevap_icerik] => some value
)
... and so on ..
)
If this isn't what you want, then you need to show us an example.
I also recommend that you go through some basic SQL tutorials. How SELECT works is SQL 101. Here's one of many guides: https://www.tutorialspoint.com/mysql/mysql-select-query.htm

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.

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

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

PHP MYSQL multidimensional array

I'm having major headaches trying to create a multidimensional array from two separate MySQL selects.... I've been searching here and Google all day and have to finally admit defeat and ask for some help (I'm a newbie as well which doesn't help!!!).
I have two tables, one which contains a single row result per id and another which can contain several rows for an id. What I'm trying to do is combine the two into a multidimensional array.
My code (poor as it may be) looks like this:
require 'php/phpConnection.php';
$sqlString1 = mysql_query("SELECT id FROM supportstaff_section1_a");
$firstArray = array();
$secondArray = array();
while ($r = mysql_fetch_assoc($sqlString1)) {
$applicantID = $r['id'];
$sqlString2 = mysql_query("SELECT educationalname FROM supportstaff_section5 WHERE id = '$applicantID'");
while ($x = mysql_fetch_assoc($sqlString2)) {
$secondArray[] = $x;
}
$firstArray[] = $r + $secondArray;
$secondArray = array();
}
print json_encode($firstArray);
mysql_close($con);
The result is this:
[{"id":"8m8wwy","0":{"educationalname":"GCSE - English"},"1":{"educationalname":"GCSE - Maths"}},{"id":"wiL7Bn"},{"id":"zAw6M1"}]
But I think it needs to look something like this:
[{"id":"8m8wwy","Array2":"[{"educationalname":"GCSE - English"},{"educationalname":"GCSE - Maths"}]"},{"id":"wiL7Bn"},{"id":"zAw6M1"}]
Anyway, how can I insert my second SQL Select into my first SQL Select for each ID.
Thanks for any advice/help.
EDIT
Taken from W3Schools.com:
Array
(
[Griffin] => Array
(
[0] => Peter
[1] => Lois
[2] => Megan
)
[Quagmire] => Array
(
[0] => Glenn
)
[Brown] => Array
(
[0] => Cleveland
[1] => Loretta
[2] => Junior
)
)
I'm trying to make it work like the above.
You need to get a little creative here. Something like the following would work as a join AND with multi-dimensional data:
<?php
require 'php/phpConnection.php';
// ======================================================================
// Create a join query (way faster than several separate ones!)
$sqlquery =
"SELECT SSSA.id, SSS5.educationalname" .
" FROM supportstaff_section1_a SSSA" .
" LEFT OUTER JOIN supportstaff_section5 SSS5 ON SSS5.id = SSSA.ID";
// ======================================================================
// Run the query and get our results
$resultarray = array();
if ($resource = mysql_query($sqlquery)) {
while ($curarray = mysql_fetch_assoc($resource)) {
// Create an array, if it doesn't exist
if (!isset($resultarray[$curarray["id"]]))
$resultarray[$curarray["id"]] = array();
// Add to the array, if not null
$curstring = (string) $curarray["educationalname"];
if ($curstring != "")
$resultarray[$curarray["id"]][] = $curstring;
}
mysql_free_result($resource);
}
// ======================================================================
// Convert from a keyed array to a standard indexed array (0, 1, 2, etc.)
$finalarray = array();
foreach ($resultarray as $id => & $data) {
// Start with just ID
$newarray = array(
"id" => $id
);
// Get the data, if we have any
if (count($data))
$newarray["educationalnames"] = & $data;
// Add to our final array and clear the newarray
$finalarray[] = & $newarray;
unset($newarray);
}
// ======================================================================
// Get the JSON of our result
$jsonresult = json_encode($finalarray);
// ======================================================================
// Echo it to test
echo $jsonresult;
// ======================================================================
// Close the database
mysql_close($con);
?>
And the resulting $jsondata would look like this (but not so unravelled of course):
[
{
"id": "8m8wwy",
"educationalnames": ["GCSE - English", "GCSE - Maths"]
},
{
"id": "wiL7Bn"
},
{
"id": "zAw6M1"
}
]
If you have an ID from the first Array, you can check for keys / values with this ID in the second Array.
If you want to get the key you should use
array_key_exists($string)
And if you want to get the value you should use
in_array($string)
You can use a foreach loop to execute this functions!

Categories