I want to output all image files of a specific productid. What is the right syntax to output the image path for row 1, row 2, row 3 etc? I can not find it.
$sql = "SELECT *
FROM images
WHERE productid = $productid";
$select = $db->prepare($sql);
$select->execute(array());
foreach($select as $index => $rs) {
if($rs['imagepath']){
if($index == 0){
echo $imagepath[0]; // <---What is the right sytax of this?
}
}
if($rs['imagepath']){
if($index == 1){
echo $imagepath[1]; // <---and this?
}
}
if($rs['imagepath']){
if($index == 3){
echo $imagepath[2]; // <---and this?
}
}
The whole point of a foreach loop is it goes once through each select as "index". so you shouldn't have to worry about making an if-statement for each possible row, just make the statement once, and it will happen on each and every iteration
$rows = [];
$sql = "SELECT *
FROM images
WHERE productid = productid";
$select = $db->prepare($sql);
$select->execute(array());
foreach($select as $index => $rs) {
$rows []= $rs;
}
echo $rows[0]['imagepath'];
aren't we missing the fetch function?
`
$select = $db->prepare($sql);
$select->execute(array());
$i = 0;
while($row = $select->fetch()) {
echo $i . ' '. $row['imagepath'] . '<br>';
$i++;
}
?>
`
--
addendum:
I now understand you only want one, or some, of the images to be shown.
Would it not be easier then, to only select that/those images?
SELECT imagepath
FROM images
WHERE productid = productid
AND someid = 3
or if no "someid" is present:
SELECT imagepath
FROM images
WHERE productid = productid
LIMIT 2,1
That would avoid the need to loop through may be 100 records to only use the 3th.
Related
This PHP code takes records from my database and displays them. Basically, I want every occurrence of the string "cross" (lowercase only) to be changed to an image that is on my web server.
Records currently look like: crossJohn Doe. So when it appears on the page, it should replace cross with the img and keep the rest.
The code:
$sql = "SELECT DisplayName, LastName, FirstName FROM donor WHERE DonationAmount = 1000 ORDER BY LastName ASC LIMIT 154";
$result = mysqli_query($conn, $sql); // query
if (mysqli_num_rows($result) > 0) { // as long as the query returns something, do the calcs.
$array = array(); // create a variable to hold the information
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){ // whule there are results, put them in the array
$array[] = $row; // add the row in to the results (data) array
}
$counter = (count($array)); // find the amount of items in the array
$divisorCount = ceil($counter/2); // column count
$forEachCount = 1;
//loop while there are items in the array
foreach ($array as $row){
$forEachCount++; //increment counter
// naming logic
if (empty($row['DisplayName'])) { // if there is no DisplayName
if (empty($row['FirstName'])) { // show lastname
$block[] = "<div class='block'>".$row['LastName']."</div>\n";
}
else { //show first + last if no display name
$block[] = "<div class='block'>".$row['FirstName']." ".$row['LastName']."</div>\n";
}
} else { // show display name
$block[] = "<div class='block'>".$row['DisplayName']."</div>\n";
}
if($forEachCount > $divisorCount){ //insert each record into a "block"
$forEachCount = 0;
end($block);
$key = key($block);
$block[$key] .= "</div><div class='column'>"; // insert all "blocks" into a css div
}
}
unset($row,$key,$forEachCount,$divisorCount); //cleanup
//insert the div and populate it with the blocks
$output = "<div class='tableContainer'>
<div class='column'>".implode($block)."</div>
</div>";
print_r($output); // display all of it!
unset($array,$block);
}else{echo "<p>There are no donors in this category.</p>";}
using the REPLACE mysql string function might be enough
$sql = "SELECT REPLACE(DisplayName,'cross','<img src=\"path/to/image\" />') AS `DisplayName`, REPLACE(LastName,'cross','<img src=\"path/to/image\" />') AS `LastName`, REPLACE(FirstName,'cross','<img src=\"path/to/image\" />') AS `FirstName` FROM donor WHERE DonationAmount = 1000 ORDER BY LastName ASC LIMIT 154";
-- http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_replace
you can use mysqli_fetch_assoc instead of using mysqli_fetch_array and adding another argument to get only the associative one
while ($row = mysqli_fetch_assoc($result)) {
if (stripos('cross',$row['keyname']) !== false)
$row['keyname'] = str_replace('cross','<img src="path/to/image"/>',$row['keyname']);
$array[] = $row; // add the row in to the results (data) array
}
$query = "select * from tableitem";
$result = mysql_query($query);
$col = array();
while ($row = mysql_fetch_array($result)){
//they have computation here inside loop.
$amount = $value;
if($row['status']>3){ // base on the status only
if($amount>0){ //base on the computation
$count = $item;
// i need to count here the item before the grouping of duplicate item below.
if (!isset($col[$row['item']])) { // this is working for grouping the duplicate value
echo $row['item'];
echo $count; // count item
$col[$row['item']] = true;
}
}
}}
Sample output should be like this inside while loop if possible.
Item one 2
Item two 3
Item five 4
You can do that with sql not necessary php;
SELECT COUNT(*) as N,item
FROM tableitem
GROUP BY item
it will return duplicate items and you can check with n>1. And you can add more column for group.
$itemArray;
while ($row = mysql_fetch_array($result)){
if($row['n']>1){
itemArray[] = $row['item'];
}
}
print_r($itemArray);
If you increment array values using the keys you are trying to count:
$check = array();
foreach($values as $key => $value) {
if (isset($check[$key])) {
$check[$key]++;
} else {
$check[$key]=1;
}
}
var_dump($check);
I am trying to pass id to second page which I am selecting from another table but the below code isn't working. When I do var_dump I can see that the values are what I want but the rows for main query don't show up(The title and image aren't being displayed).
I have two queries in which the one is inside the other one. Can someone help me out? The main query works fine if I get rid of the while loop of the second query.
$paginate = new pagination($page, "SELECT * FROM table1 where title != '' ORDER BY id desc" , $options);
}
}
catch(paginationException $e)
{
echo $e;
exit();
}
if($paginate->success == true)
{
$result = $paginate->resultset->fetchAll();
foreach($result as $row)
{
$dx = $row['image_one'];//image_one from main query
//second query
$item = $mydb->prepare("select * from table2 where imageone = ?");
$item->bind_param('s', $dx);
$item->execute();
$item_res = $item->get_result();
while($row = $item_res->fetch_assoc()){
$rx = $row['id'];
var_dump($rx);
} //the rows below aren't being displayed
$path = 'images/';
echo "<a href='second.php?title=".urlencode($row['title'])." &item=".$row['id']."&id=".$rx."'>"."<img src='".$path."".$row['image_one']."'/></div>"."</a>";
}
Try this:
echo "<a href='second.php?title="'.urlencode($row['title']).'" &item="'.$row['id'].'"&id="'.$rx.'"'>"."<img src='"'.$path.'"".$row['image_one']."'/></div>"."</a>";
use ' ' around var name
You are reassigning $row in your while loop once it exits $row is null.
Try this instead:
while($item_row = $item_res->fetch_assoc()) {
$rx = $item_row['id'];
}
Also, instead of nested queries you should try using a join.
I understand this could appear alarming but bear with me.
I need to echo every field in every row in a table.
This is only an example - I have removed the HTML wrapped around it to improve readability.
$a = 1;
while ($a <= $count_rows) {
$query = "SELECT col1, col2 etc.. FROM table WHERE `id`='$id'";
$result = mysqli_query($con, $query);
$i = 1;
while($i <= $count_fields) {
$row = mysqli_fetch_array($result, MYSQL_NUM);
echo "$row[$i]";
$i++;
}
$a++;
$id = $a;
}
This only outputs the first field of every row? Why?
If I echo $row[2] I get nothing!
If I echo $row[2] I get nothing!
because it's actually third item
and there is some strange code interfering with $i variable
Anyway, to get every column from every row ou need a code like this
$query = "SELECT * FROM table";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_row($result)) {
foreach ($row as $index => $value) {
echo "$index => $value, ";
}
echo "<br>\n";
}
I have a while loop running that is returning values from a MYSQL table. It returns about 90 entries from the query. My hope is to be able to break these 90 values up and display them in groupings of 5. This may sound confusing so let me share some code samples to help clarify:
$con = mysql_connect("host", "username", "password") or die ("Unable to connect to server");
mysql_select_db("database") or die ("Unable to select database");
$sql = mysql_query("SELECT * FROM `table` WHERE column IS NOT NULL AND column <> ''");
Here I am pulling the values out that I need from the table...
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$column=$row['column'];
echo $id . '<br>';
echo $column . '<br>';
}
At this point, I have run the loop and get the display of all 90 entries. How can I pull the values out and display them in smaller chunks? If I use the looped values outside of the while loop, it just gives me the last value from the set. Is there a simple way to use the unique $id value from the column to get a specific grouping within the loop?
This will add more br's and a hr after each 5 records:
$cnt = 0;
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$column=$row['column'];
echo $id . '<br>';
echo $column . '<br>';
if($cnt % 5 == 0) echo "<br><br><hr><br><br>";
$cnt++;
}
Here is one (not very sophisticated) approach you could take:
$group_size = 5;
$tracking_variable = 0;
while ($row = function_to_fetch_row()) {
if ($tracking_variable == 0) {
// logic for the start of a grouping
}
// logic to display the row
$tracking_variable = ($tracking_variable + 1) % $group_size;
if ($tracking_variable == 0) {
// logic for the end of a grouping
}
}
if ($tracking_variable > 0) {
// logic for the end of the final grouping
}
You want to save this data in a variable, and reference it outside of the loop.
Try this:
$data = array();
while($row=mysql_fetch_array($sql))
{
$data[$row['id']] = $row['column'];
}
And now you can just display specific rows:
print $data[$someRow];