If Statements Inside For Loops = Problems - php

For some reason my if statements don't work as expected.
$query = "SELECT title FROM blog";
$result = mysql_query($query);
$rows = mysql_num_rows($result);
for ($j = 0; $j < $rows; ++$j)
{
if (isset($_POST['$j']))
{
$id = mysql_real_escape_string($_POST['id']);
$query = "DELETE FROM blog WHERE id='$id'";
mysql_query($query);
echo 'Deleted post.. ';
echo 'Click here';
}
else
{
echo 'Failed!';
}
}
What happens is that "Deleted post.." and the "link" get echoed the number of rows I have in my table blog. Only one row in my table gets deleted though which is what I want. One button gets pressed each time, so shouldn't it echo "Deleted post.." only one time and "Failed!" the rest of the times? Thanks =)
Note: I'm still new to programming, sorry if the question is stupid.
Note 2: I have many buttons on another page.. they are labeled by numbers '1, 2, 3' etc.

change:
$_POST['$j'] // here, due to the single quotes you're
// always testing for the literal `$j`, and not
// the value of current loop iteration.
to:
$_POST[$j]

Variables are not parsed in single quotes, you need to use double quotes. isset($_POST["$j"]
Also you are trying to delete the same record over and over in the loop, you're checking if $_POST["$j"] is set but using $_POST['id']

Try this
<?php
$query = "SELECT title FROM blog";
$result = mysql_query($query);
$rows = mysql_num_rows($result);
for ($j = 0; $j < $rows; ++$j)
{
if (isset($_POST[$j]))
{
$id = mysql_real_escape_string($_POST['id']);
$query = "DELETE FROM blog WHERE id='" .$id ."'";
mysql_query($query);
echo 'Deleted post.. ';
echo 'Click here';
}
else
{
echo 'Failed!';
}
}
?>

The problem is that you're looping through $_POST[0] to $_POST[Whatever], but you're only deleting where ID = $_POST['id']. $_POST['id'] never changes. Even though you're looping over and over, you're still trying to delete the same row for each loop

It will not work because the POST or GET or REQUEST only takes what was posted to the current page from the previous page.
You need to POST some variable to some page then only is it that you can use the $_POST['j']. You cannot use the variables in the current page inside POST
If you are posting j from some other page then I think you can use this condition instead of using like that
$j = $_POST['j'];
if(isset($_POST['j'])){
for($j = 0; $j < $rows; ++$j){
//your code
}
}
Hope this helps

Related

How to avoid last added 2 data in while loop

how to avoid last added 2 data in while loop
$counter = 0;
$data=mysql_query("select * from tbl_sub_product");
$cnt = sizeof(mysql_fetch_assoc($data));
while($row= mysql_fetch_assoc($data)) {
if(($counter==$cnt-1) || ($counter== $cnt-2)){
}
echo $id = $row['id'];
}
is this a correct way.?is there any other way.? please help me
Firstly, as #Twinfriends said you should avoid using mysql_ functions.
You need to actually increment your $counter. You can do this by $counter++ (which is basically shorthand for $counter = $counter + 1 or $counter += 1).
Also, as #jeroen pointed out, the way you're checking for the count would have
returned the first row of your results so it would be missing from your while loop.
Given you the column count rather than the row count.
With mysql_ functions you need to use mysql_num_rows() for this.
$counter = 0;
$data = mysql_query("select * from tbl_sub_product");
$cnt = mysql_num_rows($data);
$stop = $cnt - 2;
while ($row = mysql_fetch_assoc($data)) {
$counter++;
if ($counter >= $stop) {
break;
}
echo $id = $row['id'];
}
break; inside a loop with stop the loop there and then. If you have the situation where you want to skip an iteration but you don't want to stop the loop you can use continue; instead.
Hope this helps!
The solution would be simple. Adding an additional condition within your while loop is not required at all, consider the solution below and Moreover mysql_functions are deprecated so I will suggest you to go with mysqli_functions
$count = 1;
/* Here $db would be something like $db = mysqli_connect('YOUR_HOST', 'DB_USER', 'DB_PASSWORD', 'DB_NAME'); */
$data = mysqli_query($db, "select * from tbl_sub_product");
$rows_count = mysqli_num_rows($data);
while($count++ < $rows_count-2 && $row = mysqli_fetch_array($data)) {
echo $id = $row['id']
}
That's all you have to do.
You can do it like this
$counter = 0;
$data=
mysql_query("select*
from tbl_sub_p roduct");
$cnt =mysql_num_rows($data);
$run=$cnt-2;
while($row=
mysql_fetch_assoc($data)) {
$count++;
if($count!=$run)
{echo $id = $row['id'];
}
}
If you want to avoid last two entries added in database then simply modify your query to:
$data = mysql_query("SELECT * FROM tbl_sub_product ORDER BY id DESC LIMIT 2,18446744073709551615");//it will start selecting from 3rd record and leave first two records in database which are actually last inserted records
this is the answer for my question
$counter = 0;
$data=mysql_query("select* from tbl_sub_product");
$cnt =mysql_num_rows($data);
$run=$cnt-0;
$run1=$cnt-1;
while($row= mysql_fetch_assoc($data)) {
$count++;
if($count!=$run && $count!=$run1)
{
echo $id = $row['id'];
}
}

How to echo columns 1...n from mysql database except the first one in php?

I have a table with par_id and columns (par1-5) 1 up to 5, but I'm trying to have my php function below to echo any number of columns
//-------------------------------------- get about ----------------------------------------------
function getAbout($option){
$div = array();
$sql_st = "undefined";
if($option == "about")
$sql_st = "SELECT * FROM `about` where par_id='1'";
// connect to database
mysql_connect($_SESSION['dbSever'],$_SESSION['dbUser'],$_SESSION['dbPass']) or die(mysql_error());
mysql_select_db($_SESSION['tblName']) or die(mysql_error());
$result = mysql_query($sql_st) or die(mysql_error()."<br/>".$sql_st);
$num_rows = mysql_num_rows($result);
while ($row = mysql_fetch_array($result) ){
// not sure what to do here
}
// disconnect
mysql_close();
return $div;
}
From your question title I'm assuming you have an ID maybe in your first column and you want to keep that from being printed. You could try something like:
$numberOfColumns = mysql_num_fields($result);
while ($row = mysql_fetch_array($result) ){
for ($i = 1; $i < $numberOfColumns; $i++){
echo $row[$i];
}
}
The $i iterator in the for loop is initiated with value of 1 because PHP handles (like many languages) arrays as zero-based, which means that the first element is referenced by $row[0] (as in this example) - by starting the loop at one and going for as many elements there are in the array, you're effectively grabbing all elements except for the first one.
A really simple one would be to have a flag like so:
$skippedFirstRow = false;
while ($row = mysql_fetch_array($result)){
if(!$skippedFirstRow) {
//do whatever you want here
}
$skippedFirstRow = true;
}
However, keep in mind that this is just a quick hack for what you want and considering your code, but it is not an elegant solution.

Ignored if-statement

this is only my second question so please be gentle, I am new to PHP.
I have written a statement that queries a database, then checks a file to see if the relevant is present before creating a div to put the image into. The problem is that the output creates divs for rows that have no images.
$query = "SELECT vehicle_make_logo FROM vehicle_makes";
$result = mysql_query($query);
if(!$result) die ("Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0; $j < $rows; ++$j)
{
$row = mysql_fetch_row($result);
$image = 'images/vehicleBrands/'.$row[0];
if(file_exists($image)){
echo '<div class="component"><img class="icons" src="images/vehicleBrands/'.$row[0].'"></div>';
}
}
I have tried adding an empty else-statement, but that didn't do anything.
Any help would be greatly appreciated.
Another possibility for what is happening is that your DB table has rows in there which haven an empty field for verhicle_make_logo, at which point your if statement is checking if that folder exists, which it obviously does. If you are certain this is not the case ignore the below, if it is then this might be a solution.
<?php
$query = "SELECT vehicle_make_logo FROM vehicle_makes";
$result = mysql_query($query);
if(!$result) die ("Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0; $j < $rows; ++$j)
{
$row = mysql_fetch_row($result);
$image = 'images/vehicleBrands/'.$row[0];
if(!empty($row[0]) && file_exists($image)){
echo '<div class="component"><img class="icons" src="images/vehicleBrands/'.$row[0].'"></div>';
}
}
A browser can never overwrite PHP code because it never sees the PHP code. A browser will only render exactly what the PHP code passes to it. In the case where IE creates extra div tags, it could be that your HTML is malformed and IE tries to normalise it and creates extra divs in the process to close off some open tags that you may have overlooked.
Try copying the view-source code of the page and run it through a HTML validator to see.
Do not ever think for a minute that, Whatever kind of Browser you are using can actaully influence the way how PHP behaves. Because, it Can not! It may seem that way to you, because sometimes, the HTML tags/codes... outputted/echo'ed by your PHP script may be rendered in a different way, according to the browser type you are using, specially by IE, because it sucks. Now, to get back to your code, try this
<?php
$query = "SELECT vehicle_make_logo FROM vehicle_makes";
$result = mysql_query($query) or die(mysql_error());
if(mysql_num_rows($rows) > 0) {
for($j=0; $j < count($rows); ++$j){
$row = mysql_fetch_row($result);
$image = 'images/vehicleBrands/'.$row[0];
if(file_exists($image)){
echo '<div class="component">
<img class="icons" src="images/vehicleBrands/'.$row[0].'"></div>';
}
}
}else {echo 'No record found';}

Avoiding running the same MySQL script multiple times

I have a script like this:
$result = array();
$sql = "SELECT DISTINCT Name FROM servers"; //doesn't really matter what this MySQL script is
//storing the same query in two different variables
$result[0] = mysql_query($sql);
$result[1] = $result[0];
for($i = 0; $i < 3; $i++) {
$result[0] = $result[1];
while($ret = mysql_fetch_array($result[0]) {
//run some code
}
}
Unfortunately, the above code executes once and then for the next iterations returns nothing. What am I doing wrong?
I am not so sure what are you trying to do. but if i understand, try this. remove the for loop, just put the while loop and do what ever you want to.
$sql = "SELECT DISTINCT Name FROM servers";
$result = mysql_query($sql);
while($ret = mysql_fetch_array($result) {
//run some code
echo $ret['Name'];
}
}
you will get all 3 records in each iteration and do what ever process you want to do for each record. no need to make a three 3 query for 3 records. One query will have all records and do while loop to get each record. hope it helps.

PHP/MYSQL while loop only displays the last record [duplicate]

This question already has answers here:
How to store values from foreach loop into an array?
(9 answers)
Closed 1 year ago.
I have this code:
include('config.php');
$result = mysql_query("SELECT * FROM system");
while($row = mysql_fetch_array( $result )) {
$name_system = $row['name'];
$value_system = $row['value'];
if($name_system=='website_register' AND $value_system==1)
{$register_system = 1;}
else
{$register_system = 0;}
if($name_system=='website_offline' AND $value_system==1)
{$offline_system = 1;}
else
{$offline_system = 0;}
}
My problem is the fact that the loop only displays the last record from "system" table.
My problem is the fact that the loop only it displays the last record from
No, the problem is the fact that the loop displays nothing. The display happens afterward, in code that's outside the loop and therefore gets executed only once, when the cursor has browsed the whole table and only the last row remains in $row to be printed.
Move the code that does the echo or print or whatever inside the loop, and it'll work.
This is sloppy, but it will show you what's happening as it goes through the loop:
include('config.php');
$result = mysql_query("SELECT * FROM system");
while ($row = mysql_fetch_array($result)) {
$name_system = $row['name'];
$value_system = $row['value'];
if($name_system=='website_register' AND $value_system==1)
{$register_system = 1;}
else
{$register_system = 0;}
if($name_system=='website_offline' AND $value_system==1)
{$offline_system = 1;}
else
{$offline_system = 0;}
print "$name_system, $value_system, $register_system, $offline_system<br />";
}
Your problem is you're overriding the last value each time on the same variable. Instead, add it as a new cell in an array. e.g. each place instead of doing
$register_system = 1;
Do
$register_system[] = 1;
At the end your can do print_r($register_system) to see all the value. You'll notice the keys of the array are 0,1,... You can consider using the $row['name'] as the key, like this:
$register_system[$row['name']] = 1
Assuming of-course these are distinct values.
the echo/print needs to be inside the loop.
Try to use break wherever it is necessary...
Use the logic of flag variable...
You might want to store your items into an array.
$result = mysql_query("SELECT * FROM system");
while($row = mysql_fetch_array( $result )) {
$name_system[] = $row['name'];
$value_system[] = $row['value'];
if($row['name']=='website_register' AND $row['value']==1)
{$register_system[] = 1;}
else
{$register_system[] = 0;}
if($row['name']=='website_offline' AND $row['value']==1)
{$offline_systemp[] = 1;}
else
{$offline_system[] = 0;}
}
That way you can print out each of the values by doing something like:
for ($i = 0; $i < count($name_system); $i++) {
echo 'Name system is: '.$name_system[$i];
}

Categories