I'm updating some old code that has deprecated MySQL functions. But for some reasons I cannot get all the results from the column. The strange part is that if I run the query directly on the server I get all results fine. So this is an issue with PHP getting the results, not the MySQL server or my query.
Here is the new and old code:
My current updated code:
$sql = "SELECT user, monitor FROM users WHERE `status` = 'y'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
// This works. It shows all results
echo $row["user"];
// This does not work! Only shows one result:
$account= $row["user"];
}
else {
echo 'No results';
}
When I use that query directly on DB server, I get all results. So the SQL query is correct. I actually also get all results as well in PHP if I echo the row directly like:
echo $row["user"];
But for some reason when I try to use it with a PHP with variable it only lists one user result.
In the past I used this but the mysql_fetch_array function is now deprecated
while ($row = mysql_fetch_array($result)) {
array_push($data, $row["user"]);
}
foreach($data as $value) {
$account = $value
}
I cannot use my previous code anymore as those MySQL functions are obsolete today. I need to write the results into a file and my old method worked fine. The new one using mysqli does not.
Any suggestions?
You just need to add one of these [, and one of these ].
$account[] = $row["user"];
// ^^ right here.
$account= $row["user"]; means you're storing the value of $row["user"] in $account each time the loop executes. $account is a string, and it gets a new value each time.
$account[] = $row["user"]; means you're appending each value of $row["user"] to an array instead.
You should not use array_push for this. It's overkill for appending a single value to an array. And if the array isn't defined beforehand, it won't work at all.
Related
My query is not working when I use the variable in the WHERE clause. I have tried everything. I echo the variable $res, it shows me the perfect value, when I use the variable in the query the query is not fetching anything thus mysqli_num_rows is giving me the zero value, but when I give the value that the variable contains statically the query executes perfectly. I have used the same kind of code many times and it worked perfectly, but now in this part of module it is not working.
Code:
$res = $_GET['res']; // I have tried both post and get
echo $res; //here it echos the value = mahanta
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'"; // Here it contains the problem I have tried everything. Note: restaurant name is same as it is in the database $res contains a value and also when I give the value of $res i.e. mahanta in the query it is then working.
$z = mysqli_query($conn, $query);
$row2 = mysqli_fetch_array($z);
echo var_dump($row2); // It is giving me null
$num = mysqli_num_rows($z); // Gives zero
if ($num > 0) {
while ($row2 = mysqli_fetch_array($z)) {
$no = $row2['orders'];
$id = $res . $no;
}
}
else {
echo "none selected";
}
As discussed in the comment. By printing the query var_dump($query), you will get the exact syntax that you are sending to your database to query.
Debugging Tip: You can also test by pasting the var_dump($query) value in your database and you will see the results if your query is okay.
So update your query syntax and print the query will help you.
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'";
var_dump($query);
Hope this will help you and for newbies in future, how to test your queries.
Suggestion: Also see how to write a mysql query syntax for better understanding php variables inside mysql query
The problem is the way you're using $res in your query. Use .$res instead. In PHP (native or framework), injecting variables into queries need a proper syntax.
I am trying to run a query to my mysql database through php and and am trying to get all the resulting rows. I also have to compare every row to the next row returned. I am trying to do this by setting the result variable to another temporary variable and calling mysqli_fetch_assoc() on that so that the while loop runs again for the next row. But what happens is that when I try to use mysqli_fetch_assoc() even on the other variables, somehow mysqli_fetch_assoc($result) also progresses to the next of the next row when while($row = mysqli_fetch_assoc($result)) goes to next iteration.
Here is the code example to illustrate this :
$query = "SELECT * FROM records ORDER BY num ASC;";
if($result = mysqli_query($conn, $query))
{
while($row = mysqli_fetch_assoc($result))
{
$temporaryresult = $result;
$rowtwo = mysqli_fetch_assoc($temporaryresult);// this makes mysqli_fetch_assoc($result) skip the next row which is unwanted
}
}
So how can I keep mysqli_fetch_assoc($result) from moving forward when I call mysqli_fetch_assoc($temporaryresult) ?
Any help would be appreciated.
am trying to do this by setting the result variable to another temporary variable and calling mysqli_fetch_assoc() on that so that the while loop runs again for the next row
It doesn’t work that way. Just because you assigned the resource id to a second variable, doesn’t mean that you now have a second result set that you could operate on separately. Both variables refer to the same resource id. Fetching a row will still move the row pointer of the “original” data set.
I also have to compare every row to the next row returned
Most likely, you are making things harder on yourself by trying to look ahead. Stuff like this is usually easier done when you look at the previous row instead. That one you have fetched already - so you don’t need to do an additional fetch now that would mess with the row pointer.
Pseudo code example:
$prevRow = null;
while($row = fetch(...)) {
if($prevRow) { // for the first row, this will still be null, so we only
// start comparing stuff when that is not the case
// compare whatever you need to compare here
}
...
$prevRow = $row;
}
After #CBroe's answer, I tried to solve this problem while still trying to look forward. I achieved this by storing the rows returned by the database and then looping through them. This makes it very easy too look ahead in the rows returned while avoiding the complexity of changing your code to look backwards.
$array = array();
// look through query
while($row = mysql_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
}
Now, looping through these rows,
$i = 0;
for(;$i<count($array)-1;$i++)
{
if($array[$i]['somecolumn']==$array[$i+1]['anothercolumn'])//compare this column to another column in the next row
{
// do something
}
}
This successfully solved my problem. I hope it helps anyone stuck in the same position I was in.
I have a problem. I have an array of values from database, when I try to pass it to a string with commas, it works fine on my localhost, but when I upload it to my online server, the string doesn't show any values. For example: select from table where in (,,) only shows the commas and in my xampp server it works excellent. Any ideas what this can be?
Here's the code:
<?php
$sql = "select id from users where gid = 1";
$result = mysql_query( $sql);
$cat_titles=array();
while( $row=mysql_fetch_assoc($result) )
{
$cat_titles[] = $row['id '];
// do stuff with other column
// data if we want
}
mysql_free_result( $result );
echo "<p>\n";
foreach($cat_titles as $v)
{
$cat_titles[]= $row['id'];
}
echo "</p>\n";
$cat_titles = implode(',',$cat_titles);
$cat_titles = substr($cat_titles,0,-2);
echo $cat_titles;
echo "select * from users where IN (".$cat_titles.")";
?>
A number of potential issues here:
You are not handling error conditions around you database access, so if you are having issue with your queries you would never know.
Your second select query doesn't specify a field in the WHERE clause, so it will never work
This section of code does absolutely nothing and is in fact where you problem likely lies.
foreach($cat_titles as $v)
{
$cat_titles[]= $row['id'];
}
Here $row['id'] won't have a value, so you are basically looping throguh your existing array and appending empty value to new indexes.
In all likelihood you could do this with a single query, it might help if you explain what you are actually trying to do.
You should not be using mysql_* functions. They are deprecated. Use mysqli or PDO instead.
I have a list of url's(link) in my database and can echo the data to the page fine but instead of outputting it, I need to store that info(I was thinking an array) into a variable to perform php tasks using the provided links. I have yet to figure out how to do this.
The code has been updated I removed any references to using the soon to be deprecated mysql_* functions and opted for the mysqli version.
Heres my code
$query = "SELECT `Link` FROM `Table1` WHERE `Image` ='' AND `Source`='blah'";
if ($result = mysqli_query($dblink, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
$link = $row['Link'];
// echo ''.$link.'<br>';
$html = file_get_html($link);
foreach ($html->find('div.article') as $e) {
$result = $e->find('img', 0);
$imgsrc = $result->src . '<br>';
echo $imgsrc;
}
}
}
This code is working through one iteration: It will find the first link stored in the DB, use that $link in the bottom foreach() statement and output the desired result. After the first iteration of the loop, an error occurs stating:
"mysqli_fetch_assoc() expects parameter 1 to be a mysql result"
I think I understand why the problem is occurring - Since the $result is declared outside of the while loop, it is never set again after the first iteration/or changes in some way.
or
I should be using mysqli_free_result() possibly, If that were the case I am not sure where it would go in the code.
Thanks for any help you can offer!
When you do this:
$result = mysqli_query($dblink, $query);
The functions return a link identifier you store in $result. This identifier we need to pass to fetch functions in order to be able to show it from which result to fetch. It shouldn't be changed until you are done fetching all the results you want.
This goes right the first time:
$row = mysqli_fetch_assoc($result)
But then, in the foreach, you overwrite that variable with other information:
$result = $e->find('img', 0);
As such, when the next iteration comes around, it is no longer a valid result identifier, so MySQL doesn't know what to do with it.
The fix is actually rather simple, you need to change the name of the variable you are using in the foreach:
$result = $e->find('img', 0);
$imgsrc = $result->src . '<br>';
Becomes:
$found= $e->find('img', 0);
$imgsrc = $found->src . '<br>';
And voila, it should work...
Your snippet is full of potential errors:
1) Not checking if query succeeded
$query_run = mysql_query($query)
You execute a query, but you never check if your query succeeded by verifying if $query_run is an actual resource and not FALSE.
2) Validation of rows returned
Your validation for the number of rows returned by the query is useless:
if (mysql_num_rows($query_run)==NULL) {
echo 'No results found.';
}
This is never true, as mysql_num_rows() returns an inte or FALSE, never NULL.
3) Use of variable with potentially invalid value
Using
while ($query_row = mysql_fetch_assoc($query_run)) { ... }
is risky as you never check if $query_run is an actual resource, which is required by mysql_fetch_assoc().
4) Misunderstanding of while loop
The following lines are probably wrong too:
while ($query_row = mysql_fetch_assoc($query_run)) {
$link = $query_row['Link'];
// echo ''.$link.'<br>';
}
$html = file_get_html($link);
You iterate over all rows returned by the query. After the while loop exits, $link only contains the value of the last row as single variable cannot contain the values of multiple rows.
Conclusion
I strongly recommend you improve your error checking and improve the overall quality of your code. Also consider using one of the newer extensions like mysqli or PDO, the mysql extension is deprecated.
If you want to add all links to an array try this:
$link[] = $query_row['Link'];
Instead of:
$link = $query_row['Link'];
You were close but you weren't using square brackets you were using parentheses as shown here:
$link = $query_row($link);
Also, try taking $query_run out of the if statement. It should look something like this:
$query = "SELECT `Link` FROM `Table1` WHERE `Value1` ='' AND `Source`='blah'";
$query_run = mysql_query($query);
if ($query_run) {
echo 'Query Success!<br><br>';
if (mysql_num_rows($query_run) == NULL) {
echo 'No results found.';
}
while ($query_row = mysql_fetch_assoc($query_run)) {
$link[] = $query_row['Link'];
// echo ''.$link.'<br>';
}
$html = file_get_html($link);
foreach ($html->find('div.article') as $e) {
$result = $e->find('img', 0);
$imgsrc = $result->src . '<br>';
echo $imgsrc;
}
}
You should revisit the PHP Language Reference.
The foreach loop syntax is
foreach($array as $element)
or
foreach($array as $key=>$value)
But you seem to have other weak points that I fear are not in the scope of Stackoverflow to mend. For example your own code would work quite well by just moving a single } from line 11 down a few lines.
UPDATE: I solved it using a for loop:
for ($i=0; $i < mysql_num_rows($result); $i++) {
$row = mysql_fetch_assoc($result);
echo $row['name'];
}
ORIGINAL QUESTION:
This looks kinda stupid. I'm sure im missing something that's very simple, since I was able to accomplish this before. Anyways, I want to echo some text for every item in an array. This array is derived from mySQL.
here's the code
while ($row = mysql_fetch_assoc(mysql_query("SELECT * FROM files"))) {
echo $row['name'];
}
can you post the complete code? I think you forgot the database connection.
Try this:
$result = mysql_query("SELECT * FROM files") or die (mysql_error());
while ($row = mysql_fetch_assoc($result)) {
var_dump($row['name']);
}
This will throw an error, I guess you made a mistake over there. Also, var_dump() your $row in the while to make 100% sure you have "a" value.
Also, are you sure the row does exist? If don't have any records, the echo on your $row will not work sinc it does not exist.
Also, set error reporting to E_ALL like so.
error_reporting(E_ALL);
Also, since you are running your query inside the while() loop, it will continue to run forever. So first run the query, and put it in a variable, and then loop through the results. (see my piece of code above)
You can execute query individual instead of while loop because if your query return more than 1 rows it will goes under the loop. show your loop print only first data of result and your loop is infinite.
From your question it seems so simple, try this way it's working.
$sql="SELECT name From files";
$names = $db->query($sql);
while($name1 = $db->fetchByAssoc($names))
{
echo $name1['name'];
}