I'm trying to create JSON from a comma delimited array - php

I need to output like this.
{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"},{"name":"","lat":"28.6192875","lng":"77.0261699"},{"name":"","lat":"28.6192887","lng":"77.02616139999999"},{"name":"","lat":"28.6192887","lng":"77.02616139999999"},{"name":"","lat":"28.6192887","lng":"77.02616139999999"},{"name":"","lat":"28.6192887","lng":"77.02616139999999"},{"name":"","lat":"28.6236227","lng":"77.0317984"},{"name":"","lat":"28.6244627","lng":"77.0322383"},{"name":"","lat":"28.6245415","lng":"77.0331425"},{"name":"","lat":"28.6245418","lng":"77.0331053"},{"name":"","lat":"28.6246156","lng":"77.0322415"},{"name":"","lat":"28.6242647","lng":"77.0316073"}
PHP Script
$sql="SELECT name,lat,lng FROM `in_point_creation` WHERE 1";
$result=mysql_query($sql);
while ($row=mysql_fetch_assoc($result)) {
$json_array = json_encode($row);
print_r($json_array);
}
Current Output
{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.619284999999998","lng":"77.02616189999999"}{"name":"","lat":"28.6192875","lng":"77.0261699"}{"name":"","lat":"28.6192887","lng":"77.02616139999999"}{"name":"","lat":"28.6192887","lng":"77.02616139999999"}{"name":"","lat":"28.6192887","lng":"77.02616139999999"}{"name":"","lat":"28.6192887","lng":"77.02616139999999"}{"name":"","lat":"28.6236227","lng":"77.0317984"}{"name":"","lat":"28.6244627","lng":"77.0322383"}{"name":"","lat":"28.6245415","lng":"77.0331425"}{"name":"","lat":"28.6245418","lng":"77.0331053"}{"name":"","lat":"28.6246156","lng":"77.0322415"}{"name":"","lat":"28.6242647","lng":"77.0316073"}
Thanks

You need to create the entire object you need before calling JSON encode:
$sql="SELECT name,lat,lng FROM `in_point_creation` WHERE 1";
$result=mysql_query($sql); //You need to switch to mysqli , mysql is no longer a valid choice
$json_array = [];
while ($row=mysql_fetch_assoc($result)) {
$json_array[] = $row;
}
$jsonString = json_encode($json_array);
print_r($jsonString);

There are multiple ways to solve your "problem".
But first, don't use mysql_* functions => deprecated in PHP 5.5
Use mysqli_* functions instead.
If you have just a few hundred rows, you maybe could build an array with all items, like Paul Crovella and apokryfos said.
But if there are a multiple thousands of rows, you should prefer to write them out as quick as possible and don't save them to your RAM. Because PHP has limited space in RAM.
Maybe you could try it without loop:
$conn = mysqli_connect('host','username','password','database')
$query = 'SELECT name,lat,lng FROM `in_point_creation` WHERE 1';
$result = $conn->query($query);
$data = mysqli_fetch_all($result,MYSQLI_ASSOC);
echo json_encode($data);

Related

$result only one row then convert into session

i am trying to query one single row from a table 'account'. I kind mess up with the MYSQLI so i need some advice. How can i do that?
$link = mysqli_connect("localhost","root","","database") or die("Error " . mysqli_error($link));
$query = "SELECT * FROM account WHERE username='".$user."' AND password='".$passcode."' LIMIT 1";
$result = $link->query($query) or die("Error " . mysqli_error($link));
$numrow = $result->num_rows;
$res = $result->fetch_assoc();
After the query i want to copy the data to a session, i am doing like that:
session_start();
$tableau = array($res['cod_acc'],$res['username'],$res['password']);
$_SESSION['tableau'] = $tableau;
And after these, how can i print the data?
$tableau = $_SESSION['tableau'];
echo "$tableau['username']";
From your question:
how can i print the data?
First of all you need to add error_reporting() on in your code:
error_reporting(E_ALL);
You are saving values in an array for $_SESSION:
$tableau = array($res['cod_acc'],$res['username'],$res['password']);
$_SESSION['tableau'] = $tableau;
If you look your session array it's not an associative array.
So you can not get the result like:
$tableau = $_SESSION['tableau'];
echo $tableau['username'];
Solution:
You can get username from session array as:
echo $tableau[1]; // username on second index.
Solution 2:
If you want associative index than you need to use associative array as:
$tableau = array(
"cod_acc"=>$res['cod_acc'],
"username"=>$res['username']);
$_SESSION['tableau'] = $tableau;
Now you can use as you need. Note that I am removing password field from session I think its not need.
Side note:
I don't know why are mixing Procedural and Objected Oriented style together.
The problem was in some other line code, sorry for the post. But thanks guys.

What are ways to run a MySQL query in PHP and output the result to an array in less space?

I'm getting really tired of writing:
$rows = array();
$result = $db->query("SELECT * FROM `table` WHERE `field`='".$information."'");
while($row = $result){
$rows[] = $row;
}
I tried a function, but it was kinda of messy feeling changing the input to field inputs. I thought maybe this or something similar would help:
$rows = array();
while($row = ($db->query("SELECT * FROM `table` WHERE `field`='".$information."'"))->fetch_assoc()){
$rows[] = $row;
}
but I get unexpected T_OBJECT_OPERATOR. I'm still on the line about using a function. Maybe there's a more efficient way of writing one. This is how I tried writing a function:
$array = SELECT ($db,$toSelect,$table,$where);
It still seems cumbersome, however. I would like something like $array = $db->("MYSQL");
The simplest solution is to write a function, which expects a database handle and a string query parameter, and returns all the rows.
$rows = fetch_all($db, "SELECT ...");
A bit more advanced is to write your own database class which wraps the database handle and adds such functionality.
$rows = $mydb->fetch_all("SELECT ...");
If you don't want to reinvent the wheel, simply use an existing ORM / PHP database library which does all this (and more) for you.
$db
->select('*')
->from('table')
->where('field', $information);
Note: http://www.php.net/manual/en/security.database.sql-injection.php - the third solution automatically solves this problem.

Put mysql results in one php array, like this?

To get an array like this array("123","456","789"); I use the code:
$Regids = mysql_query("SELECT regid FROM $tabel WHERE active = '1'");
while($row = mysql_fetch_array($Regids))
{
$result_array[] = "\"".$row['regid']."\"";
}
$regIDs = implode(',', $result_array);
$registrationIDs = array($regIDs); // array("123","456","789");
but I would expect PHP/mySQL has a simpler/faster solution for this?
I doubt that your code produces the result you want.
// assuming the this query produces 123,456,789
$Regids = mysql_query("SELECT regid FROM $tabel WHERE active = '1'");
// $row contains: array("123")
while($row = mysql_fetch_array($Regids))
{
$result_array[] = "\"".$row['regid']."\"";
}
// $result_array now contains: array("\"123\"", "\"456\"", "\"798\"");
$regIDs = implode(',', $result_array);
// $regIDS now contains a single string: "\"123\",\"456\",\"798\"";
$registrationIDs = array($regIDs);
// registrationIDs now is an array containing a single string: array("\"123\",\"456\",\"798\"");
If you really need an array that looks like this: array("123","456","789"); it is much simpler.
$Regids = mysql_query("SELECT regid FROM $tabel WHERE active = '1'");
while($row = mysql_fetch_array($Regids))
$registrationIDs[] = $row['regid'];
and that's all.
If your mysql result contains the number as an integer instead of an string you can convert it like this:
$Regids = mysql_query("SELECT regid FROM $tabel WHERE active = '1'");
while($row = mysql_fetch_array($Regids))
$registrationIDs[] = strval($row['regid']);
Also, keep in mind that the mysql_* functions are becoming deprecated. Don't start new code with it and make plans to port your existing code to mysqli_* or PDO.
You can use PDO implementation. At first sight, it may be more difficult to understand, but once you get used to it, it reveals to be really powerful and handy (IMHO! One year ago i switched to it and i love it)!
For your example, the PDO implementation would be like this:
/*CONNECT TO DB, FIRST. $dbh contains a handler to the current DB connection*/
$stmt = $dbh->prepare("SELECT regid FROM table WHERE active = '1'");
$stmt->execute();
$Regids = $stmt->fetchAll(PDO::FETCH_COLUMN,0);
There are many formatting options you can specify, like
PDO::FETCH_COLUMN
PDO::FETCH_ASSOC
and more...These options will allow you to get the array formatted as you prefer. As you can see i got the result in just 3 simple rows.
EDIT
Note: you are not escaping PHP variables before inserting them in your Query, and your code may suffer SQL INJECTION. Be careful!! Here is a simple guide to prevent it.
(In my code, just to be clear, i avoided the problem by just putting the table name instead of $table, just to show simply how to get the result you wanted.)
try this .. use Group concat in query ...
$Regids = mysql_fetch_array(mysql_query("SELECT GROUP_CONCAT(regid) as regids FROM $tabel WHERE active = '1'"));
echo $Regids[0]['regids']; // 123,456,789
for getting result "123","456","789" try this
$Regids = mysql_fetch_array(mysql_query("SELECT GROUP_CONCAT('\"',CONCAT(regid),'\"') as regids FROM $tabel WHERE active = '1'"));
echo $Regids[0]['regids']; // "123","456","789"

php: iterate recordset - easier way?

i've just changed from ASP to php and i'm a bit confused about the way php is handling recordsets.
i'd like to know if there's an easier way to iterate a recordset by creating a php class.
here's the ASP syntax to show what i mean:
sq = "select * from myData"
set rs = db.execute(sq)
do while not rs.eof
response.write rs("name") // output data (response.write = echo)
rs.movenext
loop
any ideas?
thanks
You'd pretty much do the same thing...
$sql = "select * from myData";
$result = mysql_query($sql) or die(mysql_error()); //executes query
while($row = mysql_fetch_array($result)){ //will automatically return false when out of records
echo $row['name'];
}
You're probably looking for a function contains word fetch in it's name.
E.g. mysql_fetch_assoc() or $pdo->fetchAll().
Most of database API functions in PHP returns some sort of pointer variable called "resource", which can be passed to the fetch-family function, like this:
$res = mysql_query();
while($row = mysql_fetch_assoc($res)){
echo $row['name'];
}
However, some of them (like PDO's fetchAll method) returns but regular PHP array, which you can iterate using as regular foreach operator.

Get the full result

Is there a PHP function to get the full result with a mysql query in a multidimensional array?
SELECT * FROM table
Usually I would make something like this:
$query = mysql_query = ("SELECT * FROM table");
while ($result = mysql_fetch_array($query){
echo $result[0];
}
You can create your own function like mysql_fetch_array_complete() and imagine that it's builtin ;-)
If you are using PDO to access mysql there is.
http://www.php.net/manual/en/pdostatement.fetchall.php
Otherwise you need to do it yourself.
$query = mysql_query = ("SELECT * FROM table");
$all_results = array();
while ($result = mysql_fetch_array($query){
$all_results[] = $result;
}
print_r($all_results);
The $all_results variable will be a multi-dimensional array with all the records.
You could always write your own function to do this, but it would often lead to an unnecessary iteration through the result set (once when you call your function, another time when you actually USE the resulting array).
Since you're in php5, you could create a database result class that implements the Iterator interface. Then, you can use your class in foreach () loops and have much of the ease-of-use that you get from an array.
As of PHP 5.3 there is a built in function:
fetch_all

Categories