Assign a image id with php by total count of images - php

Im trying to assign a id for each image returned from the database. The id will then be put into img id. The id needs to be from the total count of the number of database rows returned.
<?php
while ($result = mysql_fetch_assoc($query)) {
$imgURL = $result['imageUrl'];
$imgID = mysql_num_rows($query);
for ($i=0; $i <= $imgID; $i++) {
}
echo"<img id =\"$i\" src=\"uploads/$imgURL\"/>";
}
?>
What i get in return is the images are displayed from the database, but instead of img id being sequential numbers (ie 1, 2, 3 etc.) it just returns me the total count. How can I get it to assign a individual number in order for each image returned?
All help is welcome. Thank you!

You don't even need to calculate the number of rows or have multiple loops. Just let $i be incremented with each pass of the while loop.
$i = 0;
while ($result = mysql_fetch_assoc($query)) {
$imgURL = $result['imageUrl'];
echo '<img id ="' . $i . '" src="uploads/' . $imgURL . '" />';
$i++;
}

You need to put your echo inside your for loop:
for ($i=0; $i <= $imgID; $i++) {
echo "<img id =\"$i\" src=\"uploads/$imgURL\"/>";
}
EDIT:
As an aside, you might not want to identify your images that way. The order of records in your query might not stay consistent depending on your application logic. Each record should have a unique ID in the database and that value would be preferable to the iteration count.

You have a bracket in the wrong place. I have rewritten it for you:
<?php
while ($result = mysql_fetch_assoc($query)) {
$imgURL = $result['imageUrl'];
$imgID = mysql_num_rows($query);
for ($i=0; $i <= $imgID; $i++) {
echo "<img id =\"$i\" src=\"uploads/$imgURL\"/>";
}
}
?>
You might also some consistency problems unless the ID comes from a field in the database. If your query does not have a sort, then you are not guaranteed any particular ordering. The most common way of rectifying this is to create another field called "id", and give it the auto_increment attribute. This way it will give you a unique sequential number that will never change. You can also sort by this number.

You should do something like this. The thing you've done is completely useless, because you are doing the same thing again and again in the same row:
<?php
$imgID = 0;
while ($result = mysql_fetch_assoc($query)) {
$imgURL = $result['imageUrl'];
echo"<img id =\"$imgID\" src=\"uploads/$imgURL\"/>";
$imgID = $imgID + 1;
}
?>

Related

PHP run query off each array variable and return results in table

I am trying to run a query off multiple array variables and display the results in a table.
The user selects 1 or more records, which includes BOL and CONTAINER. These selections are put in their own arrays and they are always an equal amount.
<?php
$bolArray = explode(',', $_POST['BOL']);
$containerArray = explode(',', $_POST['CONTAINER']);
$count = count($bolArray); // to get the total amount in the arrays
I use a FOR loop to separate each value from the 2 arrays:
for($i = 0; $i < $count; $i++)
{
$bol = $bolArray[$i];
$container = $containerArray[$i];
}
Here is the part where I'm stuck and probably where I am messing up.
I need to take each variable from the FOR loop and run query using both variables.
First, I'll start the table:
echo "<table><thead><tr><th>BOL</th><th>Container</th></thead><tbody>";
Here is where I tried a FOREACH loop:
foreach($containerArray as $container) // I am not sure if I am using this FOREACH correctly
{
And now, the query. Please take note of the variables from the first FOR loop:
$preQuery = "SELECT * FROM mainTable WHERE CONTAINER = '".$container."' AND BOL = '".$bol."'";
$preRes = mysql_query($preQuery) or die(mysql_error());
$preNum = mysql_num_rows($preRes);
I use a WHILE loop with a mysql_fetch_assoc:
while($preRow = mysql_fetch_assoc($preRes))
{
echo '<tr>'
echo '<td>'.$preRow[BOL_NUMBER].'</td>';
echo '<td>'.$preRow[CONTAINER_NUMBER].'</td>';
echo '<td>'.$preRow[ANOTHER_COLUMN].'</td>';
echo '</tr>'
}
}
echo '</tbody></table>';
?>
The query actually works. Problem is, it only returns 1 record, and it's always the last record. The user could select 4 records, but only the last record is returned in the table.
I tried to use the same query and paste it inside the first FOR loop. I echoed out the query and it displayed the same amount of times as the number of array values, but will only return data for the last record.
I do not understand what I am doing wrong. I just want to display data for each value from the array.
Edit
Here is what the code looks like when I throw the query in the first FOR loop:
echo "<table class='table table-bordered'><thead><tr><th>BOL</th><th>Container</th></tr></thead><tbody>";
for($i = 0; $i < $count; $i++)
{
$bol = $bolArray[$i];
$container = $containerArray[$i];
$preQuery = "SELECT BOL_NUMBER, CONTAINER_NUMBER FROM `intermodal_main_view` WHERE BOL_NUMBER = '". $bol ."' AND CONTAINER_NUMBER = '".$container."'";
$preRes = mysql_query($preQuery) or die();
$preNum = mysql_num_rows($preRes);
while($preRow = mysql_fetch_assoc($preRes))
{
echo '<tr>';
echo '<td>'.$preRow[BOL_NUMBER].'</td>';
echo '<td>'.$preRow[CONTAINER_NUMBER].'</td>';
echo '</tr>';
}
}
echo "</tbody></table>";
I think you can use "IN" if your POST vars are comma separated.
$preQuery = "
SELECT * FROM mainTable
WHERE CONTAINER IN ($_POST['CONTAINER'])
AND BOL IN ($_POST['BOL'])
";
$preRes = mysql_query($preQuery) or die(mysql_error());
$preNum = mysql_num_rows($preRes);
Then go to your while loop....
This would omit the need for creating an array and looping it.
Also, you need to switch to PDO for your query, and switch to parameter binding. It will take all of an hour to learn.

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.

Foreach inside While Statement (NumRows)

I'm trying to figure out how I would do a foreach statement inside my while statement. As you can tell by this code, it will only submit 1 row out of the table, even though it selects all the rows. How would I make it select each row?
Code:
$q2 = mysql_fetch_array(mysql_query("SELECT * FROM `ticketreply` WHERE `ticketid`='$id'"));
$num_rows = mysql_num_rows($q2);
while(count($num_rows) > $i){
echo "<div style='float:left;width:940px;margin-bottom:2%;margin-left:".($i + 1)."0px;margin-right:25%;'><div style='margin-left:".($i + 1)."0px;border:1px solid #cecece;padding:10px;'>Posted By: <a href='#'>".user2($q2[1])."</a><h2>".$q2[2]."</h2></div></div></div>";
$i++;
}
New Attempt:
$q2 = mysql_query("SELECT * FROM `ticketreply` WHERE `ticketid`='$id'");
$i = 0;
foreach($q2 as $s){
echo "<div style='float:left;width:100%;margin-bottom:2%;margin-left:".($i + 1)."0px;margin-right:25%;'><div style='margin-left:".($i + 1)."0px;border:1px solid #cecece;padding:10px;'>Posted By: <a href='#'>".user2($s[1])."</a><h2>".$s[2]."</h2></div></div></div>";
$i++;
}
Although now this doesn't display any rows.
$q2 = mysql_query("SELECT * FROM `ticketreply` WHERE `ticketid`='$id'");
$i = 0;
while ($s = mysql_fetch_array($q2, MYSQL_NUM)) {
echo "<div style='float:left;width:100%;margin-bottom:2%;margin-left:".($i + 1)."0px;margin-right:25%;'><div style='margin-left:".($i + 1)."0px;border:1px solid #cecece;padding:10px;'>Posted By: <a href='#'>".user2($s[1])."</a><h2>".$s[2]."</h2></div> </div></div>";
$i++
}
Just to be clear, your query, SELECT * FROMticketreplyWHEREticketid='$id' is most likely only selecting one row from the table. I'm assuming that the ticketid in your ticketreply table is unique. So there is only one row selected.
If I go with this assumption, then...
mysql_fetch_array fetches all of the columns from a single row returned by a query. Documentation on mysql_fetch_array can be found here.
I would recommend, before you dive right into outputting your HTML and styling, start first with some print statements of $q2, to see that it really contains what you expect it to contain, and has the structure that you expect it to have.
Try:
$q2 = mysql_fetch_array(mysql_query("SELECT * FROM `ticketreply` WHERE `ticketid`='$id'"));
print_r($q2);
You should see that $q2 is an array that is both integer-indexed and also string-indexed (that is, it is also a hash where each column name in your table is a key). Let's restrict mysql_fetch_array so that it just gives us the associated array (the string-indexed part) and not the integers.
$q2 = mysql_fetch_array(mysql_query("SELECT * FROM `ticketreply` WHERE `ticketid`='$id'"), MYSQL_ASSOC);
Now, you can access each element of $q2 as a key-value pair by the following:
foreach ($q2 as $column => $value) {
print "column name: $column\n";
print " value: $value\n";
print "\n";
}
If, instead, you don't care about the column names, and you just want an integer-indexed array of values, then you can do the following:
$q2 = mysql_fetch_array(mysql_query("SELECT * FROM `ticketreply` WHERE `ticketid`='$id'"), MYSQL_NUM);
Then, you can use a regular for loop for iterating through your result...
for ($i = 0; $i < sizeof($q2); $i++) {
print "Value $i: " . $q2[$i] . "\n";
}
Once you get a good feel for what the structure of $q2 is, then you will probably feel pretty comfortable and confident outputting your HTML with values from $q2 embedded in the right place.

If Statements Inside For Loops = Problems

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

MYSQL - Select specific value from a fetched array

I have a small problem and since I am very new to all this stuff, I was not successful on googling it, because I dont know the exact definitions for what I am looking for.
I have got a very simple database and I am getting all rows by this:
while($row = mysql_fetch_array($result)){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
Now, my question is: how do I filter the 2nd result? I thought something like this could work, but it doesnt:
$name2= $row['name'][2];
Is it even possible? Or do I have to write another mysql query (something like SELECT .. WHERE id = "2") to get the name value in the second row?
What I am trying to is following:
-get all data from the database (with the "while loop"), but than individually display certain results on my page. For instance echo("name in second row") and echo("id of first row") and so on.
If you would rather work with a full set of results instead of looping through them only once, you can put the whole result set to an array:
$row = array();
while( $row[] = mysql_fetch_array( $result ) );
Now you can access individual records using the first index, for example the name field of the second row is in $row[ 2 ][ 'name' ].
$result = mysql_query("SELECT * FROM ... WHERE 1=1");
while($row = mysql_fetch_array($result)){
/*This will loop arround all the Table*/
if($row['id'] == 2){
/*You can filtere here*/
}
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
$counter = 0;
while($row = mysql_fetch_array($result)){
$counter++;
if($counter == 2){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
}
This While loop will automatically fetch all the records from the database.If you want to get any other field then you will only need to use for this.
Depends on what you want to do. mysql_fetch_array() fetches the current row to which the resource pointer is pointing right now. This means that you don't have $row['name'][2]; at all. On each iteration of the while loop you have all the columns from your query in the $row array, you don't get all rows from the query in the array at once. If you need just this one row, then yes - add a WHERE clause to the query, don't retrieve the other rows if you don't need them. If you need all rows, but you wanna do something special when you get the second row, then you have to add a counter that checks which row you are currently working with. I.e.:
$count = 0;
while($row = mysql_fetch_array($result)){
if(++$count == 2)
{
//do stuff
}
}
Yes, ideally you have to write another sql query to filter your results. If you had :
SELECT * FROM Employes
then you can filter it with :
SELECT * FROM Employes WHERE Name="Paul";
if you want every names that start with a P, you can achieve this with :
SELECT * FROM Employes WHERE Name LIKE "P%";
The main reason to use a sql query to filter your data is that the database manager systems like MySQL/MSSQL/Oracle/etc are highly optimized and they're way faster than a server-side condition block in PHP.
If you want to be able to use 2 consecutive results in one loop, you can store the results of the first loop, and then loop through.
$initial = true;
$storedId = '';
while($row = mysql_fetch_array($result)) {
$storedId = $row['id'];
if($initial) {
$initial = false;
continue;
}
echo $storedId . $row['name'];
}
This only works for consecutive things though.Please excuse the syntax errors, i haven't programmed in PHP for a very long time...
If you always want the second row, no matter how many rows you have in the database you should modify your query thus:
SELECT * FROM theTable LIMIT 1, 1;
See: http://dev.mysql.com/doc/refman/5.5/en/select.html
I used the code from the answer and slightly modified it. Thought I would share.
$result = mysql_query( "SELECT name FROM category;", db_connect() );
$myrow = array();
while ($myrow[] = mysql_fetch_array( $result, MYSQLI_ASSOC )) {}
$num = mysql_num_rows($result);
Example usage
echo "You're viewing " . $myrow[$view_cat]['name'] . "from a total of " . $num;

Categories