Using mysql_fetch_assoc and mysql_result together? - php

I am having great trouble trying to use mysql_fetch_assoc and mysql_result together in the same PHP script.
Originally (when not utilizing the mysql_result function) I was getting the required database values using a combination of mysql_query and mysql_fetch_assoc and everything was fine. Then i added 2 lines into my code to obtain certain ‘title’ field values using mysql_result.
Now if i run my script as it is below i will only receive 1 result even though there are 2 result. Then if i move my do/while loop up so that it is between the other 2 blocks of code (mysql_fetch_assoc and mysql_result lines) i will receive the desired 2 results.
I need my loop to come after the mysql_result section so putting the loop before it is not an option.
// connect to DB and get values
mysql_select_db($database, $mywebsite);
$query_not_related_before = "SELECT * FROM table limit 2";
$not_related_before = mysql_query($query_not_related_before, $ mywebsite);
$row_not_related_before = mysql_fetch_assoc($not_related_before);
// Extract just the results from the title field (the problem area!)
$before_essayid4 = mysql_result($not_related_before,0, 'title');
$before_essayid5 = mysql_result($not_related_before,1, 'title');
// Display results etc
do {
echo "<br />".$row_not_related_before['title']."<br />";}
while ($row_not_related_before = mysql_fetch_assoc($not_related_before));
Plase help,
Many thanks,
David

I am unsure if this will solve your problem but I think you should "seek" the result back.
mysql_data_seek ($not_related_before, 0)
Also, check out the warning on the mysql_result page:
Calls to mysql_result() should not be
mixed with calls to other functions
that deal with the result set.
Hope this helps ;)

You get one row because the first already requested here:
$row_not_related_before = mysql_fetch_assoc($not_related_before);
So I think you have to move result pointer to beginning:
mysql_data_seek($not_related_before, 0);
// Display results etc
do {
echo "<br />".$row_not_related_before['title']."<br />";}
while ($row_not_related_before = mysql_fetch_assoc($not_related_before));

A simpler solution would be to use 2D array's, i have always found the mysql functions to be a little cumbersome.
<?php
$result = mysqli_query(db_connect(),$query);
$result_out = array();
if(#mysqli_num_rows($result))
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC))$result_out[]=$row;
foreach($result_out as $row)
{
echo "<br />".$row['title']."<br />";
}
?>
hth

Related

Moving Query to MySQLi

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.

PHP while loop. Why does this work?

I'm creating my first php site using tutorial for reference. I can't get my head around why the following works:
while ($row = mysql_fetch_array($result)){
echo $row[1]. " ".row[2]."<br/>";
}
Specifically, how does the loop increment to the next row?
UPDATE:
Thanks to all who bothered to provide an answer, including those who implored me to RTM. My problem was not understanding how while loops work, rather simply I couldn't see how the loop increments.
THE ANSWER:
From the PHP docs,
mysql_fetch_array: Returns an array that corresponds to the fetched row and moves the internal data pointer ahead
I see now, all is well.
You can rewrite that code to this equivalent:
$row = mysql_fetch_array($result); // fetch and advance
while ($row !== false) { // compare result against false
echo $row[1]. " ".row[2]."<br/>";
$row = mysql_fetch_array($result); // fetch and advance
}
An assignment yields a value which can then be used in a condition, though it's a good practice to put parentheses around the assignment:
// fetch and advance, compare fetched result against false
while (($row = mysql_fetch_array($result)) !== false) {
echo $row[1]. " ".row[2]."<br/>";
}
mysql_fetch_array() will take a $result and save into $row in form an array. Using while loop, your program will loop the data in the array from the beginning until the end.
By the way, your codes should be like
while ($row = mysql_fetch_array($result)){
echo $row['someData1']. " ".row['someData2']."<br/>";
}
If you want to iterate through the index, then the code looks like following but it will print the word Array as you will print the result in "that" specific index.
$indexCounter = 0;
while ($row = mysql_fetch_array($result)){
echo $row[$indexCounter]."<br/>";
}
Hope this helps! Thank you.
The mysql_fetch_array take the first element of $result then is $result have elements this work... is like take cards from a deck
Take a read though the PHP While documentation. It might also be useful to learn what mysql_fetch_array() does and how it works. After you're done reading about that, don't use the mysql_* functions again because they're deprecated. Instead, use mysqli_* or PDO.

Array not containing values when using "in_array" (php) w/ mysql_query

I continue to struggle with array! This is probably easy to answer.
I'm retrieving a data set from MYSQL w/ PHP. I get an array that has the 1st row (ala the mysql_fetch_array). Typically I would just loop through this and get each value, but in this case I'm already in the middle of a loop and I need to find out if a particular value exists in the full data set (which will be more than 1 row).
I figured I could just loop through and put all the values into an array with something like:
$query = "SELECT MapId FROM Map Where GameId = $gl_game_id";
$result_set = mysql_query($query, $connection);
confirm_query($result_set);
$map_set = array();
while($row = mysql_fetch_assoc($result_set)) {
$map_set[] = $row;
}
When I print_r this, I do in fact get the full data set (e.g. all rows of MapId from table Map).
So now, when I go to look in there and see if a value (that is coming out of this other loop) exists, it won't find it.
So my code looks like:
if (in_array($i, $map_set)) {
echo "yes, it's there baby!";
}
But it doesn't work. I tried hard coding the array, and that does in fact work. So there is simply something wrong with the way I'm constructing my array that this function doesn't like it.
if (in_array($i, array(40,12,53,65))) {
echo "yes, it's there baby!";
}
arrrg... I do hate being a noobie at this.
Function mysql_fetch_assoc returned array.
If you make print_r($map_set) then you will see that is 2-dimension array. Sure in_array not worked.
Just replace $map_set[] = $row; by $map_set[] = $row["MapId"]; and then try again.

Newbie While Loop

I get the following error when i try to display index.php
Warning: mysql_numrows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\cards\index.php on line 18
I can't tell if I'm not connecting to the database correctly or if thre is some other error. Basically I'm trying to display 3 random lines of data from my table "cards". The column in the table that I want to display the data from is "playerName". I'm not worried about formatting the data yet. Code is below:
<?php
include_once 'header.php';
require_once 'config.php';
$con = mysql_pconnect("localhost","*****","*****");
mysql_select_db("USE cards",$con);
$cards=0;
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$sql = "SELECT * FROM cards ORDER BY RAND() LIMIT 3";
$results = mysql_query($sql);
$array = mysql_fetch_array($results);
$num=mysql_num_rows($results);
$i=0;
while ($i < $num) {
echo $rows['playerName'];
$i++;
}
include_once 'footer.php';
?>
I know this is probably a simple newbie question, but I appreciate the help.
Your mysql_select_db call should take only the database name as first argument, not the entire USE statement. Most likely it silently fails and does not select the cards database. Then the query fails (again, silently) returning false.
Also, it's mysql_num_rows (not mysql_numrows).
Manual: http://php.net/manual/en/function.mysql-num-rows.php
Two things, echoing an array wont print it(echo $results;) instead use print_r($results) or var_dump($results) and the other thing, I reckon the error is caused be cause no results are returned, but if you use var_dump or print_r you will be able to verify whether that is the case :)
also there is a typo here: $con = mysql_pconnect("localhost","jalexander","brunswick3"); remove the p from connect :)
Also, you might want to replace your db credentials with asterixes on here :)
Finally, you declare the variable cards but never use it?
In fact one more, change $rows[playerName] to $rows['playerName']
To get different rows instead of using a while loop you can use a foreach like so:
foreach($array as $row){
echo $row['playerName'];
}
Or to do it using a while loop use
$i=0;
while ($i < $num) {
echo $rows[$i]['playerName'];
$i++;
}
It did not work in your current code because you was not looping through the elements of the array, just echoing the same one each time

PHP while loop Error

My query is right but its fetch zero result so why this while loop is print ones this statement No error please tell thanks in advance
while(mysql_fetch_array($query))
{ echo "<br>"."No Error"."<br>"; }
Please do a small debugging and put "echo mysql_num_rows($query);" just before that. It should tell you the exact number of records - and thus, the number of loops in while. mysql_fetch_array returns FALSE when no more records (or no records from the beginning).
mysql_fetch_array() method takes result of running a query on database as parameter rather than query itself and returns a row as an array.
Correct code would be:
$result = mysql_query($query);
while($row = mysql_fetch_array($result) )
{
echo "<br>"."No Error"."<br>";
}
For more details on mysql_fetch_array(), have a look at:
http://php.net/manual/en/function.mysql-fetch-array.php

Categories