store rows retrieved from database as separate variables in php - php

I have a loop which displays the wanted rows but I also want each row to be stored in its own variable in php. I have a table that has an ID and an info column.
This displays the wanted ID and info:
if ($info = $stmnt2->fetch()) {
do {
echo "$info[id] . $info[info] </br> ";
} while ($info = $stmnt2->fetch());
} else {
echo "<p>No Info</p>";
}
I want each row to have its own variable so I can manipulate the data later down the line. Like the first row will be stored in a php variable called $one and the second row in $second.
How can I do this?

I wouldn't use a variable to solve this! Take an array instead:
$rows = [];
if ($info = $stmnt2->fetch()) {
do {
$rows[] = $info;
echo $info['id'].$info['info']."</br>";
} while ($info = $stmnt2->fetch());
} else {
echo "<p>No Info</p>";
}
if (!empty($rows)) {
//you can change the values of the rows like the following.
$rows[0]['id'] = 1; // The ID of the first row!
$rows[0]['info'] = 'Some Info'; // The info of the first row!
$rows[1]['id'] = 2; // The ID of the second row!
$rows[1]['info'] = 'Some Info'; // The info of the second row!
//...
}
With the above example each item on rows is one row ($rows[number_of_row - 1]).
Hint: $info[id] and $info[info] isn't valid. You have to replace these with $info['id'] and $info['info']!

Just add $info to an Array:
if ($info = $stmnt->fetch()) {
$array = [];
do {
echo "$info[id] . $info[info] </br> ";
$array[] = $info;
} while ($info = $stmnt2->fetch());
} else {
echo "<p>No Info</p>";
}
// Do stuff with all rows

if ($info = $stmnt2->fetch()) {
$array=[];
do {
$array[$info['id']][]=$info; //the array index will be the same as id from the db
echo "$info[id] . $info[info] </br> ";
} while ($info = $stmnt2->fetch());
} else {
echo "<p>No Info</p>";
}
The array index will be same as the id in the DB.
To Retrieve the content use
$array[1]['info'] //will retrieve content id id = 1

$mysqli = new mysqli('localhost','root','','yourdb');
if($resultobj=$mysqli->query("select * from yourtable limit 4")){
list($one,$two,$three,$four)=$resultobj->fetch_all();
}
print_r($one);

Related

Mysqli_stmt_num_rows and foreach

Hi i've got the following code, I'm trying calculate num rows to show a message if there is no rows in the database. I've got an array and I've used foreach to loop the arrays values and query the database. The problem is that if one of the ids from the array returns 0 rows but the other returns one row I get the value from the database query but also the message saying no rows found. Does anybody know why? Many thanks
$user_id = 30;
// Array of ids
$id_gruppo= user_group_ids($conn, $user_id);
$query_last_tickets = mysqli_prepare($conn, "SELECT ticket_id, ticket_subject, ticket_body, ticket_time_stamp, ticket_status, ticket_user_id, ticket_group FROM user_tickets WHERE ticket_group = ? ORDER BY ticket_time_stamp DESC LIMIT 5");
mysqli_stmt_bind_param($query_last_tickets, 'i', $data);
foreach ($id_gruppo as $data) {
mysqli_stmt_execute($query_last_tickets);
mysqli_stmt_bind_result($query_last_tickets, $ticket_id, $ticketsubject, $ticketbody, $ticketdate, $ticketstatus, $ticketuserid, $ticket_group);
mysqli_stmt_store_result($query_last_tickets);
$numTicket = mysqli_stmt_num_rows($query_last_tickets);
if ($numTicket > 0) {
while (mysqli_stmt_fetch($query_last_tickets)) {
echo $ticket_id;
}
}
}
if ($numTicket < 1) {
echo "no rows found";
}
You're checking the variable $numTicket after the loop that is updated inside the loop.
If the last $numTicket is 0, you'll fall in your last condition.
You can try something like this :
$have_tickets = false ;
foreach ($id_gruppo as $data) {
mysqli_stmt_execute($query_last_tickets);
mysqli_stmt_bind_result($query_last_tickets, $ticket_id, $ticketsubject, $ticketbody, $ticketdate, $ticketstatus, $ticketuserid, $ticket_group);
mysqli_stmt_store_result($query_last_tickets);
$numTicket = mysqli_stmt_num_rows($query_last_tickets);
if ($numTicket > 0) {
$have_tickets = true;
while (mysqli_stmt_fetch($query_last_tickets)) {
echo $ticket_id;
}
}
}
if (!$have_tickets) {
echo "no rows found";
}
You are assigning a value to $numTicket each time through the loop. This means that when you get to the if statement after the loop, it will contain the last value assigned to it within the loop. What you want to do is use a flag to determine if any of the iterations through the loop produce a count/result.
$user_id = 30;
// Array of ids
$id_gruppo= user_group_ids($conn, $user_id);
$query_last_tickets = mysqli_prepare($conn, "SELECT ticket_id, ticket_subject, ticket_body, ticket_time_stamp, ticket_status, ticket_user_id, ticket_group FROM user_tickets WHERE ticket_group = ? ORDER BY ticket_time_stamp DESC LIMIT 5");
mysqli_stmt_bind_param($query_last_tickets, 'i', $data);
// initialize the flag to false
$ticketsFound = false;
foreach ($id_gruppo as $data) {
mysqli_stmt_execute($query_last_tickets);
mysqli_stmt_bind_result($query_last_tickets, $ticket_id, $ticketsubject, $ticketbody, $ticketdate, $ticketstatus, $ticketuserid, $ticket_group);
mysqli_stmt_store_result($query_last_tickets);
$numTicket = mysqli_stmt_num_rows($query_last_tickets);
if ($numTicket > 0) {
// flip the flag to true since tickets were found
$ticketsFound = true;
while (mysqli_stmt_fetch($query_last_tickets)) {
echo $ticket_id;
}
}
}
if (!$ticketsFound) {
echo "no rows found";
}

How to number items in for-loop php

I have this code that select content from database and loop all, and few items are specify to be different by adding method (type-A and type-B) in database, so now i want to give all type-B numbers like 1,2,3 depending on number of type in database.
I could have do this using the id in database but it not number accordingly so i need just assign new number to list how many of it i have.
<?php
$getReply = $reply_stmt->getAll(); // this from my database
if(!is_null($getReply)){
foreach($getReply as $row){
$name = $row->itemname;
$method = $row->method;
}
if($method == 'type-B'){
$number = 1;
$number++;
echo $number."B-class<br/>".$name."".$method;
}else{
echo $name."".$method;
}
}
?>
Now i want to return something like this
1 B-class
Peter type-B
John type-A
2 B-class
Mike type-B
I am not sure but try to something like this...
$getReply = $reply_stmt->getAll(); // this from my database
if(!is_null($getReply)){
$number = 1;
foreach($getReply as $row){
$name = $row->itemname;
$method = $row->method;
if($method == 'type-B'){
echo $number." B-class<br/>".$name." ".$method;
$number++;
}else{
echo $name." ".$method;
}
}
}

Query not assigned into the variable / Not going into the condition

I was doing this code for my project and it seems that I can't get the values of the query into $currentRow. All that saved into the variable $currentrow is 22 which is the number rows in the database. I want to have access to all the query results. Please help. Here's the code.
public function getBSIConfig(){
$conn = oci_connect("472proj","system","//localhost/XE");
$sql = oci_parse($conn,"SELECT conf_id, conf_key, conf_value FROM bsi_configure");
oci_execute($sql);
echo "0";
while($currentRow = oci_fetch_all($sql,$res)){
echo "1.5";
echo $currentRow;
if($currentRow["conf_key"]){
echo "1";
if($currentRow["conf_value"]){
$this->config[trim($currentRow["conf_key"])] = trim($currentRow["conf_value"]);
echo "2";
}else{
$this->config[trim($currentRow["conf_key"])] = false;
echo "3";
}
}
}
}
And the output is only:
0
1.5
22
The results from this function are stored in the 2nd argument, rather than returned directly. See if this works for you:
$results = array();
$numResults = oci_fetch_all($sql, $results);
foreach ($results as $result) {
if ($result["conf_key"]) {
// etc ...
}
}
Read this http://php.net/manual/en/function.oci-fetch-all.php , you might get an idea what's wrong.

How to check if all rows match a criteria in PHP

I want to check if a certain field of all rows match a criteria.
So if all rows has in the Status field 'RUN' as value then echo "Success".
If there is one row with END as value then echo "Fail":
I'm guessing I need a loop and an IF statement ?
I was thinking something like this but it doesnt return anything:
while($source_row = mysqli_fetch_array($source_selection)){
if ( ($source_row['Stat']) == ("Run" ) {
echo "Success<br />";
} else
echo "Fail";
}
I don't want to echo each row, I want all rows to match a criteria then echo, if one doesn't match a criteria then echo as well.
This should work for you:
First of all you have to fetch all rows with mysqli_fetch_all(). After this I extract only the Stat column with array_column(). Then I just simply array_fill() an array with X values as you have in $states with the value "Run". And check if every value is equals.
$result = mysqli_fetch_all($source_selection, MYSQLI_ASSOC);
$states = array_column($result, "Stat");
if($states == array_fill(0, count($states), "Run")) {
echo "Success";
} else {
echo "Fail";
}
There are some error in the code and you can use the count to match -
$count = 0;
while($source_row = mysqli_fetch_array($source_selection)){
if ($source_row['Stat'] == "Run" ) {
$count++;
}
}
if($count != mysqli_num_rows($source_selection)) {
echo "Fail";
} else echo "Success";
For best performance you can do it directy on the SQL:
select count(*) from table where Stat <> 'Run';
And then test the returning value to check that is greater than zero.
To do it with php you should know that when you find an error you can stop the iterations. The code would look like that:
while($source_row = mysqli_fetch_array($source_selection)){
if ( $source_row['Stat'] != "Run" ){
$fail = true;
break;
}
}
if ($fail) {
echo "Fail";
} else
echo "Success";
}
Try this
$success=true;
while($source_row = mysqli_fetch_array($source_selection)){
if ( ($source_row['Stat']) != ("Run" ) {
$success=false;
}
}
if ($success) {
echo "Success";
} else {
echo "Fail";
}

Check for empty rowset in oci_fetch_array

I am doing the following...
$approved = oci_parse($conn_prs, "select * from patch_files where patch_reviewer = '". $_SESSION['id'] ."' and patch_status = 'Approved'"); // now rows available for current id
oci_execute($approved);
while ($row = oci_fetch_array($approved, OCI_BOTH + OCI_RETURN_NULLS )) {
var_dump($row); // shows nothing
if ($row == null) { echo "<p>None Found...</p>"; }
else { ....
Not sure why the null condition is not working...
Your null condition is not working because $row is never null. oci_fetch_array() returns an array of the row fields, or false. If there are no rows your while loop is not executed.
You seem to have misunderstood the purpose of OCI_RETURN_NULLS. When used, it creates array elements for empty fields in $row, not an empty array if there are no rows.
A quick and dirty way to do what you want is:
$i = 0;
while ($row = oci_fetch_array($approved, OCI_BOTH + OCI_RETURN_NULLS)) {
$i++;
...
}
if ($i == 0) {
echo "<p>None Found...</p>";
}
try with -
while ($row = oci_fetch_array($approved, OCI_BOTH + OCI_RETURN_NULLS )) {
var_dump($row); // shows nothing
if (empty($row)) { echo "<p>None Found...</p>"; }
else { ....
oci_fetch_array() - returns the next row from a query as an array.

Categories