Foreach loop does not work correctly (PHP) - php

here is my code
$query = mysql_query("SELECT * FROM accommodation_vacancies WHERE accommodation_id = '$accom'");
$results = mysql_fetch_array($query);
if($query === FALSE) {
die(mysql_error());
} else {
print_r($results);
foreach ($results as $result) {
echo $result['start_date']; echo "<br/>";
}
}
And here is my output
By using the print_r commant i can see that The variable $results works properly,the query works properly also, i guess that i have mistakes on the foreach loop.
Thank you.

You are only fetching a single result. Use a while loop instead.
while ($result = mysql_fetch_array($query)) {
Side note: As stated in the comments, the mysql_* functions are deprecated. You should NOT learn how to use mysql using these deprecated methods. They will be removed from PHP in some future version and your code will stop working then. If you learn it, use mysqli_* or PDO.

Related

Passing mysql_query to JSON file does not work

I have a small code that should convert a query to my mysql database into a json file, but it does not return anything.
I have seen this example in many places but it does not work for me
Of course I checked before the query contains rows
I appreciate the help
<?php
if (!$enlace = mysql_connect('X.X.X.X', 'xxxx', 'xxxx') or !mysql_select_db('xxxx', $enlace)) {
echo 'No pudo conectarse a mysql';
exit;
}
$sql = 'SELECT * FROM `Tabla`';
$resultado = mysql_query($sql, $enlace);
$json = array();
while($row=mysql_fetch_assoc($resultado)){
$json[]=$row;
}
echo json_encode($json);
?>
The reason for not getting anything is because you are overwriting the array variable,
also note that you need to use mysqli since mysql_ is deprecated.
Change this line:
$resultado = mysql_query($sql, $enlace);
$json = array();
while($row=mysql_fetch_assoc($resultado)){
$json=$row;
}
to:
$resultado = mysqli_query($sql, $enlace);
$json = array();
while($row=mysqli_fetch_assoc($resultado)){
$json[]=$row;
}
Fist of all use mysqli instead of mysql it is deprecated since PHP 5.5.0.
And then add the row to the array instead of overwriting it.
$json[] = $row;
for test add this line in the loop
$json = [];
while($row = mysql_fetch_assoc($resultado)){
$json[] = $row;
print_r($row);
}
If you get no output the query is not giving you any results
You may try converting to array to be sure.
while($row=mysql_fetch_assoc($resultado)){
$json[]=(array)$row;
}
and yes simple debugging is important just use var_dump() to identify the issue
var_dump(['socket:', $resultado]); $i=0;
while($row=mysql_fetch_assoc($resultado)){
$json[]=(array)$row;
var_dump([$i++, $row]);
}
exit();
And of course you should not use deprecated functions but i assume this is a learning environment or just an old working system

PHP search only showing one result from SQL

Im using a PHP search function on my website and it is currently only displaying one result from my SQL database - i would like it to display all results included in the site_keywords!
Here is the PHP code i'm currently using on my page
<?php
mysql_connect("danieljosephdesignsc.ipagemysql.com", "searchdata", "danieljoseph");
mysql_select_db("my_db");
if(isset($_GET['search'])) {
$search_value = $_GET['value'];
$query = "select * from sites where site_keywords like '%$search_value%'";
$run = mysql_query($query);
while($row=mysql_fetch_array($run)){
$title = $row['site_title'];
$link = $row['site_link'];
$desc = $row['site_desc'];
}
}
?>
Here is what is included in my body:
<?php echo "<div><a href='$link'><h2>$title</h2></a><p>$desc</p><a href='$link'>$link</a></div>";?>
Please let me know if you require further info. Any assistance on this would be greatly appreciated.
Thanks
You problem is that you aren't echoing the results within your loop.
you need something like this:
while($row=mysql_fetch_assoc($run)){
$title = $row['site_title'];
$link = $row['site_link'];
$desc = $row['site_desc'];
echo "<div><a href='$link'><h2>$title</h2></a><p>$desc</p><a href='$link'>$link</a></div>";
}
Important Note:
You are using deprecated code. This is true of any function that begins with mysql_. This means that your code will no longer work in newer versions of php, and is likely to be not secure if you call any of your variables in your queries. You really need to look up using prepared statements using either mysqli or PDO.
From the official site
This extension is deprecated as of PHP 5.5.0, and will be removed in
the future. Instead, the MySQLi or PDO_MySQL extension should be used.
See also MySQL: choosing an API guide and related FAQ for more
information. Alternatives to this function include:
mysqli_connect()
PDO::__construct()
Here's how to use mysqli prepared statements
or PDO prepared statements
The problem is in this block of code:
while($row=mysql_fetch_array($run)){
$title = $row['site_title'];
$link = $row['site_link'];
$desc = $row['site_desc'];
}
Even though you're getting multiple results, each result overwrites the values of the previous one. So in the end you only have a single row. Try saving the results to an array instead and iterating over it in the body.
$rows =array();
while($row=mysql_fetch_array($run)){
$rows[] =$row;
}
foreach($rows as $row){
$title = $row['site_title'];
$link = $row['site_link'];
$desc = $row['site_desc'];
echo "<div><a href='$link'><h2>$title</h2></a><p>$desc</p><a href='$link'>$link</a></div>";
}

MySQL time-exceeded error

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

How do get all the data from a single table in mysql using php?

I'm trying to simply get all the data from a mysql table using the following code:
$dbc = mysqli_connect('host', 'user', 'password', 'table');
$q = 'SELECT * FROM users';
$r = mysqli_query($dbc, $q);
$user_array = array();
while ($row = mysql_fetch_array($r))
{
$user_array[]=$row;
}
echo "<br />";
echo "print r of user_array: <br />";
print_r($user_array);
i'm getting nothing. I looked at this tutorial (http://www.w3schools.com/php/php_mysql_select.asp), among others, but all they do is confuse me.
What am I doing wrong?
try changing this
mysql_fetch_array($r)
to
mysqli_fetch_array($r)
You have connected via the procedural MySQLi API (mysqli_connect()), but you are attempting to use the old mysql_fetch_array() from the old mysql_*() API. They aren't compatible.
You need to fetch via mysqli_fetch_array() or mysqli_fetch_assoc() instead. mysqli_fetch_assoc() is recommended unless you really need numeric keys in addition to column names in the output $row:
// Check for errors.
if ($r) {
while ($row = mysqli_fetch_assoc($r)) {
$user_array[] = $row;
}
}
else echo mysqli_error($dbc);
What you're working with now is a simple query with no parameters, just a SELECT * without a WHERE clause. For the future, when you start adding WHERE conditions, you'll want to start reading about prepared statements and mysqli::prepare().

Loading MySQL data into a PHP array

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();
}

Categories