Generating variables from db content? - php

I am querying a database to get 6 values in my params table suing this;
$result = mysql_query("SELECT * FROM params");
while($row = mysql_fetch_array($result))
{
$param = $row['value'] ;
}
is this right, if so is their away i can add one to the variable name each time round so i get $param1, $param2....
I dont want to have to send a query to the database for each param, is it possible to get them all like this?

The simpliest way is to use an array:
$result = mysql_query("SELECT * FROM params");
$param = array();
$i = 0;
while($row = mysql_fetch_array($result)) {
$param[$i] = $row['value'] ;
$i++;
}
Than you get $param[0], $param[1], ...

You can create variable names like this:
${'var'.1}
${'var'.'1.cat'}
${'var'.$x}
${$y.$x}
and so on.

This seems like a design flaw. But what you can do is:
$count = 1;
$result = mysql_query("SELECT * FROM params");
while($row = mysql_fetch_array($result))
{
$paramname = 'param' . $count++;
$$paramname = $row['value'] ;
}

You may find the list function useful - http://php.net/manual/en/function.list.php
list($param1,$param2,$param3,$param4,$param5,$param6) = mysql_fetch_row($result);
Probably more use when using descriptive variables, just a thought.

Related

how to make a mysql query and turn it into an array in php

if I have a query that looks like this in php...
if ($result3 = $connuser->query("SELECT * FROM devices WHERE uid='".$username."'")){
}
How can I turn $result3 into an array?
Also, separate question, I tried doing
echo $result3;
but it doesn't work. Is there a way to view $result3 so I can see what it looks like?
You can do:
$rows = [];
while($row = mysqli_fetch_array($result3))
{
$rows[] = $row;
}

retrieve all datas from selected column and store

$result = mysql_query("SELECT * FROM Race");
$rows = mysql_num_rows($result);
for ($i = 0 ; $i < $rows ; ++$i)
{
$row = mysql_fetch_row($result);
echo $row[0];
}
above is probably an awkward method but it'll print out all datas stored in first column, which is good but now, I want to store each one of them into an array...
I tried
$array[$i]=$row[0];
and echoed it out, but it just prints"Array"...
I tried
$result = mysql_query("SELECT raceid FROM Race");
while ($row = mysql_fetch_array($result)) {
$array[]=$row[0];
}
...which does the same as code written before, i guess, since it too just print "Array".
Please help! Thank you!!
Do you use simple echo $array;? It's wrong. You can't output array this way.
Use this:
$array = array();
$result = mysql_query("SELECT raceid FROM Race");
while ($row = mysql_fetch_array($result)) {
$array[]=$row[0];
}
foreach($item in $array) {
echo $item."<br>"; // and more format
}
If you want to watch array contents without any format use (e.g. for debugging) print_r or var_dump:
print_r($array);
var_dump($array);
Advice: better to use assoc array.
$array = array();
$result = mysql_query("SELECT raceid FROM Race");
while ($row = mysql_fetch_array($result)) {
$array[]=$row['raceid'];
}
Advanced advice: better to use PDO and object results.
You SQL code will be invulnerable to SQL injections
Code will be more modern and readable.

php - dynamic mysql_query in for loop from url array

I've looked for something similar on stack but nothing exactly as this.
I (think I) need to generate a unique MySQL query inside a loop as each iteration needs to look up a different table. the loop is from an exploded $_GET array.
The problem is creating a differently named mysql query based on the loop iteration. I've done it where the $var name is different but it doesn't work, I think because it is a string not a variable?
Any help appreciated
$temps = explode(",", $_GET['temps']);
$tempCount = count($temps);
for ($i=0; $i<$tempCount; $i++)
{
/*'normal' database lookup
$check = mysql_query("SELECT * FROM _db_".$temps[$i]."");
$checks = array();
while ($row = mysql_fetch_assoc($check)) {
$checks[] = $row;
}*/
//here's where I'm trying to build a 'dynamic' lookup for each loop iteration
$checkTemp=$check.$temps[$i];
$checkTempArray=$check.$temps[$i].'Array';
$checkTemp = mysql_query("SELECT * FROM _db_".$temps[$i]."");
$checkTempArray = array();
while ($row = mysql_fetch_assoc($checkTemp)) {
$checkTempArray[] = $row;
}
}
If I understand correctly you're trying to SELECT * from all tables seperated by , in the $_GET["temps"]
$temps = explode(",", $_GET['temps']);
$tempCount = count($temps);
$allResults = array();
for ($i=0; $i<$tempCount; $i++)
{
$checkTemp = mysql_query("SELECT * FROM _db_".mysql_real_escape_string($temps[$i]));
$allResults[$temps[$i]] = array();
while ($row = mysql_fetch_assoc($checkTemp))
{
$allResults[$temps[$i]][] = $row;
}
}
// Now for example $allResults["john"][3] contains the fourth row in the table _db_john
print_r($allResults["sally"][2]); // print the third row in _db_sally
Seems like a typo in your code
$checkTemp = mysql_query("SELECT * FROM db".$temp[$i]."");
either use
$temps[$i] or just $temp
$temp[$i] doesn't makes any sense
so your query should be instead
$checkTemp = mysql_query("SELECT * FROM db".$temps[$i]."");
EDIT:
for your array part you can use
$$temp = array();
while ($row = mysql_fetch_assoc($checkTemp)) {
$$temp[] = $row;
}

Easier way to assign MySQL table values to variables

I would like to know if there is an easier way to assign all my different columns to a variable. I have over 70 to check if a user has earned a specific song. This is a shortened version of the code. I haven't done all the songs yet and I was wondering if there is an easier way.
$results = mysqli_query($con,"Select * FROM users WHERE user_name ='$username'");
while ($row = mysqli_fetch_array($results))
{
$userpoints = $row['points'];
$intro = $row['intro'];
$fightingfires = $row['fightingfires'];
$may = $row['may'];
$crowdedstreet = $row['crowdedstreet'];
}
Yup, use php extract() http://php.net/manual/en/function.extract.php
Here is a simple example:
$results = mysqli_query($con,"Select * FROM users WHERE user_name ='$username'");
while ($row = mysqli_fetch_array($results))
{
extract($row);
}
// This will give you variables for each item
// so you will get $points for what would have been $row['points'], etc.
Edit: Look at the other people's examples on using extract() which does similar stuff to the foreach loop that I have here:
Try using variable variables:
while ($row = mysqli_fetch_array($results))
{
foreach ($row as $column => $value) {
$$column = $value;
}
}
For each row, essentially you'll be loading variables that have the same name as the column name. It would be like doing:
$points = $row['points'];
$intro = $row['intro'];
$fightingfires= $row['fightingfires'];
$may = $row['may'];
$crowdedstreet= $row['crowdedstreet'];
..etc
Basically, "points" is the name of the first key, and the variable gets the name "points" so you get variable $points.
http://php.net/manual/en/language.variables.variable.php
It's as simple as doing
extract($row);
Your loop will look something like
while ($row = mysqli_fetch_array($results))
{
extract($row);
echo $intro;
}
PHP Manual

getting results of SQL query

I've seen there there are numerous ways to put the results of a SQL query into usable format (that is, variables).
If I have a targeted SQL query that I know will be returning a set of expected values, lets say querying a customer number to pull data, city, state, first and last name, etc..
Code example follows:
$example = '50';
$result = mysql_query("SELECT * FROM customers WHERE customer_ID = '$example'",$db);
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $col => $val) {
if ($col == 'firstname') {
$customerfirstname = $val;
}
}
}
or another way:
$result = mysql_query("SELECT * FROM customers WHERE customer_ID = '$example'",$db);
$myResultArray = array();
while ($row = mysql_fetch_assoc($result))
$myResultArray = $row;
foreach ($myResultArray as $val) {
$customerfirstname = $val['firstname'];
}
That's just two that I could think of.
Is one of the above methods preferable over the other? If so, why?
Is there an alternate method that is even more efficient than either of these?
Neither are preferred.
The foreach's are superfluous.
Since you know the fieldnames you need, you can just do:
while ($row = mysql_fetch_assoc($result)) {
$customerfirstname = $row['firstname'];
}
If you do need to apply a conditional for some reason, you can test for the field's existence in the array:
while ($row = mysql_fetch_assoc($result)) {
if (isset($row['firstname'])) {
$customerfirstname = $row['firstname'];
}
}
Finally, since you appear to be selecting by primary key, the while loop is also unnecessary:
if ($row = mysql_fetch_assoc($result)) {
$customerfirstname = $row['firstname'];
}
I have used the first example that you posed in every website I have done that requires a database and it hasn't failed me yet. As far as if one is better than the other I'd say no. It's just a matter of taste.
There are many ways. Here's a quick one, but I would prefer to set it up using a DTO and accessing it that way... this will work though for your question.
$query = "SELECT first_name, last_name, city FROM customers WHERE customer_id = '$example'";
$result = mysql_query($query);
// If you are expecting only one row of data, then use this:
list($first_name, $last_name, $city) = mysql_fetch_row($result);
//several rows:
while(list($first_name, $last_name, $city) = mysql_fetch_row($result)){
echo $first_name;
}
I seem to be missing something...
Why not this?
$result = mysql_query("SELECT * FROM customers WHERE customer_ID = '$example'",$db);
while ($row = mysql_fetch_assoc($result)) {
$customerfirstname = $row['firstname'];
}
In the first example?

Categories