i have a mysql table the contains an index id, a data entry and 10 other columns called peso1, peso2, peso3...peso10. im trying to get the last 7 peso1 values for a specific id.
like:
$sql = mysql_query("SELECT * FROM table WHERE id='$id_a' ORDER BY data DESC LIMIT 0, 7");
when i try to fetch those values with mysql_fetch_array, i get all values together.
example:
while($line = mysql_fetch_array($sql)) {
echo $line['peso1'];
}
i get all peso1 values from all 7 days together. How can i get it separated?
They will appear all together because you are not separating them as you loop through them.
for example, insert a line break and you will see them on separate lines
while($line = mysql_fetch_array($sql)) {
echo $line['peso1'] ."<br />";
}
You could key it as an array like so
$myArray = array();
$i = 1;
while($line = mysql_fetch_array($sql)) {
$myArray['day'.$i] = $line['peso1'];
$i++;
}
Example use
$myArray['day1'] // returns day one value
$myArray['day2'] // returns day two value
It's not clear what you mean by "separated" so I'm going to assume you want the values as an array. Simply push each row field that you want within your while loop onto an array like this:
$arr = array();
while($line = mysql_fetch_array($sql)) {
$arr[]=$line['peso1'];
}
print_r($arr);//will show your peso1 values as individual array elements
Related
So, I'm trying to display an associative array generated from a table in my database. These are the steps I'm trying to accomplish:
Get result set from database that's already sorted in certain order based on a column(Ascending/Descending).
Add/Transfer/Append each record/row in the result set to another array. While in the process of appending, check if the array we are adding records has a value(based on a different column) similar to the record we are currently adding.
If the value we are checking for is already there, skip appending. If not, append the record and continue with the loop until the end of the result set.
This is the sample data I am working with, tbl_user_details:
Sample data
As you can see, it has been sorted in descending order based on the user_pos column. If you look at the user_id column, we have duplicate values. What I am trying to achieve is adding each record to an array and skipping the duplicate values based on the user_id column.user_id = 4 and user_pos = 7. Next will be ada with user_id = 2 and user_pos = 6. The next record which we are not going add is woz with user_id = 2 and user_pos = 5 because we already have someone with user_id = 2. So, we skip to adding ghopper who has user_id = 3 and user_pos = 4... and so forth. I think this example explains the flow of data I need displayed.
I've tried some simple code to get this done which it's clearly not working. Here is the snippet:
$query3 = "SELECT * FROM `user_details` ORDER BY `user_details`.`user_pos` DESC";
$user_set = mysqli_query($connection, $query3);
if (!$user_set) {
die("Database query failed.".mysqli_error($connection));
}
$user_arr = array();
while ($row = mysqli_fetch_assoc($user_set)) {
if (in_array($row["user_id"], $user_arr)) {
continue; // skip if we already have this value in array
}
$user_arr[] = $row;
}
The records that should be displayed are of aswartz, ada, ghopper and rasmusl. The rest are ignored. When I display the data in '$user_arr[]' using the foreach loop method, it still displays the whole data as it is on the table.
It will become multi dimensional array when you add row to array so you cant check user_id in it. There are many other solutions to check unique record but One simplest solution is to assign user_id as key then check key for duplication
while ($row = mysqli_fetch_assoc($user_set)) {
if (isset($user_arr[$row["user_id"]])) {
continue; // skip if we already have this value in array
}
$user_arr[$row["user_id"]] = $row;
}
Note: If you want unique records only then you can use DISTINCT in query
Use another $tempArr which will contain only user_id to in in_array, In you code you are checking user_id against array or whole row which is user details not just against user_ids
$user_arr = array();
$tempArr = array();
while ($row = mysqli_fetch_assoc($user_set)) {
if (in_array($row["user_id"], $tempArr)) {
continue; // skip if we already have this value in array
}
$user_arr[] = $row;
$tempArr[] = $row["user_id"];
}
I'm using this script to get data from a database
$sql = "SELECT * FROM items WHERE catid = 1";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
echo $row['extra_fields'];
}
The output is:
[{"id":"1","value":"johndoe"},{"id":"2","value":"marydoe"}]
I want to extract/print only the value corresponding to "id":"1" (that in this case is 'johndoe'). I'm not able to extract it from the above data type.
To read JSON in PHP use
while($row = mysql_fetch_array($result)){
$array = json_decode($row['extra_fields'];
// Do something with $array['id']
}
Did you realise you can directly go for that data in MySQL?
SELECT value FROM items WHERE id = 2;
edit:
Basically your query is
SELECT comma-separated column names or star for all, use only what you really need to save bandwidth, e.g. SELECT id, value
FROM table-name, e.g. FROM mytable
WHERE columnname = desired value, e.g. WHERE id = 2
You want to query only the required columns in the required rows. Imagine one day you would have to parse 1 million users every time you want to get an id... :)
The output is JSON. Use PHP's json_decode function.
while($row = mysql_fetch_array($result)){
$array = json_decode($row['extra_fields']);
foreach($array AS $item) {
echo $item['id'];
}
}
Currently this is the code that fits my needs:
while($row = mysql_fetch_array($result)){
$array = json_decode($row['extra_fields']);
$value = $array[0]->value;
}
You should do it in the mysql query part. For example, set the ID = 1 in the query.
I'm probably missing something easy, but I seem to be blocked here... I have a MySQL database with two tables and each table has several rows. So the goal is to query the database and display the results in a table, so I start like so:
$query = "SELECT name, email, phone FROM users";
Then I have this PHP code:
$result = mysql_query($query);
Then, I use this to get array:
$row = mysql_fetch_array($result);
At this point, I thought I could simply loop through the $row array and display results in a table. I already have a function to do the looping and displaying of the table, but unfortunately the array seems to be incomplete before it even gets to the function.
To troubleshoot this I use this:
for ($i = 0; $i < count($row); $i++) {
echo $row[$i] . " ";
}
At this point, I only get the first row in the database, and there are 3 others that aren't displaying. Any assistance is much appreciated.
You need to use the following because if you call mysql_fetch_array outside of the loop, you're only returning an array of all the elements in the first row. By setting row to a new row returned by mysql_fetch_array each time the loop goes through, you will iterate through each row instead of whats actually inside the row.
while($row = mysql_fetch_array($result))
{
// This will loop through each row, now use your loop here
}
But the good way is to iterate through each row, as you have only three columns
while($row = mysql_fetch_assoc($result))
{
echo $row['name']." ";
echo $row['email']." ";
}
One common way to loop through results is something like this:
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
// do stuff with $row
}
Check out the examples and comments on PHP.net. You can find everything you need to know there.
I have a mysql table with columns id, f1, f2, f3, ..., f20 where id is productID and f1,...f20 are product features. Depending on each product, some might have all, none or only some columns filled.
Each column holds a delimited string like a#b#c#d where a,b,c,d are values in different languages (a=english, b=french etc)
I need to select a row by it's id, explode each column's value (f1,f2...) with '#' in order to get the language part I need and then pass the values to an array in order to use in my product spec page.
How do I loop through the fetched row (i'm using $row = my_fetch_array) and put the exploded value into a one dimension array like $specs=('green', 'M', '100', 'kids'...) etc?
PS:I know, is complicated but I cant come up with a better idea right now.
Try this:
$result = mysql_query("...");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$arr = array();
foreach ($row as $k=>$v)
{
$features = explode("#", $v);
$value = $features[1]; // get the specific language feature
$arr[] = $value;
}
$specs = join(", " , $arr);
}
Not sure this is the best way togo but you could define an array with your langs, then access the result by lang
<?php
$langs=array('eng'=>0,'fr'=>1,'ger'=>2,'geek'=>3);
while ($row=mysql_fetch_assoc($result)) {
$specs=explode('#',$row['f1']);
$other=explode('#',$row['f2']);
...
}
//Get lang from cookie that you could set elsewhere
$lang=(isset($_COOKIE['lang']))?$_COOKIE['lang']:'eng';
echo $specs[$langs[$lang]];
?>
My solution for how I understand you question:
// Make a MySQL Connection
$sQuery = "SELECT f1,f2,... FROM table WHERE id = ...";
$oResult = mysql_query($sQuery) or die(mysql_error());
//Fetch assoc to use the column names.
$aRow = mysql_fetch_assoc($oResult);
//Prepare the product properties array
$aProductProperties = array("English"=>array(),"French"=>array(),"Dutch"=>array());
//Loop over all the columns in the row
foreach($aRow as $sColName=>$sColVal){
//Explde the column value
$aExplodedCol = explode("#",$sColVal);
//The code below could be nicer when turned into a looped that looped over every language,
//But that would make the code less readable
$aProductProperties['English'][$sColName] = $aExplodedCol[0];
$aProductProperties['French'][$sColName] = $aExplodedCol[1];
$aProductProperties['Dutch'][$sColName] = $aExplodedCol[2];
}
//Done, you should now have an array with all the product properties in every language
How can i get every row of a mysql table and put it in a php array? Do i need a multidimensional array for this? The purpose of all this is to display some points on a google map later on.
You need to get all the data that you want from the table. Something like this would work:
$SQLCommand = "SELECT someFieldName FROM yourTableName";
This line goes into your table and gets the data in 'someFieldName' from your table. You can add more field names where 'someFieldName' if you want to get more than one column.
$result = mysql_query($SQLCommand); // This line executes the MySQL query that you typed above
$yourArray = array(); // make a new array to hold all your data
$index = 0;
while($row = mysql_fetch_assoc($result)){ // loop to store the data in an associative array.
$yourArray[$index] = $row;
$index++;
}
The above loop goes through each row and stores it as an element in the new array you had made. Then you can do whatever you want with that info, like print it out to the screen:
echo $row[theRowYouWant][someFieldName];
So if $theRowYouWant is equal to 4, it would be the data(in this case, 'someFieldName') from the 5th row(remember, rows start at 0!).
$sql = "SELECT field1, field2, field3, .... FROM sometable";
$result = mysql_query($sql) or die(mysql_error());
$array = array();
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
echo $array[1]['field2']; // display field2 value from 2nd row of result set.
The other answers do work - however OP asked for all rows and if ALL fields are wanted as well it would much nicer to leave it generic instead of having to update the php when the database changes
$query="SELECT * FROM table_name";
Also to this point returning the data can be left generic too - I really like the JSON format as it will dynamically update, and can be easily extracted from any source.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo json_encode($row);
}
You can do it without a loop. Just use the fetch_all command
$sql = 'SELECT someFieldName FROM yourTableName';
$result = $db->query($sql);
$allRows = $result->fetch_all();
HERE IS YOUR CODE, USE IT. IT IS TESTED.
$select=" YOUR SQL QUERY GOOES HERE";
$queryResult= mysql_query($select);
//DECLARE YOUR ARRAY WHERE YOU WILL KEEP YOUR RECORD SETS
$data_array=array();
//STORE ALL THE RECORD SETS IN THAT ARRAY
while ($row = mysql_fetch_array($queryResult, MYSQL_ASSOC))
{
array_push($data_array,$row);
}
mysql_free_result($queryResult);
//TEST TO SEE THE RESULT OF THE ARRAY
echo '<pre>';
print_r($data_array);
echo '</pre>';
THANKS