I am querying MySQL to perform an operation and return an array. To do this I am using the following code:
$return_array = array(
"title" => "nearby media",
"nearby_media_list" => array()
);
$my_query = "select * from `Media`";
$result = $conn->query($my_query);
while($row = $result->fetch_assoc()) {
$mediaLat = $row["lat"];
$mediaLon = $row["lon"];
$calculated_distance = distance( $userLat, $userLon, $mediaLat, $mediaLon, "M");
if( $calculated_distance <= $distance_limit ) {
// Build array
$return_array["nearby_media_list"][] = array(
'uid' => $row['uid']
);
}
}
echo json_encode($return_array);
$conn->close();
?>
and my output looks like this:
{"title":"nearby media","nearby_media_list":[{"uid":"-Kn1f0jo_36qnQBCqjCq"}]}
Since the array only contains one type of data I don't need to store a key and don't need JSON. What I want is a simple array of the values separated by a token so I can take it apart more easily. desired outcome is something like
[value1##$%value2##$%]
Can anyone instruct me how to do this? I haven't had any luck
Related
I am not sure how to write the following code.
$rowID = $_POST['rowID'];
if ($listing = $Listings->getData($rowID)) {
$jsonArray = array(
'listing_number' => $listing['listing_number'],
);
exit(json_encode($jsonArray));
}
When I do it like that, the response is Undefined Index: listing_number.
However, If I write it like this,
$rowID = $_POST['rowID'];
if ($listing = $Listings->getData($rowID)) {
$jsonArray = array(
'listing_number' => $listing[0],
);
exit(json_encode($jsonArray));
}
The response is
{"listing_number":{"id":"24","client_id":"1","address":"","address_2":"","city":"","state":"","zip":"","price":"","listing_number":"asdasdasdasd","remarks":"","link":"","status":"","bd":"","ba":"","lot_sz":"","sq_ft":"","yr":"","type":"","thumb":""}}
Which lets me know my SQL is and PHP is correct, I just don't know how to access $listing['listing_number] correctly.
Any help would be appreciated.
as GrumpCrouton said in the comment, your query is returning an array of results. So if you want to access a value in the first result, you first need to access this result using it's index : $listing[0]->listing_number.
$rowID = $_POST['rowID'];
if ($listing = $Listings->getData($rowID)) {
$jsonArray = array(
'listing_number' => $listing[0]->listing_number,
);
exit(json_encode($jsonArray));
}
P.S. You can convert object to array using a simple cast ( $result = (array) $result ), but it is not a must in your case. Casting your object to array will allow you to acces it's data using result['key'] rather than result->key.
I did a very short and simple PHP .
The output is an array in json. However it doesn't work .
The array-items are always null.
I guess it must have something to do with mistakenly calling the db table columns
('id' => $row->MASTER_ID).
Whereas 'MASTER_ID' is the name of the column in my db.
I'd be very glad if someone could point me in the right direction.
My script looks as follows:
<?php
$db = new PDO('mysql:host=xxx;dbname=xx;charset=utf8mb4', 'xx', 'xxx');
$month = date('Y-m');
$monthwild = "$month%";
$sql = ("SELECT * FROM MASTER WHERE START_DATE LIKE '". $monthwild ."'");
$out = array();
foreach($db->query($sql) as $row) {
$out[] = array(
'id' => $row->MASTER_ID,
'title' => $row->MASTER_TITLE,
'start' => strtotime($row->MASTER_START),
'end' => strtotime($row->MASTER_END)
);
}
echo json_encode(array('success' => 1, 'result' => $out));
exit;
?>
I'm new to PDO (used to do things like this with mysql) and
I didn't get it yet and didn't find the right resources
PDO::query “executes an SQL statement, returning a result set as a PDOStatement object,” not a row.
You have to put the result in a variable and then retrieve rows from this variable:
$result = $db->query( $sql );
while( $row = $result->fetchObject() )
{
(...)
}
As alternative, you can set a default fetch mode and then retrieve single rows with:
$result = $db->query( $sql );
$result->setFetchMode( PDO::FETCH_OBJ );
while( $row = $result->fetch() )
{
(...)
}
Edit:
Actually, also direct foreach works, but without a specific fetch mode it returns enumerated and associative result:
foreach( $db->query( $sql ) as $row )
{
$id = $row['MASTER_ID'];
// $id = $row[0]; // ← Alternative
}
To use objects with direct foreach you have to use this syntax:
foreach( $db->query( $sql, PDO::FETCH_OBJ ) as $row )
{
$id = $row->MASTER_ID;
}
Read more about PDO::query
Read more about PDOStatement
I'd say that your definition of $monthwild is wrong.
The right notation for that what you want to write is:
$monthwild = $month."%";
In your script is the content of $monthwild the string "$month%"
Now is the content of $monthwild the string %
I hope you can understand that.
It is not easily described.
$thearray = array
(
//(0)ID, (1)NAME, (2)LOCATION, (3)PHONE
array("0","Name 1","Nowhere 11","0004444"),
array("1","Name 2","Everywhere 11","0005555"),
array("2","Name 3","ThisPlace 11","0002222"),
array("3","Name 4","NoPlace 11","0003333"),
array("4","Name 5","ThatPlace 11","0001111")
);
This is how I used to store my information
I would then run through them to find what I needed
and display them using for example
echo $thearray[$i][4]
I want to do the same thing except store that information in Mysql
This is how far I've gotten but I keep getting strange errors and I cant output from the array
This is how far I've gotten
$result = $db->query("SELECT * FROM table");
$thearray = array();
while($thearray = $result->fetch_assoc()){
$thearray[] = $thearray;
}
For some reason this isn't working for me, its like it isnt in a 2d array like I have above :S I can't simply echo it like I did before.
Well first of all
while($thearray = $result->fetch_assoc()){
$thearray[] = $thearray;
}
Will keep overwriting the array and get very confused
try
while($row = $result->fetch_assoc()){
$thearray[] = $row;
}
The array returned from your query is no longer a simple array, it is a associative array
i.e. it will look something like this:
$new_array = array
(
//(0)ID, (1)NAME, (2)LOCATION, (3)PHONE
array('ID' => "0", 'NAME' => "Name 1", 'LOCATION' => "Nowhere 11", 'PHONE' => "0004444"),
array('ID' => "1", 'NAME' => "Name 2", 'LOCATION' => "Nowhere 22", 'PHONE' => "0005555"),
etc
);
So now when you want to use it you will have to use this sort of construct
$name = $new_array[$i]['NAME']
$location = $new_array[$i]['LOCATION']
etc
or
<?php echo $new_array[$i]['NAME']; ?>
<?php echo $new_array[$i]['LOCATION'] ?>
etc
I'm having major headaches trying to create a multidimensional array from two separate MySQL selects.... I've been searching here and Google all day and have to finally admit defeat and ask for some help (I'm a newbie as well which doesn't help!!!).
I have two tables, one which contains a single row result per id and another which can contain several rows for an id. What I'm trying to do is combine the two into a multidimensional array.
My code (poor as it may be) looks like this:
require 'php/phpConnection.php';
$sqlString1 = mysql_query("SELECT id FROM supportstaff_section1_a");
$firstArray = array();
$secondArray = array();
while ($r = mysql_fetch_assoc($sqlString1)) {
$applicantID = $r['id'];
$sqlString2 = mysql_query("SELECT educationalname FROM supportstaff_section5 WHERE id = '$applicantID'");
while ($x = mysql_fetch_assoc($sqlString2)) {
$secondArray[] = $x;
}
$firstArray[] = $r + $secondArray;
$secondArray = array();
}
print json_encode($firstArray);
mysql_close($con);
The result is this:
[{"id":"8m8wwy","0":{"educationalname":"GCSE - English"},"1":{"educationalname":"GCSE - Maths"}},{"id":"wiL7Bn"},{"id":"zAw6M1"}]
But I think it needs to look something like this:
[{"id":"8m8wwy","Array2":"[{"educationalname":"GCSE - English"},{"educationalname":"GCSE - Maths"}]"},{"id":"wiL7Bn"},{"id":"zAw6M1"}]
Anyway, how can I insert my second SQL Select into my first SQL Select for each ID.
Thanks for any advice/help.
EDIT
Taken from W3Schools.com:
Array
(
[Griffin] => Array
(
[0] => Peter
[1] => Lois
[2] => Megan
)
[Quagmire] => Array
(
[0] => Glenn
)
[Brown] => Array
(
[0] => Cleveland
[1] => Loretta
[2] => Junior
)
)
I'm trying to make it work like the above.
You need to get a little creative here. Something like the following would work as a join AND with multi-dimensional data:
<?php
require 'php/phpConnection.php';
// ======================================================================
// Create a join query (way faster than several separate ones!)
$sqlquery =
"SELECT SSSA.id, SSS5.educationalname" .
" FROM supportstaff_section1_a SSSA" .
" LEFT OUTER JOIN supportstaff_section5 SSS5 ON SSS5.id = SSSA.ID";
// ======================================================================
// Run the query and get our results
$resultarray = array();
if ($resource = mysql_query($sqlquery)) {
while ($curarray = mysql_fetch_assoc($resource)) {
// Create an array, if it doesn't exist
if (!isset($resultarray[$curarray["id"]]))
$resultarray[$curarray["id"]] = array();
// Add to the array, if not null
$curstring = (string) $curarray["educationalname"];
if ($curstring != "")
$resultarray[$curarray["id"]][] = $curstring;
}
mysql_free_result($resource);
}
// ======================================================================
// Convert from a keyed array to a standard indexed array (0, 1, 2, etc.)
$finalarray = array();
foreach ($resultarray as $id => & $data) {
// Start with just ID
$newarray = array(
"id" => $id
);
// Get the data, if we have any
if (count($data))
$newarray["educationalnames"] = & $data;
// Add to our final array and clear the newarray
$finalarray[] = & $newarray;
unset($newarray);
}
// ======================================================================
// Get the JSON of our result
$jsonresult = json_encode($finalarray);
// ======================================================================
// Echo it to test
echo $jsonresult;
// ======================================================================
// Close the database
mysql_close($con);
?>
And the resulting $jsondata would look like this (but not so unravelled of course):
[
{
"id": "8m8wwy",
"educationalnames": ["GCSE - English", "GCSE - Maths"]
},
{
"id": "wiL7Bn"
},
{
"id": "zAw6M1"
}
]
If you have an ID from the first Array, you can check for keys / values with this ID in the second Array.
If you want to get the key you should use
array_key_exists($string)
And if you want to get the value you should use
in_array($string)
You can use a foreach loop to execute this functions!
I got a database with 2 fields: amount and name.
I want to get all the data from the database (40 rows) and create an associated array out of it like this:
$arr = array("amount" => "12", "name" => "John");
How is this done dynamically in PHP? I am stuck.
If you're using the mysql_* function, you can do the following to get one row at a time:
$res = mysql_query("SELECT amount, name FROM mytable");
while ($row = mysql_fetch_assoc($res)) {
var_export($row); // outputs array ( 'amount' => '12', 'name' => 'John', )
}
To get all rows in a single array:
$customers = array();
$res = mysql_query("SELECT amount, name FROM customers");
while ($row = mysql_fetch_assoc($res)) {
$customers[] = $row;
}
Well, if you run your query, e.g.
$result = mysql_query('SELECT amount, name FROM table');
you can loop over the result like that:
$values = array();
while(($row = mysql_fetch_assoc($result))) {
$values[] = $row;//$row will be like array("amount" => "12", "name" => "John")
}
and you will have an array of arrays.
Check out mysql_fetch_assoc if you want to fetch database rows as an associative array (the documentation comes with a good example, too).
$data = $pdo->query('SELECT amount, name FROM ...')->fetchAll(PDO::FETCH_ASSOC);
That's it in PDO. And if you're not using PDO, well, that's your problem then...