Explode array from mysql and assign to variables PHP - php

OK so in the database I have a column that contains data like this
:Novice:Intermediate:Advanced
( some columns have more than the 3 listed above )
What I'm trying to do is explode at the : and then assign the exploded values to variables
At most there are 4 bits of data separated by : so a max of 4 variables
Here is the code I have so far
$query = mysql_query("SELECT * FROM venues",$dbc);
$result = mysql_fetch_assoc($query);
do{
$eventtype = explode(':',$result['def_sessions']);
list($var1, $var2, $var3, $var4) = $eventtype;
//print_r(explode(":",$result['def_sessions']));
echo $var1.'<br>'.$var2.'<br>'.$var3.'<br>'.$var4;
}while($result = mysql_fetch_assoc($query));
It works ( to an extent )
For example record ID 13 has this in the column
:Novice:Novice/Intermediate:Intermediate/Advanced:Advanced:
The output however does NOT display the final
Advanced
it only displays
Novice
Novice/Intermediate
Intermediate/Advanced
Anyone help me please I am pulling hair out badly here .
I have also tried adding another $var5 but that doesnt help

I forgot to add $var5 to the list()
$query = mysql_query("SELECT * FROM venues WHERE id ='30'",$dbc);
$result = mysql_fetch_assoc($query);
do{
$eventtype = explode(':',$result['def_sessions']);
list($var1, $var2, $var3, $var4,$var5) = $eventtype;
//print_r(explode(":",$result['def_sessions']));
echo $var1.'<br>'.$var2.'<br>'.$var3.'<br>'.$var4.'<br>'.$var5;
}while($result = mysql_fetch_assoc($query));
Working fine now :)

do it like this
$query = mysql_query("SELECT * FROM venues",$dbc);
$result = mysql_fetch_assoc($query);
$i=0;
while($result = mysql_fetch_assoc($query)){
$var1[$i]=$row['Novice'];
$var2[$i]=$row['Intermediate'];
$var3[$i]=$row['Advanced '];
echo $var1[$i].'<br>'.$var2[$i].'<br>'.$var3[$i].'<br>';
$i++;
}

Your problem it´s how you are trying to get the values from the table and explode.
I use something like this:
$query = mysql_query("SELECT * FROM venues",$dbc);
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($result)) {
$def_sessions = row(number of yor row);
$eventtype = explode(":", def_sessions);
$val0 = $eventtype[0];
$val1 = $eventtype[1];
...
}

Related

Why does Mysql query only give me the last result of a query instead of all results?

getting values
session_start();
$text = $_SESSION['text']; (it's an array with multiple values)
making the array suitable for the query
$text = array_filter($text);
$text = implode("','", $text);
$text = "'".$text."'";
run query
$sql = "SELECT id_category FROM eiofm_category_lang WHERE name IN (".$text.")";
$query = mysql_query($sql);
get query result
while($result = mysql_fetch_array($query))
{
var_dump($result);
}
EDIT
I got it working with a foreach loop but still don't know why the while loop didn't work.
This worked for me
foreach($text as $values){
$query = mysql_query("SELECT id_category FROM eiofm_category_lang WHERE link_rewrite LIKE '$values'");
while ($row = mysql_fetch_assoc($query))
{
array_push($array, $row['id_category']);
}}
But still don't know why the while loop didn't work

array_sum returning the sum of values as string

This seems like it should be really straightforward, but I keep getting unexpected output. I'm trying to access specified rows in a SQL database which each contain a numerical value and then calculate the sum of those values. PHP is concatenating the values as if they were strings even after I've set the datatype of the values to float. My code:
$query = "SELECT * FROM populations WHERE username ='{$_SESSION[name]}' AND region_name = 'region'"
$query .= "AND city_name = 'city'";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
$population_value = $row['population_value'];
$population_value = is_array($population_value) ? $population_value : array($population_value);
foreach($population_value as $value){
echo $value;
}
echo array_sum($population_value);
}
I have also tried:
$total = array("");
foreach($population_value as $value){
floatval($value);
array_push($total, $value);
echo $value;
}
echo array_sum($total);
My output is always something like: 100002000030000
with 10,000 20,000 and 30,000 being the values of each population.
I've successfully calculated sums using foreach with values that weren't retrieved from MySQL.
What is going on here?
$query = "SELECT * FROM populations WHERE username ='{$_SESSION[name]}' AND region_name = 'region'"
$query .= "AND city_name = 'city'";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
$population_value = $row['population_value'];
//This is actually rewriting the array or NOT adding the value to it.
$population_value = is_array($population_value) ? $population_value : array($population_value);
//ok, so you're going to repeatedly output this?
foreach($population_value as $value){
echo $value;
}
echo array_sum($population_value);
}
I think what you want is this:
$query = "SELECT * FROM populations WHERE username ='{$_SESSION[name]}' AND region_name = 'region'"
$query .= "AND city_name = 'city'";
$result = mysqli_query($connection, $query);
$population_value=array(); //Initialize the array so we can just add to it.
while($row = mysqli_fetch_assoc($result)) {
$population_value[]= intval($row['population_value']); //Just making sure we get a number.
echo end($population_value); //We could output the row again, or just grab the last element of the array we added.
}
//Now that the array is fully populated and we've made sure it's only numbers, we output the grand total.
echo array_sum($population_value);
First, don't initialize the array with an empty string. Do this instead:
$total = array();
or with the new style:
$total = [ ];
Second, rewrite the floatval thing like this:
array_push($total, floatval($value));
That should fix it...

Show selected data as array value instead of string

I'm trying to put data from my database into seperate arrays within another array. This works but when I'm trying to fetch the 'user_id' information, it only shows one number so it works like a string. How can I get it to work like an array and get the entire user_id?
$fetch = mysqli_query($con, "SELECT * FROM spotify_userdata");
$return_arr = [];
while ($row = mysqli_fetch_array($fetch, MYSQL_ASSOC)) {
$return_arr[] = array(
$row_array['user_id'] = $row['user_id'],
$row_array['name'] = $row['name'],
$row_array['artists'] = $row['artists'],
);
}
$user = json_encode($return_arr[0]);
echo $user[2];
This code returns 1 so it show the third number of the user_id. How can I get it to show the entire user_id like this: 111434343
You have many things in your code that's wrong:
Remove the last array item's comma
Change
$return_arr = [];
To
$return_arr = array();
3.Add:
$row_array = array()
at the begginning of all that code
At the end your code must be like this:
$fetch = mysqli_query($con, "SELECT * FROM spotify_userdata");
$row_array = array();
while ($row = mysqli_fetch_array($fetch, MYSQL_ASSOC)) {
$return_arr = array(
$row_array['user_id'] = $row['user_id'],
$row_array['name'] = $row['name'],
$row_array['artists'] = $row['artists'],
);
}
$user = json_encode($return_arr[0]);
According to your code you should use:
echo $user['user_id'];
But the real problem is - where is $row_array initialized?!?
And even bigger problem - why use "=" inside array creation in the while ... it seems to me that "=>" would fit better, don't you think?

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.

php query function / class

It must be Monday, the heat or me being stupid (prob the latter), but for the life of me I cannot get a simple php function to work.
I have a simple query
$sql = mysql_query("SELECT * FROM table WHERE field_name = '$input'");
Which I want to run through a function: say:
function functionname($input){
global $field1;
global $field2;
$sql = mysql_query("SELECT * FROM table WHERE field_name = '$input'");
while($row = mysql_fetch_array($sql)) :
$field1[] = $row['field1'];
$field2[] = $row['field2'];
endwhile;
mysql_free_result($sql);
}
So that I can call the function in numerious places with differeing "inputs". Then loop through the results with a foreach loop.
Works fine the first time the function is called, but always gives errors there after.
As said "It must be Monday, the heat or me being stupid (prob the latter)".
Suggestions please as I really only want 1 function to call rather than rewrite the query each and every time.
This is the error message
Fatal error: [] operator not supported for strings in C:\xampp\htdocs\functions.php on line 270
function functionname($input){
$sql = mysql_query("SELECT field1,field2 FROM table WHERE field_name = '$input'");
$result = array('field1' => array()
'field2' => array()
);
while($row = mysql_fetch_array($sql)) :
$result['field1'][] = $row['field1'];
$result['field2'][] = $row['field2'];
endwhile;
mysql_free_result($sql);
return $result;
}
it seems that somewhere the $field1 or $field2 are converted to strings and you cant apply the [] to a string...
i'd say that you have to do:
$field1 = array();
$field2 = array();
before the WHILE loop
The problem is that you so called arrays are strings!
global $field1;
global $field2;
var_dump($feild1,$feild2); //Will tell you that there strings
Read the error properly !
[] operator not supported for strings
And the only place your using the [] is withing the $feild - X values
GLOBAL must work because the error is telling you a data-type, i.e string so they must have been imported into scope.
another thing, why you selecting all columns when your only using 2 of them, change your query to so:
$sql = mysql_query("SELECT feild1,feild2 FROM table WHERE field_name = '$input'");
another thing is that your using mysql_fetch_array witch returns an integer indexed array, where as you want mysql_fetch_assoc to get the keys.
while($row = mysql_fetch_assoc($sql)) :
$field1[] = $row['field1'];
$field2[] = $row['field2'];
endwhile;
What I would do
function SomeFunction($variable,&$array_a,&$array_b)
{
$sql = mysql_query("SELECT field1,field2 FROM table WHERE field_name = '$variable'");
while($row = mysql_fetch_assoc($sql))
{
$array_a[] = $row['field1'];
$array_b[] = $row['field2'];
}
mysql_free_result($sql);
}
Then use like so.
$a = array();
$b = array();
SomeFunction('Hello World',&$a,&$b);
In my opinion, it's pretty unusual and even useless approach at all.
This function is too localized.
To make a general purpose function would be a way better.
<?
function dbgetarr(){
$a = array();
$query = array_shift($args);
foreach ($args as $key => $val) {
$args[$key] = "'".mysql_real_escape_string($val)."'";
}
$query = vsprintf($query, $args);
$res = mysql_query($query);
if (!$res) {
trigger_error("dbgetarr: ".mysql_error()." in ".$query);
return FALSE;
} else {
while($row = mysql_fetch_assoc($res)) $a[]=$row;
}
return $a;
}
and then call it like this
$data = dbgetarr("SELECT field1,field2 FROM table WHERE field_name = %s",$input);
foreach ($data as $row) {
echo $row['field1']." ".$row['field1']."<br>\n";
}
To understand your issue, we need the error, however, are you sure you are going about this in the right way?
Why do you need to call the function multiple times if you are just changing the value of the input field?
You could improve your SQL statement to return the complete result set that you need the first time.. i.e. SELECT * FROM table GROUP BY field_name;
Not sure if that approach works in your scenario, but in general you should aim to reduce the number of round trips to your database.
I don't know, i right or not. But i advise to try this:
function functionname($input){
global $field1;
global $field2;
$sql = mysql_query("SELECT * FROM `table` WHERE `field_name` = '" . $input . "'");
while($row = mysql_fetch_assoc($sql)) :
$field1[] = $row['field1'];
$field2[] = $row['field2'];
endwhile;
mysql_free_result($sql);
}

Categories