I have two different tables. For those I select some results.
On the first based on a min/max and for the second based on Lat/Lng. That's easy (don't pay much attention on the values) and is created by:
$sql1="SELECT * FROM events WHERE value BETWEEN '".$min2d."' AND '".$max2d."'";
$sql2="SELECT * FROM locations WHERE (lng BETWEEN ".$wl." AND ".$el.") AND (lat BETWEEN '".$sl."'AND'".$nl."')";
Now that we have downsized the results, we want to match the 'id' row of the first table if exists on the second table. On success we create results.
So let's get some numbers first:
$result1 = mysql_query($sql1);
$result2 = mysql_query($sql2);
$numRows1 = mysql_num_rows($result1);
$numRows2 = mysql_num_rows($result2);
$loopCount1 = 1;
$loopCount2 = 1;
For more efficient parsing of the JSON (from a user) we want to sort the events by creating them into a JSON array with the location as a 'holder'. So that means, each location might have several events.
Some locations might not have events, but also some events might not correspond to a location. Our only comparing method is by the same 'id'.
With my following try, which is of course buggy creates for all (that's wrong) locations results even if for those without events. And that's where I need your precious help.
$json = '{"markers":[';
while ($row2 = mysql_fetch_array($result2)){
$json .= '{"coordinates": { "lat":'. $row2['lat'] .', "lng" : ' . $row2['lng'] .'},'
.'{"events" : [';
while ($row1 = mysql_fetch_array($result1)){
if ($row1['id']=$row2['id'])
$json .= '{ '
.'"title": "'.$row1['title'].'",'
.'"info": "'.$row1['info'].'",'
.'"}';
// add comma for Json if not final row
if ($loopCount1 < $numRows1) {
$json .= ', ';
$loopCount1++;}
}
$json .= ']}}';
// add comma for Json if not final row
if ($loopCount2 < $numRows2) {
$json .= ', ';
$loopCount2++;}
}
$json .= ']}';
And finally an echo:
echo $json;
To compare values of two tables and print results as json please use below code,
<?php
/* connect to the db */
$link = mysql_connect('localhost','username','password') or die('Cannot connect to the DB');
mysql_select_db('db_name',$link) or die('Cannot select the DB');
/* grab the posts from the db */
$query1 = "SELECT * FROM test1";
$result1 = mysql_query($query1,$link) or die('Error query: '.$query1);
$query2 = "SELECT * FROM test2";
$result2 = mysql_query($query2,$link) or die('Error query: '.$query2);
/* create one master array of the records */
$posts = array();
if(mysql_num_rows($result1) && mysql_num_rows($result2)) {
while($post1 = mysql_fetch_assoc($result1)) {
$post2 = mysql_fetch_assoc($result2);
if($post1['name'] == $post2['name'])
$posts[] = array('test1'=>$post1,'test2'=>$post2);
}
}
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
/* disconnect from the db */
#mysql_close($link);
?>
Related
I have been on this for nearly a full 24 hours now.
I am not a coder and I am not pretending to be, I just have a problem I cannot solve that I'd like your help with :)
I have a database column full of latitude and longitude locations. I want to create a file called points.json which matches the following format:
{
"points": [
[LAT, LONG],
[LAT, LONG],
[LAT, LONG],
[LAT, LONG],
[LAT, LONG]
]
}
Where LAT and LONG are the records from the database (52.93839800000001,-1.1425212999999999)
My current code gets all the locations from the database and outputs on screen one lat/long per row:
$sql = "SELECT latlong from requests";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['latlong'] . "<br>";
}
} else {
echo "0 results";
}
$con->close();
Table structure:
|id|user| latlong |
----------------------------------
|1|user|52.93839801,-1.1425212999|
I just cannot work out to get it into the above format. I have tried a number of different json_encode methods but end up with separate JSON array for each row?
Ultimately I want to generate a file in the above format on the fly containing the location refs saved in the database column/row.
Thanks in advance.
Try exploding your latlong and push the values to an array.
$sql = "SELECT latlong from requests";
$result = $con->query($sql);
$points = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$points[] = explode(',', $row['latlong']);
}
}
$con->close();
echo json_encode(array('points' => $points));
If you are using a newer version of MySQL, try the following:
SELECT JSON_OBJECT(
'points', JSON_ARRAYAGG(
JSON_ARRAY(LAT, LONG)
)
FROM yourTable;
If that doesn't help, share your table structure and your database version.
If you want to try on your own, check out PHP's json_encode()
You can use below code :
$sql = "SELECT latlong from requests";
$result = $con->query($sql);
$points = array();
$i=0;
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$latlong = explode(",", $row['latlong']);
$points['points'][$i] = $latlong;
$i++;
}
}
print_r((json_encode($points)));
I am trying to create a loop that displays each row in a table. I think I need to make an array out of the PK, but I can't figure out how to do that. Here is my code so far:
$conn = dbConnect('read');
$getData = 'SELECT * FROM table';
$allData = $conn->query($getdata);
if (!$allData) {
$error = $conn->error;
} else {
$data = $allData->fetch_assoc();
$rowId = array($data['PK']);
} while ($rowId <= count($rowId)) {
// code to be run for each row
$rowId++;
}
EDIT: Sorry my question is confusing, I'm new to PHP.
Your question is a bit confusing but I think this is what you are trying to do:
$sql = 'SELECT * FROM table';
$query = $conn->query($sql);
while ($row = $query->fetch_assoc()) {
$data[$row['PK']] = $row;
}
That would iterate over each row, creating an array and using the row's value for column PK as an associative array key.
fetch_assoc() (I assume mysqli here now) doesn't fetch all data from a result, but one row after each other. So you don't need to make an array of $row['PK'], but need to loop over the results.
$conn = dbConnect('read');
$getData = 'SELECT * FROM `table`'; // you would need backticks here, if the table really is called "table" (what you shouldn't do...)
$result = $conn->query($getData); // it's not 'allData', it is a result_set. And be carefull about Case! $getData!=$getdata
if (!$result) {
$error = $conn->error;
} else {
$cnt=0;
while($row = $result->fetch_assoc()) {
// code to be run for each row
// you can display $row['PK'] now:
echo $row['PK'];
// or add that value to something else, whatever you need
$cnt = $cnt+$row['PK'];
// or to have a new array with the values of one table-column:
$columnRows[] = $row['PK'];
}
// now you can use the created array
foreach($columnRows as $PK) {
echo $PK;
}
}
I have a polymer(1.0) app i am trying to create (based on stretch-tutorials league table), i cant figure out the routing if use mvc, so i have opted for the one page site, referencing different php files.
I Have a table in MYSql that i trying to incorporate into the table, using a simple echo table script, but this repeats itself hundreds of times. How can i stop this loop ?
$result = mysql_query('select * from results',$connection) or die('cannot show tables');
while($tableName = mysql_fetch_row($result)) {
$sql = ('SELECT `home_team_name`,`away_team_name`,`home_goals_for`, `away_goals_for`, DATE_FORMAT(`fixture_date`, "%e %M %Y"), TIME_FORMAT(`fixture_time`, "%h:%i %p") FROM `results` ORDER BY fixture_date desc LIMIT 20 '.$table) or die('cannot show columns from '.$table);
echo '<h3>',$table,'</h3>';
$result2 = mysql_query($sql);
if(mysql_num_rows($result2)) {
echo '<table cellpadding="4" cellspacing="0" class="table table-striped table-hover table-bordered">';
echo '<tr class="info"><th>Home team</th><th>Away Team</th><th>Score</th><th>Score</th><th>Date<th>Time</th></tr>';
while($row2 = mysql_fetch_row($result2)) {
echo '<tr>';
foreach($row2 as $key=>$value) {
echo '<td>',$value,'</td>';
}
echo '</tr>';
}
echo '</table><br />';
}
}
I have added ' < 50 ' but this returns 50 table header rows only ?
the site is live at http://jay-o.uk/#!/results the css and other data are okay for now, just this pesky loop.
Well.. maybe you need this code:
// Create an array
$items = array();
while ($row = mysql_fetch_array($resulting, MYSQL_ASSOC)) {
/* print new insert */
var_dump('new item');
/* add a new item */
$items[] = array(
'home_team_name' => $row['home_team_name'],
'away_team_name' => $row['away_team_name'],
'home_goals_for' => $row['home_goals_for'],
'away_goals_for' => $row['away_goals_for']
);
}
$json_response = json_encode($items);
print $json_response;
If $json_response are a empty array maybe the problem is that the query don't return any row.
You need to set a "LIMIT" in the first query if you want to avoid a timeout operation, also i think that is posible to call a unique query that return all the info that you need but i don't know because your query is unintelligible.
Your code is wrong, the second query don't use the $table variable that is null value and what is de purpose to putting it after the limit parameter?
$results = mysql_query('SELECT * FROM table_name ORDER BY field_name LIMIT 50');
if(mysql_num_rows($results)) {
print '<table>';
while ($row = mysql_fetch_row($results)) {
print '<tr>';
foreach ($row as $field_name => $field_value) print '<td>'.$field_value.'</td>';
print '</tr>'
}
print '</table>';
}
Sorry, the code is a bit messy, ive been working on this for a while and ifs frustrating, im not sure where i am going wrong, if i remove the $tableName variable i get an empty array, no matter what i do this is the results.
I have tried in json to no avail...
$db = mysql_connect($host,$user,$pass);
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db($db_name,$db);
$resulting = mysql_query("select * from results", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($resulting, MYSQL_ASSOC)) {
$row_array['home_team_name'] = $row['home_team_name'];
$row_array['away_team_name'] = $row['away_team_name'];
$row_array['home_goals_for'] = $row['home_goals_for'];
$row_array['away_goals_for'] = $row['away_goals_for'];
//push the values in the array
array_push($json_response,$row_array);
$json = json_encode($json_response);
//echo $json;
$json_result = print_r((array) json_decode($json,true));
echo $json_result;
}
which leaves this: jay-o.uk/config/config.php
Could this be because i am referring to a view in mySql rather than a table ?
How about a simpler solution, just limit the query from the database to 1:
$results = mysql_query('SELECT * FROM table_name ORDER BY field_name LIMIT 1');
I would want to create an array that will hold records retrieved from a database using a query of SELECT statement.
The records to be retrieved have multiple fields such as lastname, firstname, mi and 20 more fields. What would be the best approach on coding this function?
alright i have followed what prisoner have given below.. the next question is how do i search through this kind of array using queries? for example i want to search for a username..
<?php
// run query
$query = mysql_query("SELECT * FROM table");
// set array
$array = array();
// look through query
while($row = mysql_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
// OR just echo the data:
echo $row['username']; // etc
}
// debug:
print_r($array); // show all array data
echo $array[0]['username']; // print the first rows username
You shouldn't search through that array, but use database capabilities for this
Suppose you're passing username through GET form:
if (isset($_GET['search'])) {
$search = mysql_real_escape_string($_GET['search']);
$sql = "SELECT * FROM users WHERE username = '$search'";
$res = mysql_query($sql) or trigger_error(mysql_error().$sql);
$row = mysql_fetch_assoc($res);
if ($row){
print_r($row); //do whatever you want with found info
}
}
$mysearch="Your Search Name";
$query = mysql_query("SELECT * FROM table");
$c=0;
// set array
$array = array();
// look through query
while($row = mysql_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
$c++;
}
for($i=0;$i=$c;$i++)
{
if($array[i]['username']==$mysearch)
{
// name found
}
}
$memberId =$_SESSION['TWILLO']['Id'];
$QueryServer=mysql_query("select * from smtp_server where memberId='".$memberId."'");
$data = array();
while($ser=mysql_fetch_assoc($QueryServer))
{
$data[$ser['Id']] =array('ServerName','ServerPort','Server_limit','email','password','status');
}
I have an array, $scans. I want to query MySQL with all the values in that array and get my results back in an array. For example, sample data in scans would be:
E1234
E2244
E3654
The MYSQL table PARTS has fields part, size, length, plate, side, type.
I want to end up with $output["E1234"][0] to be the size result for that part, 1 to be length, etc. and I want the array to be sortable by the MYSQL query. (order by SIDE desc, PLATE asc).
Right now, i'm just stepping through the $SCANS array and doing query after query, but I'm not able to then sort all the results properly.
Is this possible? This is what I'm doing now, but obviously since each query returns one row which is then outputted, there's no sortability. I want to be able to perform one query, sort the results within the array, and then output that data after the sort.
foreach ($scans as $currentscan) {
$partselect = substr(mysql_real_escape_string($currentscan), 0, 5);
$query = "SELECT french, length, plate, side, type FROM parts WHERE part = '$partselect' ORDER BY side DESC, plate ASC LIMIT 1";
$result = mysql_query($query);
#echo 'query is '.$query.' <br>';
$error = mysql_error();
$num_rows = mysql_num_rows($result);
if ($num_rows == 0) {
echo 'BAD PART: '.$currentscan.' '.$partselect.' error is '.$error.'<br \>
';
} else {
$row = mysql_fetch_array($result);
print $partselect.' is a '.$row['french'].'/'.$row['length'].' - '.$row['type'].' - '.$row['plate'].'('.$row['side'].')<br \>';
}
};
EDIT: This is the code as it is now following some suggestions here:
$scans = explode("\n",$_POST['scans']);
foreach ($scans as $currentscan) {
if ($currentscan[0] == "E") { //this is a cheap trick to ignore a bad scan inherent in the scanning mechanism
$partselect = substr(mysql_real_escape_string($currentscan), 0, 5);
$tempQuery .= 'part = "'.$partselect.'" OR ';
};
};//end foreach
$tempQuery = substr($tempQuery, 0, -3); //remove last OR (fixed substr to 0,-3 to scrip final OR - stephen)
$tempQuery .= ") ORDER BY side DESC, plate ASC LIMIT 1"; //add on end of query
$query = "SELECT french, length, plate, side, type FROM parts WHERE ".$tempQuery;
$result = mysql_query($query);
echo $result;
while($row = mysql_fetch_array($result)){
print $row['french']." / ".$row['length']; //just doing something pointless to verify data was pulled.
}
result is:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/foo/bar/sort.php on line 35
Line 35 is
while($row = mysql_fetch_array($result)){
FINAL EDIT:
It works.
//DECLARED CONSTANTS//
if (!$_POST) { // Have scans been entered? If not, display the form.
print '
<html>
<body>
Scans:
<form action="index.php" method="post">
<textarea rows="20" cols="6" name="scans" id="scans">
</textarea>
<br />
<input type="submit" value="Submit" />
</body>
</html>
';
} else { //Scans have been entered. Start scan processing logic
//==openDB==//
mysql_connect(SQLSERVER, SQLUSER, SQLPASSWORD) or die("Can not connect to DB server.");
mysql_select_db(DATABASE) or die("Can not connect to Database.");
//==openDB==//
$scans = explode("\n",$_POST['scans']); // Explode posted scans into scans array
foreach ($scans as $currentscan) { // step through each scan
if ($currentscan[0] == "E") { //Cheap check for real part numbers.
$partselect = substr(mysql_real_escape_string($currentscan), 0, 5); // Strip off the extraneous data from the scan
$count{$partselect}++; //Count instances of particular parts. ideally this would be in an array in the form of $count[$partnumber] so I can easily display that data at the end. each part needs to be displayed every time it's scanned.
$tempQuery .= 'part = "'.$partselect.'" OR '; //Starts building query
};
};//end foreach
$tempQuery = substr($tempQuery, 0, -3); //remove last OR
$tempQuery .= ") ORDER BY side DESC, plate ASC"; //add on end of query
$query = "SELECT part, french, length, plate, side, type FROM parts WHERE (".$tempQuery; //Form beginning of query
$result = mysql_query($query);// execute query
while($row = mysql_fetch_array($result)){ // step through results
for ($i = 0; $i < $count{$row['part']}; $i++) { //if a part was scanned $count{$row['part']} times, display it that many times
print $row['part']." ".$row['french']." / ".$row['length']." ".$row['plate']."(".$row['side'].")<br>"; //data parsing goes here. this will be expanded.
};// close for loop
};//close while loop
};//close else
?>
<?php
// Make a MySQL Connection
$query = "SELECT * FROM example";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
echo $row['name']. " - ". $row['age'];
?>
Courtesy of http://www.tizag.com/mysqlTutorial/mysqlfetcharray.php
You can also if you expect multiple results do:
<?php
// Make a MySQL Connection
$query = "SELECT * FROM example";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['name']. " - ". $row['age'];
}
?>
Added code for your comment:
foreach ($scans as $currentscan) {
$partselect = substr(mysql_real_escape_string($currentscan), 0, 5);
$tempQuery .= "(part = ".$partselect." OR";
}//end foreach
$tempQuery = substr($tempQuery,-2); //remove last OR
$tempQuery .= ") ORDER BY side DESC, plate ASC LIMIT 1"; //add on end of query
$query = "SELECT french, length, plate, side, type FROM parts WHERE ".$tempQuery;
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
//do something with row in result set...
}
Whay you should do is to construct a WHERE clause in PHP, which lets you select all rows that have any of the part numbers. Something like this:
$whereExpr = array();
for ($i = 0; $i < count($scans); $i++) {
$whereExpr[] = "part = \"{$scans[$i]}\"";
}
$whereExpr = implode(" OR ", $whereExpr);
$query = "SELECT * FROM `parts` WHERE $whereExpr ORDER BY <whatev>";
$result = array();
while ($row = mysql_fetch_array) {
$result[ $row['part'] ] = $row;
}
MySQL Fetch Array Function
After looking at your update/edit you could use the IN clause
// Represents your $scans array
$arr = array('Hello','World!','Beautiful','Day!');
foreach ($arr as $currentscan) {
$partselect[] = substr(mysql_real_escape_string($currentscan), 0, 5);
}
$inExpr = implode("','",$partselect);
$query = "SELECT french, length, plate, side, type FROM parts WHERE part IN('$inExpr') ORDER BY side DESC";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
print $partselect.' is a '.$row['french'].'/'.$row['length'].' - '.$row['type'].' - '.$row['plate'].'('.$row['side'].')<br \>';
}