Using a condition in a while loop - php

I have this code
$dbh = new PDO('mysql:host=localhost;dbname=odesk', 'root', '123456');
$sth = $dbh->prepare("SELECT id,msisdn from new_r4 limit 1,10");
$sth2 = $dbh->prepare("SELECT status from flag where id = 1");
$sth->execute();
$sth2->execute();
while ($result = $sth->fetch(PDO::FETCH_ASSOC)) {
$result2 = $sth2->fetch(PDO::FETCH_ASSOC);
$flag = $result2['status'];
$the_number = $result['msisdn'];
$id = $result['id'];
while ($flag == 0) {
echo 'Waiting.......' . PHP_EOL;
sleep(1);
}
//Part of the condition,just added
while ($flag == 1) {
echo $the_number . ' ' . $id .' ' . PHP_EOL;
sleep(1);
}
}
which is a a cli script that displays some numbers from my address book if a certain condition is met.If a the flag is 0 then no number shall be displayed and when the flag is 1,then display the number.
The problem is,i can't find the right condition to use after
while ($flag == 0) {
echo 'Waiting.......' . PHP_EOL;
sleep(1);
}
The if , else and case do not wait up until the flag is 1.
What condition can i use to get the script to display the numbers when $flag == 1?.

You're using $result2 and $result1. Your $flag will always be the value id = 1 because the WHERE clause never changes - so either $flag will always be either 1 or another value (from your question, it's going to always be another value). Either change your query to join the table, or query whilst in the while loop.
Assuming new_r4.id = flag.id
SELECT r.`id`, r.`msisdn`, f.`status`
FROM new_r4 r
LEFT JOIN flag f
ON r.id = f.id
LIMIT 1, 10
Change your code to become
while ($result = $sth->fetch(PDO::FETCH_ASSOC)) {
$flag = $result['status'];
$the_number = $result['msisdn'];
$id = $result['id'];
Now all you need to do is check $flag is equal to 1, and you're golden.
if($flag == 1) {
echo $this_number . PHP_EOL;
}

The while ($flag == 0) { is infinite and will never break out ($flag never changes within the loop); so the rest of the code is never executed.
Why not just use a simple if/else statement ?
if($flag===1){
echo $the_number . ' ' . $id .' ' . PHP_EOL;
}else{
echo 'Waiting.......' . PHP_EOL;
}

Related

How to Check If 10 Most Recent Entries in MySQL DB Begin with a String Using PHP?

I want to allow people to write something like BOLD: or ITALIC: at the beginning of their message to make bold or italic. The only way I can think of is to get the total amount of entries by ID and minus 10 then make an IF statement and minus 9 and so on. Is there a single statement I could query to check if the string in the database begins a certain way and display it in HTML in bold or italic if it does?
<?PHP
$A = "localhost"; // Server Name
$B = "root"; // MySQL Username
$C = ""; // MySQL Password
$D = "sql"; // Database
$CONNECT = new mysqli($A, $B, $C, $D);
if ($CONNECT->connect_error) {
die('<DIV>Connection Failed</DIV>');
}
echo "<DIV>Connected</DIV>";
if (isset($_POST['MSG'])) {
$MSG = htmlspecialchars($_POST['MSG']);
$SQL = "INSERT INTO Messages (Message) VALUES ('$MSG')";
if ($CONNECT->query($SQL) === TRUE) {
echo "<DIV>Message Sent</DIV>";
} else {
echo "<DIV>Error Sending Message</DIV>";
}
}
$SELECT = 'SELECT * FROM Messages ORDER BY ID DESC LIMIT 10';
$RESULT = $CONNECT->query($SELECT);
if (mysqli_num_rows($RESULT) > 0) {
while ($ROW = mysqli_fetch_assoc($RESULT)) {
echo '<DIV>ID: ' . $ROW['ID'] . ' MSG: ' . $ROW['Message'] . '</DIV>';
}
}
I added in some code if somebody begins their message with "'", but the type of strpos if statement doesn't work in the while loop for retrieving messages.
if (isset($_POST['MSG'])) {
$MSG = htmlspecialchars($_POST['MSG']);
$SQL = "INSERT INTO Messages (Message) VALUES ('$MSG')";
if ($CONNECT->query($SQL) === TRUE) {
echo "<DIV>Message Sent</DIV>";
} else {
if (substr($MSG,0,1 == '\'')) {
echo "<DIV>Error Sending Message</DIV>";
} else {
echo "<DIV>Nice Try :')</DIV>";
}
}
In order for this question to have an answer i will sum up what i did in the comments:
if (mysqli_num_rows($RESULT) > 0) {
while ($ROW = mysqli_fetch_assoc($RESULT)) {
$message = $ROW['message'];
if(strpos($ROW['message'], 'BOLD:') !== false){
$message = '<strong>'.substr($ROW['message'], 5).'</strong>';
} else if(strpos($ROW['message'], 'ITALIC:') !== false){
$message = '<i>'.substr($ROW['message'], 7).'</i>';
}
echo '<DIV>ID: ' . $ROW['ID'] . ' MSG: ' . $message . '</DIV>';
}
}
edit: oops i forgot to add the different style tags..
for bold you can wrap the $message in a strong -tag. for italic its the i -tag
edit2: included tags in the code

How to remove 5 characters from the end of every column in a table MySQLi

I'm trying to loop through every row in a table, and remove 5 characters from the end of one column. I have written the following code but it seems to remove 2 characters for some reason.
<?php
$connection = new mysqli('localhost', 'nawd_test', 'password', 'nawd_test');
if ($connection->connect_errno > 0) {
die ('Unable to connect to database [' . $connection->connect_error . ']');
}
$sql = "SELECT *
FROM test";
if (!$result = $connection->query($sql)) {
die ('There was an error running query[' . $connection->error . ']');
}
//Create an array to hold the values of id's already changed
$ids = [];
$newVals = [];
echo '<p>Fetching rows...</p>';
while ($row = $result->fetch_assoc()) {
//Check / Add the id
if (in_array($row['id'], $ids)) {
echo '<p style="red"><strong>Error: Script has repeated itself!</strong></p>';
break;
}
$ids[] = $row['id'];
$rowName = $row['name'];
$newName = substr($rowName, -1);
$newName = rtrim($rowName,$newName);
$newVals[] = $newName;
}
//Now loop and update
$newValID = 0;
foreach ($ids as &$id) {
echo '<p>Updating row with ID ' . $id . '</p>';
mysqli_query($connection, "UPDATE test SET name ='" . $newVals[$newValID] . "' WHERE id=" . $id);
echo '<p>Column successfully changed "<em>' . $newVals[$newValID] . '</em>"</p>';
$newValID++;
}
echo '<p style="color: green;"><strong>Script complete!</strong></p>';
?>
Dont do this in php, you can do it with a single sql query:
UPDATE test SET name = LEFT(name, LENGTH(name) - 5)
Change
$newName = substr($rowName, -1);
$newName = rtrim($rowName,$newName);
into
$newName = substr($rowName, 0, strlen($rowName) - 5);
With the way you're working, you could never predict how many characters that would have removed at the end.
Minimum 1, maximum the whole word.
Please read the documentation about rtrim and substr.
try this if you wanna doit inside the query:
update table1 set name=substr(name,-5,length(name))

if() else function doesn't work in a loop

I have this table
cityreportcomment :
-----------------
reportID (fK)
cityID (fK)
comment
EDIT: if city has no comment, there is no row in the table: a row (for a city) exists only if that city has a comment.
for every report, I print 13 cities (that are in another table). I would like to check if city has a comment, then echo comment, if not, echo 'different'; but my code doesn't work.
for ($i = 0; $i < 13; ++$i) {
$stmt = $conn->prepare("SELECT * FROM cityreportcomment WHERE reportID=? AND cityID=?");
if (!$stmt) {
die(printf("Error: %s.\n", mysqli_stmt_error($stmt)));
} else if (!$stmt->bind_param('ii', $reportID, $selectcityID_array_unique[$i])) {
die(printf("Error: %s.\n", mysqli_stmt_error($stmt)));
} else if (!$stmt->execute()) {
die(printf("Error execute from ereportcomment table: %s.\n", mysqli_stmt_error($stmt)));
} else {
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
if (isset($row['cityID']) && $row['cityID'] == $selectcityID_array_unique[$i]) {
$selectcomment2[] = 'same' . $row['cityID'] . (isset($row['comment']) ? $row['comment'] : "");
} elseif (!isset($row['cityID']) || $row['cityID'] != $selectcityID_array_unique[$i]) {
$selectcomment2[] = 'different';
}
}
}
/* end else */
$stmt->close();
echo $i . ' ' . $selectcomment2[$i] . '<br>';
} //end for
PROBLEM:
if $i=1 has comment, $i=2 no comment, $i=3 has comment, $i=4 no comment, my echo results is
1 comment1
2 comment3
3
4
5
.....
It should be
1 comment1
2 different
3 comment3
4 different
5 different
.....
Use this instead:
while ($row = $result->fetch_assoc()) {
if (!empty($row['cityID']) && $row['cityID'] == $selectcityID_array_unique[$i]) {
$selectcomment2[] = 'same' . $row['cityID'] . (!empty($row['comment']) ? $row['comment'] : "");
} elseif (empty($row['cityID']) || $row['cityID'] != $selectcityID_array_unique[$i]) {
$selectcomment2[] = 'different';
} else {
continue; # do nothing
}
}
Your if/else doesn't work because you are checking if $row['cityID'] "is set", in other words, if it exists or not... However, because you are using it on a mysql loop where you are returning those fields, they will always be set (exist). I suspect that what you want to check is, if $row['cityID'] is empty or not, which in that case you could use !empty() instead.
https://www.virendrachandak.com/techtalk/php-isset-vs-empty-vs-is_null/
You have this SQL:
"SELECT * FROM cityreportcomment WHERE reportID=? AND cityID=?"
You are binding $selectcityID_array_unique[$i] to the cityID placeholder, so every record returned will have a cityID equal to $selectcityID_array_unique[$i].
Then you are checking this:
if (isset($row['cityID']) && $row['cityID'] == $selectcityID_array_unique[$i]) {
Naturally, it will always be true. If no records are returned from the query, you will not see different, because the while loop will execute zero times.
You can fix it like this:
// remove the if from the while loop, as it really has no effect
while ($row = $result->fetch_assoc()) {
// you don't need the isset checks; if $row is set, then each value in it will be set
$selectcomment2[] = 'same' . $row['cityID'] . $row['comment']);
}
// if there's nothing in the comments after the loop, then put 'different' in it
if (!$selectcomment2) {
$selectcomment2[] = 'different';
}
If the comment is empty, it won't be !isset.
This code should do what you want:
I would like to check if city has a comment, then echo comment, if not, echo 'different'
$stmt = $conn->prepare("SELECT * FROM cityreportcomment WHERE reportID=? AND cityID=?");
$key = 0;
$stmt->bind_param('ii', $reportID, $key);
for ($i = 0; $i < 13; ++$i) {
$key = $selectcityID_array_unique[$i];
$stmt->execute();
$result = $stmt->get_result();
echo '<br>Results for cityID = ' . $key . '<br><br>';
while ($row = $result->fetch_assoc())
if (empty($row['comment']))
echo 'different<br>';
else
echo $row['comment'] . '<br>';
}

Browser hangs and crashes when using a while loop

I am executing two queries and evaluating the following conditions for each record:
if $production_query->row->0 is equal to $jobcard_query->row->0
if $production_query->row->1 is equal to $jobcard_query->row->1
When true, it should display the results of $production_query.
However, when using a while statement, the browser takes a long time to respond and crashes.
Can anyone suggest a solution?
My code:
$query = " SELECT job_card_num , die_qty,id FROM sample_jobcard ORDER BY id DESC”
$production_query = mysql_query($query,$connection1);
$query1 = "SELECT job_card_num , die_qty,id FROM com_jobcard ORDER BY id DESC ";
$jobcard_query = mysql_query($query1,$connection1);
while ($row = mysql_fetch_array($production_query))
{
while( $row1 = mysql_fetch_array($jobcard_query))
{
while (($row1[0] == $row[0]) && ($row1[1] == $row[1]))
{
echo $row[0] . $row[1]. $row[2]'<br>';
}
}
}
Try changing the query to something like this:
$query = "SELECT sample_jobcard.job_card_num AS JOBCARDNUM, sample_jobcard.die_qty AS DIEQTY, sample_jobcard.id AS JID, com_jobcard.job_card_num, com_jobcard.die_qty, com_jobcard.id FROM sample_jobcard
join com_jobcard on sample_jobcard.job_card_num = com_jobcard.job_card_num AND sample_jobcard.die_qty = com_jobcard.die_qty ORDER BY sample_jobcard.id DESC";
$jobcard_query = mysql_query($query);
if($jobcard_query && mysql_num_rows($jobcard_query) > 0)
{
while ($row = mysql_fetch_array($jobcard_query))
{
echo $row['JOBCARDNUM']." ".$row['DIEQTY']." ".$row['JID']."<br>";
}
}
Replace while:
while (($row1[0] == $row[0]) && ($row1[1] == $row[1]))
{
echo $row[0] . $row[1]. $row[2]'<br>';
}
With if:
if ($row1[0] == $row[0] && $row1[1] == $row[1])
{
echo $row[0] . $row[1]. $row[2] . '<br>';
}
If your conditions ever evaluate as true, you have essentially written:
while(true) {
// run forever
}
This will run forever (well, until maximum execution time).
You end up printing the same line over and over, producing a large document that your browser has difficulty handling, inducing a crash.

PDO row count confusion

I am making a login page that checks for matching values in a database if the SELECT query returns a matching row with username and password then it will return a row count of 1. The way I have it coded right now when I echo the variable that stores the row count it will echo 26 for some reason and I'm not to sure why.
Would someone explain if I am doing something wrong or if this is normal behavior and where that value is coming from?
function checkLogin($conn,$myusername,$mypassword,$row,$row1){
try {
$sql = "SELECT COUNT(*) FROM CLL_users WHERE user_name = 'user' AND password = 'XXXX'";
if ($results = $conn->query($sql)) {
if($results->fetchColumn() > 0) {
$sql = "SELECT * FROM CLL_users WHERE user_name = 'user' AND password = 'XXXXX'";
foreach ($conn->query($sql) as $row)
{
$rowCount = count($row);
echo $rowCount;
print ("Username: " . $row['user_name'] . "<br>");
print ("Username: " . $row['password'] . "<br>");
}
echo $count;
}
else {
print "NO ROWS";
}
}
} catch (PDOException $e){
echo 'Connection failed: ' . $e->getMessage();
}
}
Your code, $rowCount = count($row);, is counting the columns in the current row - not the number of rows returned by the query.
On the same note, you are echoing a second count related variable, $count, but you neither declare-it nor increment it in your code. It looks like this one is the one that's supposed to be counting the number of rows you loop through. If this is true, you should set it as $count = 0; before the loop and use $count++; within it:
$count = 0;
foreach ($conn->query($sql) as $row) {
print ("Username: " . $row['user_name'] . "<br>");
print ("Username: " . $row['password'] . "<br>");
$count++;
}
echo $count;
Also, you're currently using PDO's rowCount prior to selecting a user, and you're using it properly. You could just store that result into a variable and use it to tell how many rows you are receiving:
$sql = "SELECT COUNT(*) FROM CLL_users WHERE user_name = 'user' AND password = 'XXXX'";
if ($results = $conn->query($sql)) {
$numRows = $results->fetchColumn();
if($numRows > 0) {
... rest of your code ....
function checkLogin($conn,$myusername,$mypassword,$row,$row1)
{
try
{
$sql = "SELECT COUNT(*) FROM CLL_users WHERE user_name = 'user' AND password = 'XXXX'";
if ($results = $conn->query($sql))
{
$count = $results->fetchColumn();
echo "$count\n";
if($count > 0)
{
$sql = "SELECT * FROM CLL_users WHERE user_name = 'user' AND password = 'XXXXX'";
foreach ($conn->query($sql) as $row)
{
print ("Username: " . $row['user_name'] . "<br>");
print ("Username: " . $row['password'] . "<br>");
}
}
else
{
print "NO ROWS";
}
}
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
}

Categories