php for statement to fetch mysql data - php

I am storing the names and types of images in my database. Now I want to select the newest images from that database and display them to the user. I tried to use the following code but I am getting the same image name and type, but I want to get different images.
$new_image_count = mysql_query("SELECT COUNT(id) FROM newest");
$result = mysql_result($new_image_count, 0);
$select_images = mysql_query("SELECT * FROM newest");
$fetch = mysql_fetch_assoc($select_images);
for($result; $result > 0; $result--){
$name = $fetch['image_name'];
$type = $fetch['image_type'];
$name_dot_type = $name.".".$type;
echo '<img src="main_images/'.$name_dot_type.'" width="300">';
}
Any ideas about how to fix this problem ?

Remove the query to count rows (you don't need it)
and change the main part of the code to something like
$select_images = mysql_query("SELECT * FROM newest");
while ($fetch = mysql_fetch_assoc($select_images)) {
// echo data from $fetch
}
PS: you'll recently get a comments about using PDO instead of mysql_
PPS: you get the same results because you fetch the row just once, and after that you output the same values in the loop

First off, you shouldn't be using mysql_*() functions anymore, and should switch to mysqli or PDO
Secondly, just move the $fetch = mysql_fetch_assoc($select_images); inside the for loop:
for($result; $result > 0; $result--){
$fetch = mysql_fetch_assoc($select_images);
$name = $fetch['image_name'];
$type = $fetch['image_type'];
$name_dot_type = $name.".".$type;
echo '<img src="main_images/'.$name_dot_type.'" width="300">';
}

Related

Storing database results to a variable in PHP

I am trying to store the result from a MySQL statement for later use in PHP. I have this code which gets me the result:
// Get the categories from the db.
$categories = array();
$catSql = "SELECT id, name FROM categories";
if ($catStmt = mysqli_prepare($db, $catSql))
{
$catStmt->execute();
$result = $catStmt->get_result();
// Fetch the result variables.
while ($row = $result->fetch_assoc())
{
// Store the results for later use.
}
}
So I know i will have the results in $row["id"] and $row["name"] and I want to save all of the rows so whenever i need them i can loop through them and for example echo them. I have searched for structures and arrays for keeping them in PHP but I cannot seem to find any information about that or maybe I am not searching in the right direction. Can anyone point me where i should read about this to find out how to do this efficiently and if possible post a small example?
Use sessions:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Get the categories from the db.
$categories = array();
$catSql = "SELECT id, name FROM categories";
if ($catStmt = mysqli_prepare($db, $catSql))
{
$catStmt->execute();
$result = $catStmt->get_result();
// Fetch the result variables.
while ($row = $result->fetch_assoc())
{
// Store the results for later use.
$_SESSION['category_' . $row['id']] = $row['name'];
}
}
Then access it later from a different page
$_SESSION['session_variable_name']
You can also create an array of the information and store the entire array in a single session variable.
Just make sure you add the session_start function at the beginning of each page. The if statement prevents you from trying to start it multiple times.
$categories = array();
$catSql = "SELECT id, name FROM categories";
if ($catStmt = mysqli_prepare($db, $catSql))
{
$catStmt->execute();
$result = $catStmt->get_result();
while ($row = $result->fetch_assoc())
{
$categories[$row['id']]=$row['name'];
}
}
And If you want the name anywhere use below :
$categories[$id]

select statement returing one colum with multiple rows. I have to store those values into one variable for future use using sql

I am trying to get the values using the below code
$query="select document_id from certificate_documents where certificate_id=$certificate_id";
$res = db_query($query);
$row_count = db_num_rows($res);
$doc_id=array();
for($j=1;j<=$row_count;$j++){
$document_copy = db_fetch_object($res);
$doc_id[$j]=$document_copy->document_id;
print "$doc_id[$j]";
}
But the above code print nothing.
I have to use this value into another query . How can i get this? please help.
You can try this:
$query="select document_id from certificate_documents where certificate_id=$certificate_id";
$res = db_query($query);
$doc_id=array();
while($document_copy = db_fetch_object($res)) {
$doc_id[]=$document_copy->document_id;
}
print_r($doc_id);

PHP automatically create variables based on what is in mysql database

I dont know if this is possible, but am trying to create a php variable using an entry from a mysql database.
For example, lets say I want to create the following variables, but i want to replace google with whatever the company name is in the database.
$google = $row['companyname'];
$google_ticker = $row['ticker'];
$google_holding = $row['holding'];
So if I had a row in my database with the company name as Yahoo, the following would appear instead:
$yahoo = $row['companyname'];
$yahoo_ticker = $row['ticker'];
$yahoo_holding = $row['holding'];
I have tried different variations of the following however I cant get it to work (I know the code below wont work, its just an example of the sort of thing I have tried):
$query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($query)){
$$row['companyname'] = $row['companyname'];
$$row['companyname']_ticker = $row['ticker'];
$$row['companyname']_holding = $row['holding'];
}
I can get it to work using something similar to the following, however doing it this way means I have to create each variable manually (as far as i know). I am trying to get it to create my variables automatically depending on what company names I have in my database.
$values = [];
$query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($query)){
$values[$row['companyname']] = $row;
}
$google = $values['google']['companyname'];
$google_ticker = $values['google']['ticker'];
$google_holding = $values['google']['holding'];
Any ideas on how I can achieve this?
Many Thanks
Use a (multidimensional-)Array with KEYS that function as variable names:
$query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($query)){
$data[$row['companyname']]['name'] = $row['companyname'];
$data[$row['companyname']]['ticker'] = $row['ticker'];
$data[$row['companyname']]['holding'] = $row['holding'];
}
Now you can access the holding variable like this:
echo $data['google']['holding'];
That should get you started...
Succes!
You can use like this:
${$row['companyname']} = $row['companyname'];
doc

Create php array from one of all column that retrieve from mysql

I am a newbie on PHP,MySQL and HTML.
I have one question about php array.
I create MySQL query that joins 2 tables in php. From this join, I will get information about one product, but have multiple JIG.
$sql = "SELECT product.product_number,product.product_name,product.product_jitqty,product.product_desc,jit.jit_number,jit.jit_name,jit.jit_drawer,jit.jit_port,jit.jit_specpath
FROM product
JOIN production_jit
ON production_jit.product_number = product.product_number
JOIN jit
ON jit.jit_number = production_jit.jit_number
WHERE product.product_number = '$productnumber'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result))
{ }
from above query, I will get result like picture below.
So I want to create an array for column jit.jit_number. for easy to transfer both or only one data to another page.
I have tried below code.
$sql = "SELECT product.product_number,product.product_name,product.product_jitqty,product.product_desc,jit.jit_number,jit.jit_name,jit.jit_drawer,jit.jit_port,jit.jit_specpath
FROM product
JOIN production_jit
ON production_jit.product_number = product.product_number
JOIN jit
ON jit.jit_number = production_jit.jit_number
WHERE product.product_number = '$productnumber'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
?>
<?php
while($row = mysqli_fetch_assoc($result))
{
$jig = array ($row['jit_number']);
echo "This is JIG " . $jig[0] . ", " . $jig[1] . ".";
}
But the result is like picture below.
Can anyone help me? So if I want to transfer both data to another page, I just can use $jig[0] and $jig[1]. Or anyone can advise me the better way to transfer multiple data form mysql to another page.
I'm not really sure what you're trying to achieve, but $jig is not going to have two indices because $row['jit_number'] ist just a number itself. If you're trying to store all jit_numbers in a separate array, you could try something like this:
$numbers = array();
while($row = mysqli_fetch_assoc($result))
{
$numbers[] = $row['jit_number'];
}
You shall also try to prevent MySQL injection, WHERE product.product_number = '$productnumber'"; is rather horrible from a security point of view. Using a prepared statement or at least some sanitization / escaping is recommendable.
Try this->
$jig = array();
array_push($jig, $row['jit_number']);

How can I get this php to return the entire column of an sql db

I am trying to query a db for an entire column of data, but can't seem to get back more than the first row.
What I have so far is:
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_fetch_array($medicationItemObj, MYSQLI_NUM)){
echo count($row);
}
It's not my intention to just get the number of rows, I just have that there to see how many it was returning and it kept spitting out 1.
When I run the sql at cmd line I get back the full result. 6 items from 6 individual rows. Is mysqli_fetch_array() not designed to do this?
Well, I had a hard time understanding your question but i guess you are looking for this.
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_num_rows($medicationItemObj))
{
echo $row;
}
Or
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
$i = 0;
while ($row = mysqli_fetch_array($medicationItemObj))
{
$medicationItem[] = $row[0];
$i++;
}
echo "Number of Rows: " . $i;
If you just want the number of rows i would suggest using the first method.
http://php.net/manual/en/mysqli-result.num-rows.php
You can wrote your code like below
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
while ($row = mysqli_fetch_assoc($medicationItemObj))
{
echo $row['medication'];
}
I think this you want
You could give this a try:
$results = mysqli_fetch_all($medicationItemObj, MYSQLI_NUM);
First, I would use the object oriented version of this and always use prepared statements!
//prepare SELECT statement
$medicationItemSQL=$connection->prepare("SELECT medication FROM medication");
// execute statement
$medicationItemSQL->execute();
//bind results to a variable
$medicationItemSQL->bind_result($medication);
//fetch data
$medicationItemSQL->fetch();
//close statement
$medicationItemSQL->close();
You can use mysqli_fetch_assoc() as below.
while ($row = mysqli_fetch_assoc($medicationItemObj)) {
echo $row['medication'];
}

Categories