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.
Related
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
I need to fetch data from my db. I've done it but when I say fetch array [1], the output is the all second letters in all rows. Here is the code:
include "baglan2.php";
$query = $db->query("SELECT * FROM diziler", PDO::FETCH_ASSOC);
if ( $query->rowCount() ){
foreach( $query as $row ){
echo ($row['link']. "<br />");
}
I tried it with msqli but saw the same result; here is the mysqli code:
$query = mysqli_query($baglanti, "SELECT * FROM diziler");
if ( mysqli_affected_rows($baglanti) ){
while ( $row = mysqli_fetch_assoc($query) ){
print $row['link'][1]."<br />";
}
}
For instance all my data are links. When I run print $row['link'][1], it gives "t" letter from "http:" in all rows. I need to fetch my data by row not column. I have tried every method possible. However I couldn't find any method that worked.
for instance I want to make this codes output "http://**.com" in each element.
I am giving solution based on second attempt:-
$query = mysqli_query($baglanti, "SELECT link FROM diziler");
$link_array = array();
if ( $query){
while ( $row = mysqli_fetch_assoc($query) ){
$link_array[] = $row['link'];
}
}
echo "<pre/>";print_r($link_array); // it have all the links
Reason:- https://eval.in/649070
It's specification is given here:- https://stackoverflow.com/a/17193651/4248328
That is:- $string[int] is syntactic sugar for substr($string, int, 1)
I'm getting posts details from 'postsTable' with php and encoding it in JSON Like this way
$result_json = mysqli_fetch_all ($result, MYSQLI_ASSOC);
echo json_encode($result_json);
each post has a unique ID
Then I have another table called 'postsLikes' I want to see how many Likes the post have using mysqli_num_rows()
But my question is how can I add the data it returns to each object in Encoded JSON ?
$query_checkup = "SELECT * FROM postsTable WHERE Post_AgeFrom < $age AND $age < Post_AgeTo AND Post_Reviewed = 1";
$result=mysqli_query($con, $query_checkup);
$result_json = mysqli_fetch_all ($result, MYSQLI_ASSOC);
echo "{\"result\":";
echo json_encode($result_json);
echo "}";
You should append extra data to your array before encoding to json.
foreach ($result_json as $key => $result) {
$result_json[$key]['likes'] = getLikes();
}
echo json_encode($result_json);
And you need to implement getLikes function as you wish or can do the operation inside foreach loop.
There a note that you need to pay attention: you need to query for each product to get likes. It is better to join tables and format your array as your need in a loop.
Maybe you can create a new array and use the foreach construct to add the previous values and the new values.
$new_array = array();
foreach($result_json as $result){
$new_array[] = array(
'id' => $result['id'],
'likes' => getlikes($result['id'])
);
}
function getlikes($id){
// your code to get likes number with mysqli_num_rows()
}
echo json_encode($new_array);
You should join the 'postsLikes' table in your original query to pull in all the data you need with a single trip to the database.
Something like this:
(Guessing on how your tables are setup)
$query = "
SELECT
P.* ,
L.Likes
FROM postsTable P
LEFT JOIN postsLikes L ON L.Post_id = P.Post_Id
WHERE
P.Post_AgeFrom < :age AND
:age < P.Post_AgeTo AND
P.Post_Reviewed = 1 ";
$params = array( "age" => $age );
$pdo = new PDO('mysql:dbname=testdb;host=127.0.0.1', $user, password);
$stmt = $pdo->prepare( $query );
$stmt->execute( $params );
$results = $stmt->fetchAll( PDO::FETCH_ASSOC );
$response = array( "results" => $results );
echo json_encode( $response );
Other bits of advice:
1) Use bound parameters to prevent SQL injection.
2) Don't manually create any of the JSON in your response, create the response array first and let json_encode do the rest of the work
I've been working on a OOP method that is supposed to return the rows of a MySQL query. I have to have the data array in the format:
$rows = array('row'=> rownum, 'fld1'=> fldval .... 'fldn' => fldval);
What I have encountered are the two problems of either:
returns
$rows = array('0'=>fldval, 'fld1'=> fldval .... 'n'=> fldval, 'fldn' => fldval);
or single row of
$rows = array('fld1'=> fldval .... 'fldn' => fldval);
Little frustrated as every PHP mysql function I have tried has some sort to goofy crap flaw and will not do a straight out process.
I assume there is a good example somewhere, that can get me past the crap limitations, but haven't found anything useful yet!
I've tried all of the following:
$row = mysql_result($db_res,$n);
$row = mysql_fetch_array($db_res);
$row = mysql_fetch_assoc($db_res);
$row = mysql_fetch_object($db_res);
$row = mysql_fetch_row($db_res);
None have worked successfully! For getting out the bogus "numeric" array entries. I wrote:
foreach ($row as $k => $v)
if (is_numeric($k)) { continue; }
$result[$k] = $v;
} // end foreach $row
$row = array_push($row, 'row'=>$rownum, $result);
Hoping someone has a link.
$list = array();
$query = "SELECT value FROM table";
$resource = mysql_query($query);
while($row = mysql_fetch_assoc($resource))
{
$list['fld' . (1 + count($list))] = $row['value'];
}
$list = array('row' => count($list)) + $list;
if table have 3 row, the code above is going to give you a array like:
array(
'row' => 3,
'fld1' => 12,
'fld2' => 34,
'fld3' => 56
);
I have an array which have this structure:
$queues[n] Array (
[id] => integer
[idClient] => integer
[name] => string
[people] => integer )
Which is populated with:
$query = "SELECT clients.idClient AS 'idClient', queues.idQueue AS 'idQueue', queues.name AS 'name' FROM clients, queues WHERE clients.idClient = queues.client";
$queues = null;
$result = mysql_query($query);
if ($result){
while ($queue = mysql_fetch_assoc($result)){
$queues[] = array ("idClient" => $queue['idClient'], "id" => $queue['idQueue'], "name" => $queue['name'], "people" => 0);
}
}
Each 'n' value match a queue from Database and people, by default is set to 0.
After populating the array I query the database again with each queue to other table to obtain the number of people in queue with a query like this:
SELECT COUNT(*) FROM peoplequeued WHERE queue ='".$queue['name']."'
And then:
$result = mysql_query($query);
if ($result){
$num_people = mysql_fetch_row($result);
$queue['people'] = $num_people[0];
}
And something strange happens here. If I echo the $queue['people'] in the foreach, it shows fine the value it got but if I preview the full array before returning it, it's back to 0.
What could be happening?
My guess is that you're looping through $queues with foreach loop like this:
foreach ( $queues as $queue ) {
$result = mysql_query($query);
if ($result){
$num_people = mysql_fetch_row($result);
$queue['people'] = $num_people[0];
}
}
If so, there's no "link" between $queue and $queues[$n], i.e., by modifying $queue, you do NOT modify $queues.
If this is the case, you should either use $queue as reference variable, or modify $queues[$n] with $n being an index.
foreach ( $queues as &$queue ) { // add & so $queue is a reference to an element in $queues
$result = mysql_query($query);
if ($result){
$num_people = mysql_fetch_row($result);
$queue['people'] = $num_people[0];
}
}
unset($queue); // drop the reference, otherwise you might have unexpected results after modifying $queue outside the loop
... or ...
foreach ( $queues as $n => $queue ) { // store index of "current" element in $n
$result = mysql_query($query);
if ($result){
$num_people = mysql_fetch_row($result);
$queues[$n]['people'] = $num_people[0]; // change $queue to $queues[$n]
}
}
Alternatively, I would advise you to think about getting all data in a single statement. It looks like something like this might work for you:
select
baseTable.id,
baseTable.idClient,
baseTable.name,
peopleCount.count as people
from
baseTable
left join (
select
count(*) as count,
queue
from
peoplequeued
group by
queue
) as peopleCount on peopleCount.queue = baseTable.name
It sounds like you're probably using a foreach loop to cycle through your $queues array, like this:
foreach($queues as $queue) {
}
Each $queue variable generated is a copy, and changes to it aren't saved to the $queues variable. To save changes as you're intending, you need to do something like:
foreach($queues as $k => $queue) {
$queue['people'] = 10;
$queues[$k] = $queue;
// or, more efficiently...
$queues[$k]['people'] = 10;
}
In PHP5 you can also reference. See http://uk.php.net/manual/en/control-structures.foreach.php