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
Related
Can someone please help? I'm new to PHP and struggling to make this bit of code to work. For example I have a sql database table with the following schema and data:
Type....rent_price
a..........100
b..........200
c..........300
I want to be able to echo say, "a", in one section and "200" in another. The following code will display "a" but then I can't seem to get it to display anything from the rent_price column using a second array.
$result = $mysqli->query("SELECT * FROM dbc_posts ORDER BY ID ASC limit 3");
for ($set = array (); $row = $result->fetch_assoc(); $set[] = $row['type']);
for ($set1 = array (); $row = $result->fetch_assoc(); $set1[] =$row['rent_price']);
?>
<?php echo $set[0];?>
<?php echo $set1[1];?>
You loop through the results twice, without resetting. Try to loop only once:
$result = $mysqli->query("SELECT * FROM dbc_posts ORDER BY ID ASC limit 3");
$set = array ();
$set1 = array ();
while ($row = $result->fetch_assoc())
{
$set[] = $row['type'];
$set1[] =$row['rent_price'];
}
?>
<?php echo $set[0];?>
<?php echo $set1[1];?>
Depending on what you mean by '"a" in one section and "200" in another', you may be able to forgo creating the intermediate arrays and just print the values from your query as you fetch them. Two cells in a table row, for example:
while ($row = $result->fetch_assoc()) {
echo "<tr><td>$row[type]</td><td>$row[rent_price]</td></tr>";
}
your data is in the first element of array
$set1[0]
but youre probably better off maintaining the naming throughout
$results = array();
while ($row = $result->fetch_assoc()){
$results[] = $row;
}
foreach ($results as $result){
echo $result['type'];
echo $result['rent_price'];
}
OR
$results = array();
while ($row = $result->fetch_assoc()){
$results['types'][] = $row['type'];
$results['rent_prices'][] = $row['rent_price'];
}
foreach ($results['types'] as $type){
echo $type;
}
foreach ($results['rent_prices'] as $rent_price){
echo $rent_price;
}
Some code to fetch the field names by connecting it with db:
<?php
#mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$result = mysql_query("SELECT * FROM sample");
$storeArray = Array();
while ($row = mysql_fetch_array($result)) {
if (mysql_num_rows($result) > 0) {
$storeArray = $row['name'];
echo $storeArray;
}
}
?>
The above code works just fine but when it runs it gives me ramuraja. Here ramu and raja are seperate fields. But its giving me a joined output.
How can i get the two field value seperately like ramu and raja.
You print / echo the values directly after one another. Using echo $storeArray.'<br>'; would print a linebreak additionally, thus printing
ramu
Raja
However, you could also store all the variables in an array, for example with $storeArray[] = $row['name']; instead of $storeArray = $row['name'];. That would create a new array element, the value being $row['name'], while the key is incrementing for every element being added.
After having received all rows that match the query, you could loop through the array and Display the answers.
EDIT: Please check out mysqli or PDO; those PHP extensions are standard with newer versions and should be used instead of the old (and now deprecated) mysqli solution. Don't worry, they can do the same (and much more).
You need to do a for each statement to iterate through the array and echo the field along with a line break
First of all, you're declaring $storeArray as an array in this line: $storeArray = Array();, but later you replace it with a string $storeArray = $row['name'];
If you want to use $storeArray as an array, change this line:
$storeArray = $row['name'];
into
$storeArray[] = $row['name']; //add element to the array
Now loop all the results (remove echo $storeArray;)
After you've fetched all the results you kan echo them like:
foreach($storeArray as $name){
echo $name.'<br>';
}
Some confusion in code ....
first check ifthere are results:
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
....
}
}
than be more clear about what you wont:
an array :
$storeArray = Array();
or a string:
$storeArray = $row['name'];
I would so like this:
$storeArray = Array();
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$storeArray[] = $row['name'];
}
}
// array
print_r($storeArray);
// string
echo implode(',', $storeArray);
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?
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.
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