Mysqli_stmt_num_rows and foreach - php

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";
}

Related

How can I stop foreach loop iteration until methods result in php?

I have an array() lenght=13 which I am using in foreach
$games = array(1,2,3,4,5,6,7,8,9,10,11,12,13);
foreach($games as $game_id){
$this->insertTrainingData($game_id, 'advance', 5);
$this->insertTrainingData($game_id, 'intermediate', 4);
$this->insertTrainingData($game_id, 'easy', 3);
}
The above foreach loop passes each game_id into insertTrainingData() for game_id insertion based on certain validations.
insertTrainingData() is validating each game_id before inserting the record, if all goes well then function store game_id for particular group (advance, intermediate, easy).
What is problem that I am facing?
It is when foreach loop passes game_id to three times called insertTrainingData() method in single iteration and jump into next iteration then same process. I am thinking on next iteration foreach loop passes game_id before completion of previous iteration job (insertTrainingData()).
So is this possible if I can stop foreach loop iteration until all functions return final result and then let foreach loop on next iteration. That's what I am thinking, not sure if I am wrong.
Here is function which decides to insert game_id for particular group based on validations.
private function insertTrainingData($game_id, $type, $limit){
$error = 0;
$result = true;
$todayTraining = Training::whereRaw("Date(created_at)=Curdate() and type='".$type."'")->get();
if($todayTraining->count() === $limit ){
$error = 1;
$result = false;
}
$todayExist = Training::whereRaw("Date(created_at)=Curdate() and game_id=$game_id")->get();
if($todayExist->count() > 0 || $todayExist->first() !== null){
$error = 1;
$result = false;
}
$recordInTwoRowDays = Training::whereRaw("created_at >= DATE_ADD(CURDATE(), INTERVAL -1 DAY) and game_id=$game_id and type='".$type."'")->get();
if($recordInTwoRowDays->count() > 0 ){
$error = 1;
$result = false;
}
if($error === 0){
$AddTraining = new Training;
$AddTraining->game_id = $game_id;
$AddTraining->type = $type;
$AddTraining->save();
$result = true;
}
return $result;
}
What happened when I executed above script?
Actually the above script added 6 rows for advance group however you can see the limit is 5
Can someone kindly guide me about it, I would really appreciate.
Thank you so much.
Your code is fine and it should not insert the 6th rows, maybe you are looking on wrong place, however, here is the code that you can improve:
It will not go for other if statement when the first statement is
false
Hence it will not call for second SQL statement
->count() is way much better than ->get()->count()
.
private function insertTrainingData($game_id, $type, $limit) {
$todayTraining = Training::whereRaw("Date(created_at)=Curdate() and type='".$type."'")->count();
if ($todayTraining >= $limit ) {
return false;
}
$todayExist = Training::whereRaw("Date(created_at)=Curdate() and game_id=$game_id")->count();
if ($todayExist > 0) {
return false;
}
$recordInTwoRowDays = Training::whereRaw("created_at >= DATE_ADD(CURDATE(), INTERVAL -1 DAY) and game_id=$game_id and type='".$type."'")->count();
if ($recordInTwoRowDays > 0 ) {
return false;
}
$addTraining = new Training();
$addTraining->game_id = $game_id;
$addTraining->type = $type;
$addTraining->save();
return true;
}

store rows retrieved from database as separate variables in 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);

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.

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.

If no results in table show X, PHP MySQL

I have a query on my site and if there is no results, I'd like to say something else rather than have a blank page...
$sth = $conn->prepare("SELECT * FROM directory WHERE user_active != '' AND County = :county");
$sth->execute(array(':county' => $county));
$c = 1;
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
RETURNED DATA GOES HERE
$c++;
}
$sth->execute(array(':county' => $county));
if ($sth->rowCount() == 0) {
echo 'no rows';
} else {
while(yada yada yada) { ... }
}
Relevant docs: http://php.net/manual/en/pdostatement.rowcount.php
You're counting the results in $c, so you can check which value that has by appending your code with this:
if($c == 1) { // Counter is stuck at 1
echo "No results were found.";
}
2 possible solution,
execute a SELECT COUNT
execute a fetchall check it and later display the result

Categories