getting results of SQL query - php

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?

Related

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.

Looping through MySQL results and saving values to a $_SESSION

I am trying to store each column name in my database into its own $_SESSION. For example, say my column names are column_one, column_two, column_three, column_four, and column_five. I want these to be stored in a $_SESSION like $_SESSION['column_one'], $_SESSION['column_two'], etc. I am trying to do this in a loop but I have not been successful. How would I setup the loop to achieve this?
$query = "SELECT * FROM table WHERE user_id = $id";
$result = mysqli_query($dbc, $query);
$num = mysqli_num_rows($result);
if ($num == 1) {
//User was found
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$_SESSION['user_id'] = $row['user_id'];
}
}
Could you try this:
$id = mysqli_real_escape_string($dbc,$id);
$query = "SELECT * FROM table WHERE user_id = $id";
$result = mysqli_query($dbc, $query);
$num= mysqli_num_rows(result);
if ($num == 1) {
$row = mysqli_fetch_assoc($result);
$_SESSION['UserData'] = $row;
}else{
//handle error or user not found
}
echo '<pre>';
print_r($_SESSION['UserData']);
echo '</pre>';
You don't have necessity of use while or another loop, so is just one row
Something like this should work:
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
foreach($row as $column => $value) {
$_SESSION[$column] = $value;
}
}
Extra advice for safeguarding against SQL injection, the following two lines:
$id = mysqli_real_escape_string($dbc, $id);
$query = "SELECT * FROM table WHERE user_id = '$id'";
Update:
Thanks to EmilioGort who pointed out the missing connection parameter in mysqli_real_escape_string. See mysqli_real_escape_string docs.
While the other answers proposed a way to do, I'd strongly propose to not do this at all. Why?
First of all $row contains all details of the user in a well defined array form. It is generally good to keep this structure well prepared.
More important: Flattening $row might force name clashes like so:
Suppose $row has a property userName and somewhere else in your application you eventually set
$_SESSION[ 'userName' ] = $newUserName;
The new assignment to $_SESSION[ 'userName' ] might unintentionally change the property saved during the login process.
You might argue "Right now, my code doesn't use userName in $_SESSION'. Right! Unfortunately, you might use just this name for something else many month later on...
A better solution
I'd save the user detail like this:
$_SESSION[ 'sys$userDetails' ] = $row;
Imagine the prefix sys$ as being an indicator for framework generated properties of your session.
Thus, business logic related session data shouldn't have the sys$ prefix.

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

Generating variables from db content?

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.

How to put MySQL cell values into variables named after column names in PHP

This code selects cell values in MySQL and manually adds them to PHP variables:
$sql = "SELECT * FROM table LIMIT 0,1";
$result = mysql_query($sql);
while($rows = mysql_fetch_array($result)) {
$col1 = $rows['col1'];
$col2 = $rows['col2'];
$col3 = $rows['col3'];
.....
}
This is obviously unmanageable for multiple and large tables.
What's a better way to automatically generate the variable names and values without manually entering all the column names on all tables?
I think this is what you're looking for
$sql = "SELECT * FROM table LIMIT 0,1";
$result = mysql_query($sql);
while ($rows = mysql_fetch_array($result, MYSQL_ASSOC)) {
foreach ($rows as $key => $value) {
$$key = $value;
}
}
You could use extract() for that. But I'd keep the values in the array.
..SELECT x,y,z FROM ..
while( false!==($rows=mysql_fetch_array($result, MYSQL_ASSOC)) ) {
extract($rows);
echo $x;
...
}
Wouldn't it be more convenient having associative arrays? That way you can call your variables with their column name as you describe plus you have the benefit of having them bundled in one unit which is much better if you need to pass more than one of them to any function or view or whatever.
so I would use mysql_fetch_assoc and that's it.
I don't recommend having a variable for each row, I used to do the same to simplify writing HTML later:
echo "<tr><td>$name</td><td>$count</td></tr>";
Instead of:
echo "<tr><td>{$row['name']}</td><td>{$row['count']}</td></tr>";
Until I found a better and more readable way do it using mysql_fetch_object
while ($row = mysql_fetch_object($result)) {
:
echo "<tr><td>{$row->name}</td><td>{$row->count}</td></tr>";
:
}
Use variable variables:
Code example:
$a = 'col1';
$$a = 'somevalue';
echo $col1;
will output 'somevalue'.
http://www.php.net/manual/en/language.variables.variable.php

Categories