Script inserts the same values to the database - php

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.

Related

How to loop this array and save to database?

I have this array to save to database:
{"i_barcode_id":["3","3"],"i_barcode_sn":["8999999565404","6933412700043"]}
how do I save it to DB so the databse should be like this.
i_barcode_id i_barcode_sn
3 8999999565404
3 6933412700043
this is my current script.
foreach($myarray as $row){
$dataadd_sto_d = array (
'ID' => $rows['i_barcode_id'],
'SN' => $rows['i_barcode_sn']
);
$insertsto_d = $this->MWarehouse->add_sto_d($dataadd_sto_d); //insert script
};
The script failed to save to database. I do not know why. any
Use this tested working
$key = array();
$value = array();
foreach($myarray as $row){
$id => $rows['i_barcode_id'],
$sn => $rows['i_barcode_sn']
array_push($key, $id);
array_push($value, $sn);
}
$insert_data = array_combine($key, $value);
return $this->MWarehouse->add_sto_d($insert_data);
Note
array_combine() will now throw a ValueError if the numberof elements for each array is not equal; previously this function returned false instead.
You have some typos in your Code like foreach(... as $row) and later you want to access $rows
My Attemp would be, to grap i_barcode_id or i_barcode_sn to loop and take the value index to get the data from the other array.
Example:
//true at the end, cause i have something against stdClass without any reason
$myarray = json_decode('{"i_barcode_id":["3","3"],"i_barcode_sn":["8999999565404","6933412700043"]}',true);
foreach($myarray['i_barcode_id'] as $key => $val){
$insertArray=array(
"ID" => $val,
"SN"=>$myarray['i_barcode_sn'][$key]
);
//Your Insert Script
};

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

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

Associative array not storing first result from SQL

I have a database in MySQL and I'm using this query to select certain rows from it using PHP:
$q = "SELECT Number, Body
FROM boxes
WHERE Number BETWEEN '1' AND '4' ORDER BY Number ASC";
Then calling the query and initiating arrays:
$r = $mysqli->query($q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
$array = array();
$content = array();
Then attempting to sort the results into an associative array where the 'number' is the key and the 'body' is the value.
while ($row = mysqli_fetch_assoc($r)) {
$array = array(
$content[$row['Number']] = $row['Body']
);
This works fine except it will not store the first value. This is the result of print_r($content);, missing the first row.
Array ( [2] => This is entry two [3] => This is entry three [4] => This is entry four )
I have tried running the SQL query within PHPMyAdmin and it returns all four rows as I would expect.
Does anyone have any ideas what I'm doing wrong?
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
You are getting first returned row by this line. You have to remove it and it will work properly.
mysqli_fetch_array and mysqli_fetch_assoc returning NEXT row on every call.

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

Categories