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

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']);

Related

How can I separate. to my database variable?

I have few data in mysql(link,description,date,del(delete status))
now Im taking this data from mysql with my code. But I wanna show my data's like this photo
as you can see all data's looks clear and separate.
Im using this sql code for take these data's
$sql = "SELECT `vLink` ,`vDescription`, `vDate` FROM `video_table`
But when I use my code output looks like
https://www.youtube.com/watch?v=D8f9IiUXA4EMYSQL | How to auto date time with MYSQL?2021-01-17 02:32:55
now I can use 3 sql code(for link,description,date) to take my all data's and I can put list each by each but Im wondering have we easy way?
thats my code
$sql = "SELECT `vLink` ,`vDescription`, `vDate` FROM `video_table` WHERE `vDel` = 0 ";
$result = mysqli_query($conn,$sql);
$Vdatas = array();
if (mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_assoc($result)) {
$Vdatas[] = $row;
}
}
//print_r($Vdatas);
foreach ($Vdatas[0] as $data) {
echo $data;
}

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

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'];
}

Splitting a php array from mysql query

I have been working on this for hours on end trying to split the resultant mysql query into their usable variables and I just don't know what I am doing incorrectly. I no longer get the resource ID# but now all I get is "array" from the variables when I print_r. I am trying to get the 3 fields from the select statement in their own array and use the values. I have been pulling my hair out trying to get this to create usable data. Any help is greatly appreciated as I feel I could spend many, many more hours tinkering and just seem to be on the wrong track.
$Query = "SELECT guardian.Email, child.CFName, guardian.FName
FROM child
INNER JOIN uaccount ON child.ANum = uaccount.ANum
INNER JOIN guardian ON guardian.ANum = uaccount.ANum
WHERE uaccount.ANum = '$ANum';";
$result = mysql_query($query);
$test = mysql_fetch_array($result, MYSQL_BOTH);
print_r('this is the test '.$test."<br/>");
while($row = mysql_fetch_assoc($test, MYSQL_BOTH))
{
print_r('this is the row '.$row."<br/>");
foreach($row as $rows)
{
$info = mysql_fetch_assoc($rows, MYSQL_BOTH);
$Email = $info['0'];
$FName = $info['1'];
$CFName = $info['2'];
}
}
Thank you very much for your assistance thus far. With a combination of everyone's help I have been able to pull the values from the first level of the array with the following code :
$query = "SELECT guardian.Email, guardian.FName, child.CFName
FROM guardian
INNER JOIN uaccount ON child.ANum = uaccount.ANum
INNER JOIN guardian ON guardian.ANum = uaccount.ANum
WHERE uaccount.ANum = '$ANum';";
$result = mysql_query($query);
$info = mysql_fetch_array($result);
$Email = $info['0'];
$FName = $info['1'];
$CFName = $info['2'];
However, that is only returning me 1/3rd of the data as each account has 3 guardian email addresses related to it. Where I should be getting about 2000 rows returned, I am only getting 670. That is why I was nesting another layer inside the orginal posting and why I was attempting to pull a fetch_assoc from itself. If you cannot pull an array from itself, how do you "de-nest" so to speak? Any and all help is greatly appreciated.
$emQuery = "SELECT guardian.Email, child.CFName, guardian.FName
FROM child
INNER JOIN uaccount ON child.ANum = uaccount.ANum
INNER JOIN guardian ON guardian.ANum = uaccount.ANum
WHERE uaccount.ANum = '$ANum'";
$result = mysql_query($query);
$Email = array();
$FName = array();
$CFName = array();
$test = mysql_fetch_array($result, MYSQL_BOTH);
print_r('this is the test '.$test."<br/>");
while($row = mysql_fetch_assoc($test, MYSQL_BOTH))
{
echo 'this is the row ';
print_r($row);
echo '<br/>';
//$info = mysql_fetch_assoc($rows, MYSQL_BOTH);
$Email[] = $info['Email'];
$FName[] = $info['FName'];
$CFName[] = $info['CFName'];
}
To the best of my understanding this is what you are trying to do.
Some highlights:
print_r can only get a reference to a valid php array, no strings included.
mysql_fetch_assoc fetches a line out of a result set referenced by a variable, and then moves the reference to point to the next row.
You cannot call this function on a the result of it self, as it is not valid syntax.
In general, you'll be better off using PDO or mysqli_ functions at least, as it is by far more secure, by allowing you to use parameter binding instead of just using use input as part as your SQL.
You should just loop through the rows of your result once like so:
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
// print_r($row); Debug here if you want.
$Email = $row['Email'];
$FName = $row['FName'];
$CFName = $row['CFName'];
}
Note: You were providing a second parameter to mysql_fetch_assoc() which only takes one parameter (the result from a query). See the doc here.
mysql_fetch_array() takes another parameter that specifies what type of array to return.
Generalized PDO example out of a project of mine ($sql would be your $Query string):
$qry = $pdo->query($sql);
$all=array();
$idx=0;
while($fields=$qry->fetch( 'PDO::FETCH_ASSOC' )){
$all[key($fields)][$idx]=$fields[key($fields)];
while(next($fields)!==false){
$all[key($fields)][$idx]=$fields[key($fields)];
}
$idx++;
}
The $all variable will hold an array which in turn holds an array for each of the columns you've selected.
Like that you can do neat things like array_combine($all['Email'],$all['Fname']) and you'd get an array where the key is the Email column and the value would consist of the Fname column.

php for statement to fetch mysql data

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">';
}

Categories