SQL Query Returning Only one row in result
This might have something to do with it: you are re-writing your $result
variable in the loop.
$result = mysqli_query($conn,"SELECT user_image FROM 'users' WHERE id=$user_id");
Why PHP function is returning Only the one row from mysql
The return should be outside the while loop !
Here is how you can get all the rows :
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0){
$arr = array();
while($row = $stmt->fetch_row())
{
$arr[] = $row;
}
return $arr;
}
}
Or you can do something like this return a generator and loop through :
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0){
while($row = $stmt->fetch_row())
{
yield $row;
}
}
}
see the result here !
echo '<pre>';
foreach (getAll() as $value) {
print_r($value);
}
query returns only one row when using PHP
mysqli_fetch_assoc
returns an associative result of one row. See here
You need to do something like this:
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
that will give you an array of associative arrays of query results.
Query only returning one row (PHP / MYSQL)
The problem is that you have html code inside the loop section, meaning you're creating a map for each coordinate. I think the best approach, considering your code, is to create an array of markers and then converting it to JSON using the json_encode
method and printing it to a variable on your javascript code.
// Display the results of the query
$markers = [];
while($row = $result->fetch_assoc()) {
$markers[] = [
'coords' => [
'lat' => $row['lat'],
'lng' => $row['lng']
],
'iconImage' => 'images/hs.png',
'content' => "<h2>Hydrant - Number {$row['id']}</h2><b>Flow</b> {$row['flow']} Liters per minute<br><b>Pressure</b> {$row['pressure']} bar<br><br>{$row['type']}<br>{$row['lid']}<br><br><center><a href=images/hydrants/{$row['id']}.jpg><img src=images/hydrants/{$row['id']}.jpg width=100%></a>Updated {$row['updated']}<br><br><a href=\"report.php?id={$row['id']}\">Report problem with this hydrant</a></center>"
];
}
Then on your javascript, simply add a variable like this and print the encoded result:
var markers = <?php echo json_encode($markers); ?>;
The whole code:
<?php include("header.php");
// Connect to the hydrants table and set ORDER BY to ASC or DESC
$sql = "SELECT id, lat, lng, flow, pressure, type, lid, updated FROM hydrants_OLD ORDER BY id ASC";
$result = $conn->query($sql);
// Display the results of the query
$markers = [];
while($row = $result->fetch_assoc()) {
$markers[] = [
'coords' => [
'lat' => $row['lat'],
'lng' => $row['lng']
],
'iconImage' => 'images/hs.png',
'content' => "<h2>Hydrant - Number {$row['id']}</h2><b>Flow</b> {$row['flow']} Liters per minute<br><b>Pressure</b> {$row['pressure']} bar<br><br>{$row['type']}<br>{$row['lid']}<br><br><center><a href=images/hydrants/{$row['id']}.jpg><img src=images/hydrants/{$row['id']}.jpg width=100%></a>Updated {$row['updated']}<br><br><a href=\"report.php?id={$row['id']}\">Report problem with this hydrant</a></center>"
];
// echo "{$row['id']}, {$row['lat']}, {$row['lng']}, {$row['flow']}, {$row['pressure']}, {$row['type']}, {$row['lid']}, {$row['updated']}, <br>" ;
}
?>
<head>
<title>Hydrants</title>
<meta name="viewport" content="initial-scale=1.0">
<link rel="Shortcut Icon" href=images/hl.png>
<meta name="mobile-web-app-capable" content="yes">
<link rel="icon" href="images/hl.png">
<!--<meta name="apple-mobile-web-app-capable" content="yes">-->
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-title" content="Hydrants">
<link rel="apple-touch-icon" href="images/h-apple.png"><link rel="apple-touch-startup-image" media="(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2)" href="images/h-apple.png"><link rel="apple-touch-startup-image" media="(device-width: 768px) and (orientation: portrait)" href="images/h-apple.png">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body bgcolor="#ffffff">
<div id="map"></div>
<script>
var map, infoWindow;
function initMap(){
// Map options
var options = {
// zoom:17,
zoom:14,
center: {lat: 53.428345, lng: -6.244447},
}
var markers = <?php echo json_encode($markers); ?>;
var map = new google.maps.Map(document.getElementById('map'), options);
// Loop through markers
for(var i = 0;i < markers.length;i++){
// Add marker
addMarker(markers[i]);
}
// Add Marker Function
function addMarker(props){
var marker = new google.maps.Marker({
position:props.coords,
map:map,
//icon:props.iconImage
});
// Check for customicon
if(props.iconImage){
// Set icon image
marker.setIcon(props.iconImage);
}
// Check content
if(props.content){
var infoWindow = new google.maps.InfoWindow({
content:props.content
});
marker.addListener('click', function(){
infoWindow.open(map, marker);
});
}
}
infoWindow = new google.maps.InfoWindow;
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=0000MYAPIKEY0000&callback=initMap">
</script>
</body>
<?php
// Close database connection
$conn->close();
?>
MySQL returns only one row
$query = mysql_query("SELECT `title`,
`url_title`
FROM `fastsearch`
WHERE `tags`
LIKE '%$q%'
LIMIT 5");
while ($row = mysql_fetch_assoc($query)) {
print_r($row);
}
- You misspelled
$query
in your example mysql_fetch_assoc()
will return a row each time it is called, andFALSE
when out of rows. Use that to your advantage, by assigning a variable to it in the condition. Within thewhile()
loop,$row
will be the current row.
Sql query returns only first row
You need to use fetchALL()
as fetch()
only returns one row according to the docs:
Fetches a row from a result set associated with a PDOStatement object.
$query = "SELECT Email from client";
$result = $db->query($query)->fetchALL();
foreach($result as $email){
echo $email["Email"]."\n";
}
PHP SQL, query returns only one row of data
mysql_fetch_assoc
fetches one row at a time. You need to loop over the result set:
while(false !== ($row = mysql_fetch_assoc($results))){
[handle $row here]
}
From the docs (search is your friend):
Returns an associative array of strings that corresponds to the fetched row, or FALSE if there are no more rows.
If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using mysql_fetch_row() or add alias names. See the example at the mysql_fetch_array() description about aliases.
Cheers
SQL query returning only 1 row
Use a JOIN
query and you could return all the rows -
$query = "SELECT products.*
FROM products
JOIN partmakes
ON (
products.PARTNO = partmakes.PARTMAKE1
OR
products.PARTNO = partmakes.PARTMAKE2
OR
products.PARTNO = partmakes.PARTMAKE3
OR
products.PARTNO = partmakes.PARTMAKE4)
WHERE partmakes.MAKE = '$_POST[make]'
AND partmakes.MODEL ='$_POST[model]'";
$results = mysqli_query($cnx, $query);
echo "These are the products for your car:<br />";
echo "<table><tr><th>PARTNO</th><th>TITLE</th><th>PRICE</th></tr>";
while ($row = mysqli_fetch_assoc($results)){
echo "<tr><td>{$row[PARTNO]}</td><td>{$row[TITLE]}</td><td>{$row[PRICE]}</td></tr>";
}
echo "</table>";
Make sure to sanitize your $_POST
user data.
You can see the JOIN
query working in sqlFiddle - http://sqlfiddle.com/#!9/754feb/4
Related Topics
Data from Two Tables with Same Column Names
How to Create a Base64Encoded String from Image Resource
PHP Simplexml Attributes Are Missing
Proper Repository Pattern Design in PHP
How to Handle User Input of Invalid Utf-8 Characters
How to Redirect Back to Form with Input - Laravel 5
How to Execute PHP Code Within JavaScript
How to Change PHP Version Used by Composer
Iterable Objects and Array Type Hinting
Backslash in PHP -- What Does It Mean
Fatal Error: Call to Undefined Method MySQLi_Result::Fetch_All()
Using PHP as a Template Engine
Rest API Authorization & Authentication (Web + Mobile)
Phpmailer: Reply Using Only "Reply To" Address
Algorithm to Get All Possible String Combinations from Array Up to Certain Length