Jump to content

[PHP] - Add an array result of a MySQL query to a String


Recommended Posts

Posted

I need some help.

 

Playing with doing something in PHP where the resultant query needs to be an array that I'm then going to throw out to Google Charts API to produce some charts.

 

I'm using a mixture of Dreamweaver and adding bits as I fumble along (I'm not a programmer), but so far the following when used in my page does output to the browser the array of data I'm after, however I want to put this into another string so I can output it as a string elsewhere.

 

while ($row = mysql_fetch_array($ResultChartX, MYSQL_NUM)) {
   printf("%s,", $row[4]);  
}

?>

 

As I said, the above bit works as the printf is showing the data I want, but I want that output to go into another string (shall we say $chartx_values) not the screen.

 

Hope that makes sense, thanks in advance!

 

Pete

Posted

This is one way of doing it:

 

$ResultChartX = mysql_query($query_rsSensorData);
// Create a new array for the values
$_values = array();
while ($row = mysql_fetch_array($ResultChartX, MYSQL_NUM)) {
   // Add value from DB row to the array
   $_values[] = $row[4];
}

// Glue all the array values together with a comma - $chartx_values is your string.
$chartx_values = implode(',', $chartx_values);
?>

  • Thanks 1
Posted (edited)

Didn't work, but noticed the error. However, you put me in the right direction, so many many thanks. Works now:

 

// Glue all the array values together with a comma - $chartx_values is your string.
$chartx_values = implode(',', [b]$_values[/b]>

 

Again, really appreciate the help - put me back on track now.

 

This is my first attempt at putting something together using PHP; have to say though, do like the way it goes together.

 

Pete

Edited by FragglePete
Posted

For reference the answer to your original question is to use sprintf(), which returns the string for assignment instead of just outputting it.

 

 $monkeys = 1;
 $string = sprintf("%d monkeys ready for powdarring", $monkeys);
 echo $string;
?>

  • Thanks 1

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now



×
×
  • Create New...