I am pulling tables from a database and I'm trying to keep the userdata table from being included in the array that is eventually sent to my application. I've tried using array_diff and unset, but I haven't had any luck with it. As tables can be added, the userdata one won't always be in the same position.
The array when I check on JSONlint.com appears like this:
[{"table_name": "OSA"
}, {
"table_name": "OSB"
}, {
"table_name": "userdata"
}]
code in PHP file:
$tables = array();
while ($row = mysqli_fetch_array($result)){
array_push($tables, array("table_name"=>$row[0]));
}
$remove= array({"table_name": "userdata"});
$result = array_diff($tables, $remove);
echo json_encode($result);
The optimal way would probably be to exclude it in the query:
SELECT column FROM table WHERE column <> 'userdata'
Or, just don't add it to the array:
while($row = mysqli_fetch_array($result)) {
if($row[0] != 'userdata') {
$tables[] = array('table_name' => $row[0]);
}
}
Your array_push should work fine but I prefer the above.
But to answer the unset question. Just get the table_data column values, search for userdata and unset that key:
unset($tables[array_search('userdata', array_column($tables, 'table_name'))]);
Related
I am trying to do a mysql fetch but it keeps adding numbered and labeled keys to the array. I want it to record only the labeled names and data in the array.
Am I using the wrong mysql call?
global $con,$mysqldb;
$sql="SHOW FIELDS FROM ".$dbtable;
$tr = mysqli_query($con,$sql);
$tl = mysqli_fetch_array($tr);
$tl = mysqli_fetch_array($tr);
$sql="SELECT * FROM ".$mysqldb.".".$dbtable." ORDER BY ".$tl['Field']." LIMIT 3";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$table[$row[1]] = $row;
}
foreach($table as $item => $data){
foreach(array_keys($data) as $pointer => $field) {
echo"pointer=".$pointer."\t";
echo"field=".$field."\n";
echo "data=".$data[$field]."\n";
}
}
reults
pointer=0 field=0 data=3823
pointer=1 field=PID data=3823
pointer=2 field=1 data=AA
pointer=3 field=symbol data=AA
pointer=4 field=2 data=1
pointer=5 field=value data=1
I want to omit 0, 2, & 4 from the array.
Take a look at the PHP.net manual for the mysqli_fetch_array() function.
You'll see there's an option called resulttype that will accept 1 of 3 values - MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH the default.
Using MYSQLI_ASSOC will remove the numbered keys.
Or check mysqli_fetch_assoc().
Thanks to thebluefox for a speedy response.
I replaced the fetch with:
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
And now the results are being recorded as they should.
I must put to json_encode all values of specifed mysql table column
$fromdate = $_GET['fromdate'];
$getrezhiredh = safe_query("
SELECT rezhour FROM rezhiredhours
WHERE rezdate = '".$fromdate."' ORDER BY rezhour
");
$rows = array();
while($r = mysql_fetch_assoc($getrezhiredh)) {
$rows[] = $r;
}
print json_encode($rows);
With code above i have one problem. This code return result only when in table we have one row with selected data. In this case json_encode() result is
[{"rezhour":"1"}]
But when table have more than one row with selected data result don't return anything but
[]
How put to json_encode() all values selected from table?
EDIT:
I just wonder why in case when we have more rows in table with selected data, result don't give as example below
[{"rezhour": { [0] => "1",[1] => "4" }]
Instead in result we have "[]"
Thank You in advance.
try changing
mysql_fetch_assoc($getrezhiredh)
to
mysql_fetch_object($getrezhiredh)
Results from mysql_fetch_assoc are different than you think. Each row is more or less like this:
array(1)
"rezhour" => "1"
So you access the data it like this:
while($r = mysql_fetch_assoc($getrezhiredh)) {
$rows[] = $r["rezhour"];
}
I'm fairly new to php, and I don't know how to work with arrays very well. Here's the deal, I want to add into a multidimensional array three or more values I obtain from my database, then I want to sort them based on the timestamp (one of the values). After that, I want to show all of the sorted values. I can't seem to do this, here's the code
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, Order, Classification FROM exams WHERE (CurrentState = "Pending")';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if (mysql_num_rows($results) == 0) {
echo '<p>There\'s currently no patient on the waiting list.</p>';
return;
}
while ($rows = mysql_fetch_array($results)) {
extract($rows);
//now is the part that I don't know, putting the values into an array
}
// I'm also not sure how to sort this according to my $TargetTime
asort($sortedTimes);
//the other part I don't know, showing the values,
Thanks for the help!
Well, let's look at your code. First, you have a query that's returning a result set. I don't recommend using mysql_fetch_array because it's not only deprecated (use mysqli functions instead) but it tends to lend itself to bad code. It's hard to figure out what you're referencing when all your keys are numbers. So I recommend mysqli_fetch_assoc (be sure you're fully switched to the mysqli functions first, like mysql_connect and mysqli_query)
Second, I really dislike using extract. We need to work with the array directly. Here's how we do this
$myarray = array();
while ($rows = mysqlI_fetch_assoc($results)) {
$myarray[] = $rows;
}
echo $myarray[0]['ArrivalTime'];
So let's go over this. First, we're building an array of arrays. So we initialize our overall array. Then we want to push the rows onto this array. That's what $myarray[] does. Finally, the array we're pushing is associative, meaning all the keys of the row match up with the field names of your query.
Now, the sorting really needs to be done in your query. So let's tweak your query
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, `Order`, Classification
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime';
This way, when your PHP runs, your database now churns them out in the correct order for your array. No sorting code needed.
$arr = array();
while ($rows = mysql_fetch_array($results)) {
array_push ($arr, $row);
}
print_r($arr);
<?php
$queryWaitingPatients = ' SELECT ArrivalTime, TargetTime, Order, Classification, CurrentState
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime ';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if ($results -> num_rows < 1)
{
echo '<p>There\'s currently no patient on the waiting list.</p>';
}
else
{
while ($rows = mysqli_fetch_array($results))
{
$arrivaltime = $row['ArrivalTime'];
$targettime = $row['targettime'];
$order = $row['Order'];
$classification = $row['Classification'];
echo "Arrival: ".$arrivaltime."--Target time: ".$targettime."--Order: ".$order."--Classification: ".$classification;
}
}
echo "Done!";
//or you could put it in a json array and pass it to client side.
?>
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
I'd really like some help with the following MySQL / PHP problem (maybe bug?)
I'm trying to retrieve and display an array of data from my database using MySQL / PHP, but when I echo out the array, it returns the first value as 'null'.
So, even though the database has the following info:
"Example 1", "Example 2", "Example 3"...
The php echos out:
"null", "Example 2, "Example 3"
I would imagine this would be a common problem, but I haven't managed to find the required information elsewhere on the internet, so I'm hoping you kind folks can help.
My PHP
/* If connection to database, run sql statement. */
if ($conn) {
$fetch = mysql_query("SELECT column FROM table WHERE approved = '1' ");
// declare empty array to fill later
$result = array();
// make sure the MySQL pointer is looking at the first row
mysql_data_seek($fetch, 0);
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
foreach ($row as $value) {
$row_array = $value;
// push info into new array with just the value
array_push($result, $row_array);
}
}
}
/* Free connection resources. */
mysql_close($conn);
/* Toss back results as json encoded array. */
echo json_encode($result);
UPDATE
New code courtesy of Mark B:
if ($conn)
{
$sql = "SELECT column_name FROM table WHERE comment_approved = '1' ";
$query = mysql_query($sql) or die(mysql_error());
$result = array();
while ($row = mysql_fetch_assoc($query)) {
$result[] = $row['column_name'];
}
}
/* Free connection resources. */
mysql_close($conn);
/* Toss back results as json encoded array. */
echo json_encode($result);
NOTE:
The 'null' problem still occurs with or without the:
mysql_data_seek($fetch, 0);
as that appears to do nothing.
Any help would be great!
SOLVED
Thanks to Mark B who pointed out that the problem was probably in the database rather than the PHP, it turned out there was the character ` lurking where there should have been a '. This caused the information to appear 'null'.
$sql = "SELECT column FROM table WHERE approved = '1'";
$result = mysql_query($sql) or die(mysql_error());
$data = array();
while($row = mysql_fetch_assoc($result)) {
$data[] = $row['column'];
}
echo json_encode($data);
You shouldn't have to do the seek, as you've not done anything with the result at the time. And since you're only fetching a single column from the database, there's no need for the inner foreach() loop either.
Try removing the call to mysql_data_seek. I see no reason why the MySQL pointer wouldn't already point to the first row at the first call to mysql_fetch_array.
You could try removing mysql_data_seek($fetch, 0); as the pointer will already be on the first record if you have just made the query.