I am trying to load a list of IDs into a PHP array which I can loop through. The SQL query I am using returns 283 rows when I run it in PHPMyAdmin. However, when I run the following PHP script, it only returns a single row (the first row). How can I modify my code to include all the rows from the resulting SQL query in my PHP array?
Code:
//Get active listing IDs
$active = "SELECT L_ListingID FROM `markers`";
$active = mysql_query($active) or die(mysql_error());
if(is_resource($active) and mysql_num_rows($active)>0){
$row = mysql_fetch_array($active);
print_r($row);
};
Thanks,
Using mysql_fetch_array will return only the first row and then advance the internal counter. You need to implement it as part of a loop like the following to get what you want.
while($row = mysql_fetch_array($active)) {
// Your code here
}
Keep in mind that mysql_ functions are now also deprecated and slated to be removed in future version of php. Use mysqli_ functions or PDO.
In PDO it's rather straight forward:
$rows = $conn->query($active)->fetchAll();
See PDO::queryDocs and PDOStatement::fetchAllDocs.
With mysqli you would use mysqli_result::fetch_all and with PDO there's PDOStatement::fetchAll to fetch all rows into an array.
Code for mysqli
$sql = "SELECT L_ListingID FROM `markers`";
$result = $mysqli->query($sql);
if ($result !== false) {
$rows = $result->fetch_all();
}
with PDO it's nearly the same
$sql = "SELECT L_ListingID FROM `markers`";
$result = $pdo->query($sql);
if ($result !== false) {
$rows = $result->fetchAll();
}
Related
Following is a typical OOP way to Connect and Retrive data from MySQL database using MySQLi and PHP.
Now I am a little bit confused on using the pure PHP arrays at this example:
Can some one please let me know if the $result is array or not? I mean in
$result = $mysqli_coonect->query($sql);
if so how come we didn't use the array() function or [] to create it?!
same thing happening with $row at:
$row = $result->fetch_assoc()
I am asking this because in order to load $row; to $results[] at $results[] = $row; we declared the $results as an array explicitly before the while() how come we are not doing this for other or vice versa?!
<?php
$mysqli_coonect = new mysqli($host_name, $user_name, $pass_word, $database_name, $port);
$sql = "SELECT * FROM books WHERE id <= 10";
$result = $mysqli_coonect->query($sql);
if (($result) && ($result->num_rows > 0))
{
$results = array();
while ($row = $result->fetch_assoc())
{
$results[] = $row;
}
$result->free();
}
$mysqli_coonect->close();
Always refer to the PHP documentation. It's great and you can easily find what you want.
http://php.net/manual/en/mysqli.query.php states that a query will return mixed in this case meaning either false if the query failed or mysqli_result object of the query was successful.
Getting down to business
$result = $mysqli->query($query) returns a mysqli_result object. This means that $result is now an object.
We then call the method fetch_assoc from our newly created $result (mysqli_result) object and store the results of the method in the variable $row (which if the method is successful will be an array). If you look at what fetch_assoc returns (http://php.net/manual/en/mysqli-result.fetch-assoc.php) you see that it returns an array.
We loop through our newly created $row array.
I am running a Mysql query in a php file and parsing it as json as follow:
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['artist'] = $row['artist'];
$row_array['song'] = $row['song'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
There are thousands of entries; Is there any way I can filter the JSON results based on a value?
something like: mylink.php/artist1 or mylink.php?artist=1
I would really appreciate any sort of ideas.
thanks
You can do it so:
// Get artist info
$artist_id = isset($_GET['artist']) ? intval($_GET['artist']) : 0;
$sql = "SELECT * FROM artist";
if($artist_id)
$sql .= " WHERE artist=$artist_id";
mysql_query($sql);
Well you should filter the result with your SQL, not with PHP...
Try to Google for "MySQL SELECT FROM WHERE" it will easily help you
First, the MySQL API you are using is deprecated and will eventually be removed. It is recommended you switch to MySQLI or PDO for any new development.
In PHP to get URL parameters user the $_GET superglobal.
$artist = $_GET['artist'];
You must then bind the paramter to your SELECT statement. Here is why it would be best to switch to MySQLI or PDO because the mysql_* functions in PHP do not support prepared statements and parameterized queries. Read more at How can I prevent SQL injection in PHP?
That said, using mysql_* here is a way to pass the artist into your query:
// Query
$query = sprintf("SELECT * FROM mytable WHERE artist='%s'",
mysql_real_escape_string($artist));
$result = mysql_query($query);
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['artist'] = $row['artist'];
$row_array['song'] = $row['song'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
I have a database that I am trying to query to get information to display to my user. I have used
fetch(PDO::FETCH_ASSOC)
before when retrieving a single row or
$row = mysql_fetch_array($result)
with good results. However, it is my understanding that it is better practice to use PDO so that is what I am trying to do.
The problem I am running into is that my results are only showing me the first row of the data I need. In this instance it is displaying the column header over and over and never giving me the data.
$stmt = $conn->prepare("SELECT ? FROM application");
$stmt->bindparam(1, $application_ID);
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
foreach($results as $row){
echo $row['application_ID'];
}
Here are the results
application_IDapplication_IDapplication_IDapplication_ID
It is good that you are aware that MySQL has been oficially deprecated and now we are supposed to used MySQLi or better yet, PDO.
Since you are not accepting any user input, there is no need of using a prepared statement.
Simply do this:
$stmt = $conn->query("SELECT * FROM application");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $row){
echo $row['application_ID'];
//output other rows here
}
As per the php documentation pdo::fetchAll
you have to use fetchAll, instead of fetchall.
I know this might be a very basic question, but I am new to php and databases, I'm trying to figure out a while condition that will keep while loop running until all (would be also nice to know how to do it for fixed amount) of data is taken form database.
$stmt = $db->prepare("SELECT * FROM icecreams");
$stmt -> execute();
$row = $stmt -> fetchAll(PDO::FETCH_ASSOC);
So now I need to figure out what while condition I need, the logic is
while (there is data to fetch) {
echo "<h1>$row['flavour']</h1>";
echo "...";
}
fetchAll() returns an array containing all of the result set rows, whereas fetch() returns a single row from the result-set.
fetchAll() Usage:
$array = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($array as $row) {
# code...
}
fetch() Usage:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
# code...
}
If you're going to use this for printing HTML, the second option seems nicer. For small recordsets, the performance difference shouldn't really matter, but if you're working with a lot of records, then fetchAll() might be a little slower, as it tries to map the entire data into a single array at once.
$stmt = $db->prepare("SELECT * FROM properties");
$stmt -> execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
//$row['column_name']
}
fetchAll does fetch everything as an associative array (as flag FETCH_ASSOC tells). It does it automatically for, you don't have to worry about it.
If you do this then you will see that you have all of your data in an array already:
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<pre>'.print_r($row, true).'</pre>';
So now you can simply loop the items an access the data:
foreach($row as $k=>$v)
{
echo $k.'<br>'; // this will show you what row # you are on, sometimes useful :)
echo $v['title'].'<br>';
// etc....
}
I am currently working on an AJAX testing platform. I am experiencing stupid errors in PHP programming. Here is my code. I get the error: Maximum execution time of 30 seconds exceeded.
<?php
$resultFromJson;
$databaseConnection = mysql_connect("localhost", "root", "password");
if($databaseConnection)mysql_select_db("fastdata", $databaseConnection);
else echo mysql_error($databaseConnection);
if(isset($_GET['command'])){
switch($_GET['command']){
case "loadPeople":
{
$sqlCommandString = "SELECT * FROM `people` LIMIT 0 , 30";
$people = array();
$index = 0;
while($row = mysql_fetch_assoc(mysql_query($sqlCommandString))){
$people[$index] = $row;
$index++;
}
echo json_encode( $people );
}
break;
}
}
if(!isset($_GET['command']))echo json_encode( "Error#001" );
?>
What can I do to solve this error? What actually causes the error?
P.S. I am currently testing my PHP script directly in the browser with main.php?command=loadPeople as URL.
Execute the query, then loop through the results; don't try to re-execute the query in every iteration of the while
$resultset = mysql_query($sqlCommandString);
while ($row = mysql_fetch_assoc($resultset)) {
As you're clearly just learning the basics, I'd suggest that you learn to use MySQLi or PDO rather than the deprecated MySQL library... being able to use prepared statements and bind variables doesn't affect this query, but knowing how to use them will become more important later
i haven't written any PHP code in a while so this is a wild guess but in this piece of code:
while($row = mysql_fetch_assoc(mysql_query($sqlCommandString)))
you essentially have a neverending loop because $row will be assigned every time mysql_fetch_assoc(mysql_query($sqlCommandString)) returns a result
you need to save mysql_query($sqlCommandString) into a variable and then mysql_fetch_assoc from that variable in a loop