SQL db row,1 cell containing multiple image locations, query - php

How can I process a sql cell ($afbeeldingen) containing multiple image locations?
The vehicle table holds the column "images"(or in dutch language "afbeeldingen"), and for one vehicle there can be multiple imagelinks in "images", urls are seperated with a ","
I would like to output
<img src=imagelocation>
for each location stored in the single cell.
function toon_voertuigen()
{
include ('dbconn.php');
$query = "SELECT * FROM vehicles";
$result = mysqli_query($con, $query) or die("Couldn’t execute query.");
$nrows = mysqli_num_rows($result);
echo "<table>";
for ($i = 0; $i < $nrows; $i++)
{
$n = $i + 1; //add 1 so numbers don’t start with 0
$row = mysqli_fetch_assoc($result);
extract($row);
echo "<tr>\n
<td>$n.</td>\n
<td>
$images //Contains multiple imagelinks, this needs to be exploded to <img src=$images>
</td>
</tr>\n";
}
}
echo "</table>\n";
How can i use the explode function on $images to echo for each imageurl
<img src=$images>

Depending on how those image locations are written in that particular column. If they're separated by ";" then you can use $newarray = explode(";",$afbeeldingen) .. This will give you an array of all the parts separated by ";"... this is just an example..it could be that those image locations are separated by " " or by a "/" .. so you use the character that separates them..then you iterate on the array and you can either divide them on different or in the same but like put them in or

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.

PHP AND MySQL - Entire table column needs links instead of plain text

Basically what I'm doing is storing everything from my table into an array.
After that I go through it and select row by row and assign it to an array.
Then it goes through that array and puts it in the table, cell by cell, in a single row.
Now the last column of my table are links and they are the fourth and last column in the table and in the database. They're, just like they should, showing up as plain text, but I'd rather have them clickable (For ease of use).
Since the entire table (Except for the, in this case, 4 header items) is created by php code I would have no clue on how to change just the last bit to be a link.
Help would really be appreciated!
Code:
$sql = "SELECT * FROM Future_Mods";
$result = mysqli_query($conn, $sql) or die (mysql_error());
echo "<table>";
echo "<tr>
<th>ID</th>
<th>Mod</th>
<th>Is Available</th>
<th>Has Been Added</th>
<th>Reason</th>
</tr>";
for($i = 0; $i < mysqli_num_rows($result); $i++) {
echo "<tr>";
$row_array = mysqli_fetch_row($result);
for ($j = 0; $j < mysqli_num_fields($result); $j++) {
echo "<td>" .$row_array[$j]. "</td>\n";
}
}
echo "</table>";
Relatively simple:
while ($row = mysqlI_fetch_row($result)) {
end($row); // move array pointer to end of array
$key = key($row); // get key of current pointer element
// update last item to be a link
$row[$key] = '', $row[$key], '';
// dump out array as table cells
echo '<td>', implode('</td><td>', $row), '<td>';
}
This is a question of HTML formatting for your result set table.
If you happen to have a php variable $s that you are sure contains a URL, you can display the URL and make it clickable with php code like this:
echo sprintf ('$1', $s);
For example if $s has the value http://stackoverflow.com/ this will yield the HTML text
http://stackoverflow.com/
One of your $row items will contain that URL. So you can render it with this sort of patten.

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.

Assign a image id with php by total count of images

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

column name plus one for loop

I have name1, name2, name3 in mysql how do a do a 'for loop' to retreive the names of each person in mysql which i need to do for my form validation.
<?php
$row2 = "SELECT * FROM user WHERE username = '" . mysql_real_escape_string($_SESSION['username']) . "'";
$result = mysql_query($row2) or die("Error in SQL: " . mysql_error());
$row3 = mysql_fetch_array($result);
?>
In the form, I'm using the following, but it is not retrieving the names:
for($i=1; $i<=5; $i++)
// form code
<?php echo $row3['name'+[$i]]?>');
mysql_fetch_array() returns both numeric and associative keys by default, so your incremental for loop won't give you what you want. Instead, use the MYSQL_ASSOC option or mysql_fetch_assoc()
$row3 = mysql_fetch_assoc($result);
// OR
$row3 = mysql_fetch_array($result, MYSQL_ASSOC);
The for loop has to be done in PHP. It is difficult to tell if your loop is client side or server side.
<?php
for ($i=1; $i<=5; $i++) {
// not 'name' + $i -- PHP uses '.' for concatenation
// but it is easier to interpolate it in double quotes.
echo $row3["name$i"];
}
?>
Update
Since you were trying to mix PHP into a JS loop (which won't work), I recommend instead creating a JavaScript array using PHP, which can then be used in the JS loop later.
<?php
// Open a JS array called namesArray
echo "var namesArray = [";
$names = array();
for ($i=0; $i<=5; $i++) {
// get all the column values into an array
$names[] = '"' . $row3["name$i"] . '"';
}
// Make it into a string
$names = implode(',', $names);
// Close the JS array
echo $names . "];"
?>
That should output something like:
var namesArray = ["val1","val2","val3","val4","val5"];
In your JavaScript loop (which you don't have to change), access the values like:
// Updated to use i-1 instead of i
alert('Please make your colour & shade selection for ' + namesArray[i-1]);
The for loop needs to be inside the php tag.

Categories