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.
Related
I want the code to limit what it echos to only echo results that state "online"
when it sends to unity however still shows all the results
if(mysqli_num_rows($result) > 0){
//show data for each row
while($row = mysqli_fetch_assoc($result)){
if($row['online'] = "online")
{
echo "ip:".$row['ip'] . "|name:".$row['name']. "|usercount:".$row['usercount'] . ";";
}
}
}
You just have one very simple mistake. Change this line:
if($row['online'] = "online")
to:
if($row['online'] == 'online')
I am building a script where a user can query (search) a MySQL database.
The user firstly selects the table from a drop down list, and then they can choose upto 4 'filters' for example userID=001.
Here is my code:
$con=mysqli_connect("localhost","Username","Password","DBname");
// Check connection
if(mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT * FROM ".$table." WHERE 1=1 ";
if($filter1 != "" or $filter1v != "" )
{
$query .= " and $filter1 LIKE'%$filter1v%'";
}
if($filter2 != "" or $filter2v != "" )
{
$query .= " and $filter2 LIKE'%$filter2v%'";
}
if($filter3 != "" or $filter3v != "" )
{
$query .= " and $filter3 LIKE'%$filter3v%'";
}
if($filter4 != "" or $filter4v != "")
{
$query .= " and $filter4 LIKE'%$filter4v%'";
}
$query .= ";";
$resultRAW = mysqli_query($con, $query);
echo mysqli_error($con);
$result = array();
while($data = mysqli_fetch_array($resultRAW, MYSQLI_ASSOC))
{
$result[] = $data;
}
echo "<table class='table table-striped' id='tableWithExportOptions'>";
$amountRows = count($result);
for($i = 0; $i < $amountRows; $i++)
{
$keys = array_keys($result[$i]);
$amountColumns = count($keys);
if ($i == 0)
{
echo "<thead><tr>";
//I replaced the foreach clause because of performance reasons but they would work as well
for($j = 0; $j < $amountColumns; $j++)
{
echo "<th>".$keys[$j]."</th>";
}
echo "</tr></thead>";
}
echo "<tr>";
for($j = 0; $j < $amountColumns; $j++)
{
echo "<th>".$result[$i][$keys[$j]]."</th>";
}
echo "</tr>";
}
echo "</table>";
?>
If the user doesn't choose any filters the script works fine, however when using a filter it doesn't show any results?
Depending on your database this may vary. But you can not append a string to the result. $result is a MySQL Result object. You need to fetch the result for example with this code:
$array = array();
while($data = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$array[] = $data;
}
Then you can work with your result array $array and do whatever you want to do
If you want to create a query this way you need to call the mysqli_query later and build the query which could look like this:
$con = mysqli_connect("localhost","Username","Password","DBname");
// Check connection
if(mysqli_connect_errno())
{
echo "Failed to connect to MySQL: ".mysqli_connect_error();
}
$query = "SELECT * FROM ".$table." WHERE 1=1 ";
if($field != "" or $fieldvalue != "" )
{
$query .= " and ".$field." LIKE'%".$fieldvalue."%'";
}
if($filter1 != "" or $filter1value != "" )
{
$query .= " and ".$filter1." LIKE'%".$filter1value."%'";
}
if($filter2 != "" or $filter2value != "" )
{
$query .= " and ".$filter2." LIKE'%".$filter2value."%'";
}
if($filter3 != "" or $filter3value != "" )
{
$query .= " and ".$filter3." LIKE'%".$filter3value."%'";
}
if($filter4 != "" or $filter4value != "")
{
$query .= " and ".$filter4." LIKE'%".$filter4value."%'";
}
$query .= ";";
$resultRAW = mysqli_query($con, $query);
$result = array();
while($data = mysqli_fetch_array($resultRAW, MYSQLI_ASSOC))
{
$result[] = $data;
}
And I would be extremely careful with $table. in the query. This looks like a very good point to start an SQL Inejction attack. To prevent those I recomment the use of prepared statements. More can be found here: Prevent SQL Injection.
Unfortunalty this does not work with tablenames so you need to manually test it for any malicios input. If you "trust" this variable then it might be ok but if it is a use rinput I would AT LEAST call:
$table = mysqli_real_escape_string($table);
EDIT:
echo "<table class='table table-striped' id='tableWithExportOptions'>";
$amountRows = count($result);
for($i = 0; $i < $amountRows; $i++)
{
$keys = array_keys($result[$i]);
$amountColumns = count($keys);
if ($i == 0)
{
echo "<thead><tr>";
//I replaced the foreach clause because of performance reasons but they would work as well
for($j = 0; $j < $amountColumns; $j++)
{
echo "<th>".$keys[$j]."</th>";
}
echo "</tr></thead>";
}
echo "<tr>";
for($j = 0; $j < $amountColumns; $j++)
{
echo "<th>".$result[$i][$keys[$j]]."</th>";
}
echo "</tr>";
}
echo "</table>";
If this does not work please tell me, I have not tested this.
Because you concatenate string to $result = mysqli_query
$result = "SELECT * FROM $table WHERE 1=1";
if ($field != "" or $fieldvalue != "") {
$result .= " and $field LIKE'%$fieldvalue%'";
}
if ($filter1 != "" or $filter1value != "") {
$result .= " and $filter1 LIKE'%$filter1value%'";
}
if ($filter2 != "" or $filter2value != "") {
$result .= " and $filter2 LIKE'%$filter2value%'";
}
if ($filter3 != "" or $filter3value != "") {
$result .= " and $filter3 LIKE'%$filter3value%'";
}
if ($filter4 != "" or $filter4value != "") {
$result .= " and $filter4 LIKE'%$filter4value%'";
}
mysqli_query($con, $result);
Few things I can see that give me pause here.
But firstly, to Answer your question:
The mysqli_query(); method executes the query you pass to it. In your code you're executing the basic query with mysqli_query(); before you check for and add the filters and their values. So no matter what the user selects on your drop downs, that query without filters will always be executed first. You need to build your whole query string first, then execute the query with mysqli_query(); after all the checking and possible additions to your query.
Additionally, things that might break things later on:
Also, you might want to use and/&& in your if statements. or like you have it will allow your SELECT statement to break if you have the $filter1value populated with a value and $filter1 not, it will test true in your if and the WHERE clause will be concatenated to your query with a value but no field.
TIPS: echo your SQL command out to see what your php code has generated to see if it's valid SQL before running it while you develop.
Myself and many other PHP developers prefer to use PDO to interact with Databases personally, but that's just my preference.
I wanted to give you a code example of how I would have done it, but I honestly would change too much of your code, so I left it.
Side-note: I'm not sure what levels of security you have on the inputs but what you're doing by including your input variables directly into you SQL command string like that leaves you open to SQL injection attacks. Very dangerous depending on who will be able to access your script. Perhaps try using a prepared statement with parameters to keep security up a bit. Please look at mysqli_prepare(); it's friend, the mysqli_stmt_bind_param(); method in this case where you're using mysqli. Always use prepared statements on the database libraries you use if you're accepting external inputs to your system. It'll save your job one day.
Just my two cents use it, don't use it. :)
I guess you should add the filters on the query string before you execute the query, instead of adding the filter to the results? E.g.
$query = "SELECT * FROM $table WHERE 1=1";
if (...) {
$query .= ...
}
// some more ifs...
$result = mysqli_query($con, $query);
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;
}
Now, the program is working fine to an extent, in that when mysql_affected_rows is more than 0, it does indeed add the data to the new table and print out the relevant echo message.
However, when mysql_affected_rows = 0, I get nothing, no error message, but absolutely no output at all.
I've stripped the code back, do any of you have any idea, i've looked at brackets, and closing conditions etc and can't work out why!
Code
$query10 = ("SELECT p.surname, p.passNo, p.activeUntil FROM PASSENGER p WHERE p.activeUntil < DATE_ADD(NOW(),INTERVAL -1 DAY)");
$result = mysql_query($query10);
while($row = mysql_fetch_array($result))
{
$surname = $row['surname'];
$passNo = $row['passNo'];
mysql_query("INSERT INTO ARCHIVED_PASSENGER (surname, passNo) VALUES ('$surname', '$passNo') ")
or die(mysql_error());
if (mysql_affected_rows()>0) {
echo '<p>';
echo "The number of rows affected by this update is: ";
echo mysql_affected_rows();
}
if (mysql_affected_rows()<1) {
echo '<p>';
echo "No records were affected. Taking you back to the control panel.";
}
}
I would advice to add a if($result != false && mysql_num_rows($result) > 0) just before the while loop. Like so:
$query10 = ("SELECT p.surname, p.passNo, p.activeUntil FROM PASSENGER p WHERE p.activeUntil < DATE_ADD(NOW(),INTERVAL -1 DAY)");
$result = mysql_query($query10);
if($result != false && mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result))
{
$surname = $row['surname'];
$passNo = $row['passNo'];
$query11 = mysql_query("INSERT INTO ARCHIVED_PASSENGER (surname, passNo) VALUES ('$surname', '$passNo') ")
or die(mysql_error());
if ($query11 != false && mysql_affected_rows()>0) {
echo '<p>';
echo "The number of rows affected by this update is: ";
echo mysql_affected_rows();
echo '</p>';
}
if ($query11 == false || mysql_affected_rows()<1) {
echo '<p>';
echo "No records were affected. Taking you back to the control panel.";
echo '</p>';
}
} else {
//nothing was retrieved, give some error!
}
}
I have a very simple table that contains a list of 'victims' and the corresponding number of that type destroyed. I'm trying to make an output page of this information, using this code:
foreach( $victims as $vic )
{
$hits = mysql_query("SELECT amount
FROM victims
WHERE victim = ".$vic );
echo $hits;
print "$vic: $hits <br /><hr>";
}
However, hits comes out empty. What's wrong with my SQL query?
foreach($victims as $vic)
{
$hits = mysql_query('SELECT amount
FROM victims
WHERE victim = "' . mysql_real_escape_string($vic) . '"');
if($hits && mysql_num_rows($hits)>0) {
while($row = mysql_fetch_array($hits)) {
echo '<p>' . $row['amount'] . ' hits</p>';
}
} else {
echo '<p>' . mysql_error() . '</p>';
}
}
mysql_query() doesn't return the actual result of your query, but rather a resource with which you can then access the results.
This is a typical pattern:
$result = mysql_query(...);
$row = mysql_fetch_assoc($result);
print($row['amount']);
Each call to mysql_fetch_assoc returns the next row of the result set. If you were expecting multiple rows to be returned, you can call this in a while loop:
$result = mysql_query(...);
while ($row = mysql_fetch_assoc($result)) {
print($row['amount']);
}
Since there's no sane error checking in any of the answers, I'll put the whole thing in here:
foreach( $victims as $vic )
{
$sql = "SELECT amount
FROM victims
WHERE victim = '".mysql_real_escape_string($vic)."'";
$result = mysql_query($sql);
$result or die('Query Error: '.mysql_error() . ' - ' . $sql);
$hitsarray = mysql_fetch_assoc($result);
if ($hitsarray) {
$hits = $hitsarray['amount'];
} else {
// No row was found
$hits = 0;
}
echo $hits;
print "$vic: $hits <br /><hr>";
}
Oh, and this fixes the query error that caused the issue in the first place. Note the quotes wrapping the $vic variable in the string, as well as the proper escaping of the string...