I am trying to execute multiple queries with the multiple selected checkbox value-wise in PHP.
I am facing trouble that my code is executing only one checkbox value-wise query and the rest is denied.
I checked on StackOverflow about this issue and I got lots of threads about foreach loop but in my case, it is not working when I am applying that.
Please help me, I am first time trying the foreach loop and so that I have a bit confusing about the same.
I have also the problem that I am not able not to validate invalid data through an array.
How I fix this? it only works for the first check value but I want all checked checkboxes.
I am trying to fetch data from the database of those particular ids which value I selected in the checkbox. and echo it in the array for that all query as I mention below-
Sending Form Data format as seen in dev tool
referenceID[]: PO0203211
referenceID[]: PO203213
PHP
$checkbox = $_POST['referenceID'];
foreach ($checkbox as $chk) {
$stmt = $con->prepare(
"SELECT * FROM `table` WHERE `ref` = :referenceid"
);
$stmt->execute([':referenceid' => $chk]);
$stmt = $stmt->fetchAll();
$response = [];
$i = 1;
foreach ($stmt as $data) {
$response[] = [
"slno" => $i,
"name" => $data['name'],
"orderid" => $data['address'],
];
$i++;
}
echo json_encode($response);
exit();
}
Try this, when using exit() inside the foreach the code does not continue and only performs the first element.
EDIT 1:
Ok, I'm going to explain a little more in depth how to optimize this code.
You get "id" identifiers from checked checkboxes.
You can use SQL IN () to optimize this.
Look at this
$checkboxDivide = implode("','", $_POST['referenceID']);
$response = []; //Final Result
$stmt = [];
$query = mysqli_query($con,
"SELECT * FROM `table` WHERE `ref` IN('{$checkboxDivide}')"
);
while($stmt[] = mysqli_fetch_assoc($query));
//Delete empty last array
array_pop($stmt);
$i = 1;
foreach ($stmt as $data) {
$response[] = [
"slno" => $i,
"name" => $data['name'],
"orderid" => $data['address'],
];
$i++;
}
echo json_encode($response);
You're using the exit() function withing your foreach, which will terminate the current script. See php manual on exit.
I am referencing to the
foreach ($checkbox as $chk) {}
not to the
foreach ($stmt as $data) {}
The script will terminate after the first loop of the first foreach.
Try moving it out of the foreach.
**Updated answer because of the comment from #El_vanja
Move your $response = []; array above and out of the foreach loop. This will keep the data in the array and not reset the array every iteration of the foreach loop.
Related
I have an query which select all ids from a table. Once I have all id's, they are stored in an array which I foreach over.
Then there is an second array which pull data from url (around 5k rows) and should update DB based on the id's.
The problem - second foreach is looping once for each ID, which is not what I want. What I want is to loop once for all id's.
Here is the code I have so far
$query = " SELECT id, code FROM `countries` WHERE type = 1";
$result = $DB->query($query);
$url = "https://api.gov/v2/data?api_key=xxxxx";
$api_responce = file_get_contents($url);
$api_responce = json_decode($api_responce);
$data_array = $api_responce->data;
$rows = Array();
while($row = $DB->fetch_object($result)) $rows[] = $row;
foreach ($rows as $row) {
foreach ($data_array as $key => $dataArr) {
$query = "UPDATE table SET data_field = $dataArr->value WHERE country_id = $row->id LIMIT 1";
}
}
The query returns 200 id's and because of than the second foreach (foreach ($data_array as $key => $dataArr) { ... }) execute everything 200 times.
It must execute once for all 200 id's not 200 * 5000 times.
Since the question is aboot using a loop, we will talk about the loop, instead of trying to find another way. Actually, I see no reason to find another way.
->Loops and recursions are great, powerful tools. As usually, with great tools, you need to also find ways of controlling them.
See cars for example, they have breaks.
The solution is not to be slow and sit to horses era, but to have good brakes.
->In the same spirit, all you need to master the power called recursions and loops is to stop them properly. You can use if cases and "break" command in PHP.
For example, here we have a case of arrays containing arrays, each first child of the array having the last of the other (1,2,3), (3,4,5) and we want to controll the loop in a way of showing data in a proper way (1,2,3,4,5).
We will use an if case and a counter :
<?php
$array = array( array(-1,0,1), array(1,2,3,4,5), array(5,6,7,8,9,10), array(10,11,12,13,14,15) );
static $key_counter;
foreach( $array as $key ){
$key_counter = 0;
foreach( $key as $key2 ){
if ( $key_counter != 0 ) {
echo $key2 . ', ';
}
$key_counter = $key_counter + 1;
}
}
Since I dont have access to your DB is actually hard for me to run and debbug the code, so the best I can say is that you need to use an if case which checks if the ID of the object is the ID we want to proccess, then proceed to proccessing.
P.S. Static variables are usefull for loops and specially for recurrsions, since they dont get deleted from the memory once the functions execution ends.
The static keyword is also used to declare variables in a function
which keep their value after the function has ended.
I'm having trouble iterating through a PHP array in order to display a chart. Right now, my code is only resulting in the display of one column in the chart (this column is displaying correctly), but I can't seem to get other columns to display.
This is my code right now (in a php section at the top of my html page). I know that the issue is with this section of code, because the chart is rendering perfectly, but just not adding a column for each record in the table.
I'd really appreciate any insight into the mistakes I'm making here. Thank you.
$valueAnimalType = $_POST['animaltype'];
$connect = mysqli_connect("127.0.0.1","____","_____",3306);
$result = mysqli_query($connect,"SELECT * FROM DISPOSAL");
$datas = array();
if (mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$datas[] = $row;
}
foreach ($datas as $data){
$datas = array(
array('y' => $data[$valueAnimalType], "label" => $data['DisposalName'] ));
}
}
modify your code here:
foreach ($datas as $data) {
//LINE BELOW
$datas [] =
array('y' => $data[$valueAnimalType], "label" => $data['DisposalName']);
//LINE ABOVE
}
you're overwriting your $datas each time loop passes with last record, now it's appending new item to array
I'm trying to update the fields on my database with the ff code:
<?php
session_start();
include ('../../class/connection.php');
$sql = "UPDATE reservationmenutable SET service = ? WHERE id = ?";
$statement = $conn->prepare($sql);
foreach ($_POST["hidden_id"] as $key => $db_id) {
foreach ($_POST["service_id"] as $key => $service_key) {
$statement->execute([$service_key, $db_id ]);
}
}
?>
the POST values are arrays so I had to loop them to get to them one by one right, but I'm confused on how to do it.
I'm trying to use the contents of hidden_id[] for the second loop. I thought about using a variable then increment it one by one but that would not match since each service has a corresponding id on database, ideas would appreciated. thanks :)
Just use the $key ot hidder_id as the index of service_id
hope it helps
$serviceKeys = array_keys($_POST["service_id"]);
foreach ($_POST["hidden_id"] as $key => $db_id) {
$statement->execute([$serviceKeys[$key], $db_id ]);
}
I made a function in a CI model that first queries for the table to get its fields(because these fields will change dynamically over time,so I can't hard code a list of field names),and then when it gets the results of the first query, and builds a fields name list,it queries the table again to get the values belonging to one row or record.It then stores the second query result in an array,which is passed back to the controller.Here is the complete function that performs these steps:
public function getAssetFeatures($as_id)
{
$data = array();
//this sql query gets the field names from the table I want to query.
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '".DATABASE."' AND TABLE_NAME = 'as_features';";
$query = $this->db->query($sql);
$count = 0;
foreach($query->result_array() as $k)
{
foreach($k as $kk=>$v)
{
if( $v != "as_features_id" &&
$v != "as_id" &&
$v != "cid" &&
$v != "lot_size" )
{
$features_array[$count] = $v;
$count++;
}
}
}
$features_string = implode(",",$features_array);
//I got the field names, put them into an array, then concatenated them into a string, which I will use for the fields in the next query:
$sql = "SELECT $features_string FROM as_features WHERE as_id='$as_id'";
$query = $this->db->query($sql);
//mandatory rooms/features:
foreach($query->result() as $row)
{
foreach($row as $k=>$v)
{
$data["$k"] = $v; //build an associative array with the values of each field for the one row I am querying
}
}
return $data; // return the associative array.
}
At first I thought something was broken in my table or view,but as I kept repeating the same call to the model function by refreshing the page and entering the exact same values,I noticed that sometimes the code worked,and I wouldn't get the errors "undefined index".
So I outputted the results of the array with this code:
echo "<pre>";
print_r($asset['features']);
echo "</pre>";
...and the expected output, which only performs successfully sometimes, but not all the time, for the exact same operation using the exact same parameters, looks like this:
Array
(
[kitchen] => 1
[liv_area] => 0
[dining] => 1
[family] => 0
[bed] => 0
[bath] => 1
[half_bath] => 0
[parking] => 0
[car_storage] => 0
[pool] => 0
[miscellaneous] => 0
)
When the query returns a result set and then a populated array,my form works and looks normal.but,most of the time the query fails,and I get what looks like this:
The issue is with the following snippet of code:
foreach($query->result() as $row)
{
foreach($row as $k=>$v)
{
$data["$k"] = $v; //build an associative array with the values of each field for the one row I am querying
}
}
The way it works is that for every result which is returned it will overwrite $data with the relevant keys. However, because the $query->result() will return the row you want, then return false, the array essentially ends up being:
$data[] = false; i.e., set the whole array to false/empty.
If you change the loop to be, the code inside the loop won't be executed for the false value of $query->result():
while ($row = $query->result())
{
// your code
}
It's worth noting that if you're intending to return more that one row from this, it won't work as it will just overwrite the existing values.
Ok, the problem was my code, not the query. I was passing an encrypted as_id, but neglected to unencrypt it before constructing the select query. That's why it would work sometimes, and not others. For some reason MySQL allowed the encrypted as_id to match existing as_id of INT type. After performing the decrypt, the query results became predictable. This is something I wouldn't expect SO members to have divined. Thanks.
public function getAssetFeatures($as_id)
{
$as_id = $this->utilityclass->decryption9($as_id); // <- I had this commented out. In fact, I removed the line from my example code in the original post, because I didn't think it was important to the question. Not only was it important, it was the problem!
$data = array();
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '".DATABASE."' AND TABLE_NAME = 'as_features';";
$query = $this->db->query($sql);
I have an array being returned from the database that looks like so:
$data = array(201 => array('description' => blah, 'hours' => 0),
222 => array('description' => feh, 'hours' => 0);
In the next bit of code, I'm using a foreach and checking the for the key in another table. If the next query returns data, I want to update the 'hours' value in that key's array with a new hours value:
foreach ($data as $row => $value){
$query = $db->query('SELECT * FROM t WHERE id=$row');
if ($result){
$value['hours'] = $result['hours'];
}
It's all fine except that I've tried just about every combination of declarations for the foreach loop, but I keep getting the error that the $value['hours'] is an invalid reference. I've tried declaring $value[] ... but that doesn't work either. I don't need to iterate through $value so another foreach loop isn't necessary.
Surely this is easier than my brain is perceiving it.
Here's the whole snippet:
foreach($_gspec as $key => $value){
$sql = sprintf('SELECT * FROM List WHERE specialtyID=%s', $key);
$query = $db->query($sql);
if ($query->num_rows() !== 0){
$result = $query->row_array();
$value['hours'] = $result['hours'];
}
}
You want
$data[$row]['hours'] = $result['hours']
$row would be better named as $key (that is what it is!)
Some people would suggest using pointers, but I find this way makes more sense to me.
You need to use ampersand in front of the $value in foreach to pass it by reference like this:
foreach ($data as $row => &$value){
$query = $db->query($sql);
if ($result){
$value['hours'] = $result['hours'];
}
}
More info here: http://php.net/manual/en/control-structures.foreach.php
As of PHP 5, you can easily modify
array's elements by preceding $value
with &. This will assign reference
instead of copying the value.
Use reference ->
foreach ($data as $row => & $value) {
$query = $db->query('SELECT * FROM t WHERE id=$row');
// [...]
if ($result) {
$value['hours'] = $result['hours'];
}
}