PHP automatically create variables based on what is in mysql database - php

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

Related

Getting multiple results without query inside loop

I'm trying to improve the loading times of images and need to change around the code.
I haven't had any luck finding out how to do this and I'm not sure if it is even possible. In the example below you can see that I use KEY to match it with U_KEY to get FILE_PATH which I then add to a long comma delimited $allPaths string.
I know I should not use queries inside loops but I have no idea how to change this.
<?php
$sql = "SELECT * FROM test_users, image_uploads LIMIT 0, 27";
$result = mysqli_query($mysqli, $sql);
while($value = mysqli_fetch_array($result)) {
$files_key = $value["KEY"];
$allPaths = "";
$inner_query = "SELECT * FROM additional_uploads WHERE U_KEY = '".$files_key;
$inner_result = mysqli_query($mysqli, $inner_query);
while ($row = mysqli_fetch_array($inner_result)) {
$allpaths .= $row['FILE_PATH'].",";
}
// how do I get $allPaths without using a query inside the while loop?
}
?>
If someone could tell me how I can get $allPaths with only one query instead of multiple queries inside the loop as shown above it would probably load the images much faster.
Is this possible?
Edit
I have tried to understand the problem using the suggested answer and additionally I was looking on other forums as well to find out more. However I still cannot find a solution. Since I'm using mysqli_fetch_array the suggested answer really confuses me even further.
<?php
$inner_query = "SELECT * FROM additional_uploads";
$inner_result = mysqli_query($mysqli, $inner_query);
$rows = [];
while ($row = mysqli_fetch_array($inner_result)) {
$rows[$row['U_KEY']] .= $row['FILE_PATH'].",";
}
$sql = "SELECT * FROM test_users, image_uploads LIMIT 0, 27";
$result = mysqli_query($mysqli, $sql);
while($value = mysqli_fetch_array($result)) {
$files_key = $value["KEY"];
$allPaths = $rows[$files_key];
}
?>

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]

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

Show multiple results from PDO::FETCH_ASSOC

Iwas wondering if someone could help me?
I have a table called markers, in this table it stores multiple records each with a name etc. I would like to echo each name however the below code only shows one results. How can I show more than one. Can someone please help I am new to PDO.
$stmt = $dtb->query('SELECT * FROM markers');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$markerName = $row['name'];
}
Use an array to hold the result, in your code, the variable $markerName is overwrote on each iteration.
$stmt = $dtb->query('SELECT * FROM markers');
$markerName = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$markerName[] = $row['name'];
}
That is because you are overwriting it each and every time , use an array instead.
Rewrite like this...
$markerName = array(); //<---- Add here
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$markerName[] = $row['name'];
}
echo implode('<br>',$markerName); //<---- Implode it up for display
Rewrite like this
$names = $dtb->query('SELECT * FROM markers')->fetchAll();
Being new to PDO, you are supposed to try tag wiki first, where you can find an answer not only to this one but to many other questions.

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