"Properly" looping through (my)SQL response - php

I have a class that does the MySQL stuff for me.
I have 1 to n rows in a MySQL Table and want to query specific results.
To query a table, I can now use
$db->select('tablename', '*');
$res = $db->Result()
to get the results as an associative array.
Now if I want to loop through, I have to check if there is one or more results and then either display that one result or loop through the results.
This bloats up my code and I would like to find a way to combine both results.
At the moment, I am doing this stuff like so:
if(is_array($res[0]){
//we have more than one result
foreach($res as $something)
{
//do stuff here
}
}
else
{
//do the same stuff as above here but now with other variables since $something is only filled in the foreach loop
}
Now as said, I would love to combine those two and have only one piece of code to display the results (or work further with them)

Change the input data structure into the format the loop expects, then iterate through it in the loop:
if(!is_array($res[0]){
$res[0] = [$res[0]];
}
foreach($res as $something)
{
//do stuff here
}

I would suggest you to switch to some wide deveoped classes like PDO (http://php.net/manual/en/book.pdo.php) or simply add a check in your Result method that returns an empty array in cases there are no results
function Result() {
// stuff to fetch and fill $arr;
return (is_array($arr[0])) $arr : array();
}

Related

convert some value from mysql query using php

using php I make a query to mysql. Inside my query, some values are in seconds (just some of them), I'd like to convert them into mm:ss. So I need to move into my "array" query and I do not understand how to move inside my query result, attribute after attribute.
Here is my db :
In my php code, I make the query and then for each row I put it inside an array.
$data=array();
$q=mysqli_query($mysqli, "SELECT * FROM TEST3612 WHERE user_id=$queryid");
while ($row=mysqli_fetch_object($q)) {
//$data[]=gmdate("H:i:s", $row%86400);
$data[]=$row;
}
I'd like then to move into my array, and when I have the attribute CS for example, convert the value.
Here is what I tried :
foreach($data as $value) {
if ($value['CS']) {
$value['CS'] = gmdate("H:i:s", $value%86400);
}
}
I got an error. I don't know how to move into my array, a select a element of a object. I thought I did it good but apparently no.
Thank you for you help.
mysqli_fetch_object returns objects, not arrays. Also you used $value instead of $value->CS inside of gmdate. So you should iterate like this:
foreach($data as $value) {
if ($value->CS) {
$value->CS = gmdate("H:i:s", $value->CS % 86400);
}
}
Alternativly you can write this directly in your while loop, so you don't need the foreach loop. I would say this is the better solutions because you don't write unnecessary code and performance gets improved a little bit:
while ($row = mysqli_fetch_object($q)) {
if ($row->CS) {
$row->CS = gmdate("H:i:s", $row->CS % 86400);
}
$data[] = $row;
}

Efficient way of creating a multi - dim array from coursor

I'm executing a cursor. I have cutted off the code how the procedure is called and executed. This part is efficient.
At last I have a a not big cursor. I'm calling the procedure, which returns this cursor many times on the page and I need to create a multidimensional array from it. This array should look like like the following:
$ret = oci_execute($outrefc) ;
while ($row = #oci_fetch_array($outrefc))
{
foreach (array_keys($row) as $key)
{
$res[$i][$key] = $row[$key];
}
$i++;
}
Is there any way to make the upper snippet faster?
The multidimensional array should stay as it is. I only wonder if I could create it in any more efficient way.
Thank you!

Select only arrays for foreach

I've got a foreach statement that on an item that has both objects and arrays in it.
foreach($result as $data)
that contains both arrays and objects. how do i specify the foreach to only select to loop through one or the other? when it loops through them all it takes forever
I had tried foreach($result->data as $data) but then it errors on the arrays telling me it is trying to get property of an object, which is understandable. once I add an if statement to check if the first result is an object it almost triples the script run time since there are so many results.
Well you could just use is_object() and is_array() (both return a boolean):
if (is_object($var)) {
// do something
} else if (is_array($var)) {
// well then, do something else
}

Editing the object returned by $wpdb->get_results(SQL)

We have a nasty database call using the Wordpress function $wpdb->get_results(SQL).
After receiving the result in PHP, we need to make a few changes to the result.
So can anyone tell me how I can:
1) Remove specific rows from the get_results() returned object.
2) Change the values of the specific columns in specific rows in the returned object.
I.e. if the object returned is $nastyData, we need to:
1) Remove specific rows from $nastyData
2) Change the value of specific columns in specific rows in $nastyData, for example $nastyData->name for a specific row.
Any ideas?
I have thought about makeing get_results() return the data as an array, but that will create problems in other places in our code (where the code expects to receive an object).
Thanks,
Mads
To start with, your "Nasty database call" should be optimized to be less nasty. More specifically, only query the results you want so that you don't have to remove stuff afterwords. This is the best solution.
If you insist on trying to modify the objects, this is a workaround. According to the documentation, when returning objects, they are returned in one of two ways:
OBJECT - result will be output as a numerically indexed array of row objects.
OBJECT_K - result will be output as an associative array of row objects, using first column's values as keys (duplicates will be discarded).
So, knowing that the result is an array of objects, we can get to each individual instance using a foreach construct:
$results = $wpdb->get_results( $nastySQL );
foreach($results as $index => $result)
{
// Change name column to FirstName using copy and delete
$tmp = $result->name;
unset($result->name);
$result->FirstName = $tmp;
// Remove specific row
if( $result->name == "Tom")
{
unset($results[$index]);
}
}
Below code will replace the value coming from specific field of database table, if name field has value like Reo and you want to replace it with other name like John then you can to do this via below code
$results = $wpdb->get_results( $nastySQL );
foreach($results as $key => $value){
$results[$key]->name= 'John';
}
return $results;

Inserting textarea elements into MySQL from PHP

I need to get all the elements from a textarea in a HTML form and insert them into the MySQL database using PHP. I managed to get them into an array and also find the number of elements in the array as well. However when I try to execute it in a while loop it continues displaying the word "execution" (inside the loop) over a 1000 times in the page.
I cannot figure out what would be the issue, because the while loop is the only applicable one for this instance
$sent = $_REQUEST['EmpEmergencyNumbers'];
$data_array = explode("\n", $sent);
print_r($data_array);
$array_length = count($data_array);
echo $array_length;
while(count($data_array)){
echo "execution "; // This would be replaced by the SQL insert statement
}
you should use
foreach($data_array as $array)
{
//sql
}
When you access the submitted data in your php, it will be available in either $_GET or $_POST arrays, depending upon the method(GET/POST) in which you have submitted it. Avoid using the $_REQUEST array. Instead use, $_GET / $_POST (depending upon the method used).
To loop through each element in an array, you could use a foreach loop.
Example:
//...
foreach($data_array as $d)
{
// now $d will contain the array element
echo $d; // use $d to insert it into the db or do something
}
Use foreach for the array or decrement the count, your while loop
is a infinite loop if count is >0

Categories