Newbie While Loop - php

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

Related

how to loop through PHP code and MySQL?

How do I use the PHP loop through the query instead of putting all the result into an array then looping through the array
The way I use array and loop is like this:
<?php $userInfos = $qry->querySelect( SQL CODE HERE );
foreach($userInfos as $uInfo)
{
$fName = $uInfo['fName'];
$lName = $uInfo['lName'];
$gender = $uInfo['gender'];
?>
First name is: <? echo $fName; ?> and Last name is <? echo $lName; ?>.
<?php } ?>
I wanted to know better insight on how PHP loop through the query is better than array. Please redirect me to some example or possibly with MySQL code included.
How can I convert the above php code to be more efficient if I am pulling millions of record?
Thanks so much!.
You can do a simple loop with mysqli_fetch_row()
http://php.net/manual/en/mysqli-result.fetch-row.php
It looks like you need to use something other than the querySelect function (which appears to be returning an array).
Maybe the $qry object has some other function that will return you a statement handle you can fetch from, like the normal mysqli_ and PDO interfaces provide.
It looks to me like $qry is from a homegrown MySQL library "wrapper" class, which exposes a limited subset of the functions. If that object doesn't provide a way to get a statement handle, you may need to add the appropriate functions to the object definition, or abandon that and just use mysqli or PDO.
There's lots of examples of how to do that. With PDO, our first cut (before we add error checking and exception handling) might look something like this:
$sql="SELECT t.name FROM really_big_table t";
$sth=$dbh->prepare($sql);
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC) ) {
echo "<br>Name is: ". htmlentities($row['name']);
}
$sth->close();
Reference: http://php.net/manual/en/pdostatement.fetch.php
I do the following:
//DB Query getData
$q_getData = "SELECT `stuff`, `moreStuff`, `otherStuff` FROM `table`";
$rsgetData = mysqli_query($DBi, $q_getData) or die(mysqli_error($DBi));
$row_rsgetData = mysqli_fetch_assoc($rsgetData);
$rows_rsgetData = mysqli_num_rows($rsgetData);
if($rows_rsgetData>0) {
do {
echo $row_rsgetData['stuff'] . ' ' . $row_rsgetData['moreStuff'] . '<br>';
echo $row_rsgetData['otherStuff'];
} while ($row_rsgetData = mysqli_fetch_assoc($rsgetData));
$rows = mysqli_num_rows($rsgetData);
if($rows > 0) {
mysqli_data_seek($rsgetData, 0);
$row_rsgetData = mysqli_fetch_assoc($rsgetData);
}
mysqli_free_result($rsgetData);
};
That runs the query and loops through each row until there are no rows left - only if there are rows returned in the first place. Once it's all finished it frees up the connection.

MySQL query's suceed in PHPMyAdmin but not in the PHP Script itself

Just while playing around with Querying in PHP i ran into some trouble. The title of this post explains the problem. When i run a query in PHPMyAdmin the results will be different from the results i get in the PHP program itself. Here is the code i am using. Sorry if it looks a little odd i've been cutting and pasting things all over the place in a frantic attempt to get it working.
$connect = array('username'=>'root', 'host'=>'127.0.0.1', 'password'=>'');
$link = mysql_connect($connect['host'], $connect['username'], $connect['password']) or die('Error creating link: ' . mysql_error());
mysql_select_db('testing_pages', $link) or die('Error connecting to database: ' . mysql_error());
$sql = "SELECT `name` FROM `names`";
$query = mysql_query($sql, $link) or die('Query Failed! Check error:<br/><br/>' . mysql_error());
$query_2 = mysql_fetch_array($query);
$query = $query_2;
$loop = count($query);
$count = 0;
while($count <= $loop) {
echo $query[$count] . '<br/>';
$count++;
}
see, what im trying to get it to do is read all the names, pop it into an array, then print them out with a while loop. But it only seems to return 1 result and thats the first name in the databse. but when i run the EXACT query through phpmyadmin it will return every name in the database... Another odd thing, when using the 'count' function to get the number of values in the array is claims that there are 3 values, but during the loop it just prints out the first name, then for the second two it returns an 'Undefined index'.
Hope i dont seem like a noob right now... And i hope i explained everything well. Thanks to anyone who can help.
mysql_fetch_array fetches one row in the form of an array. Here are the docs.
And pay attention to that big warning message at the top of the page when you read the docs...

Basic mysqli select

I have a select statement where I want to get all rows from a table but seem to be having a mental blockage - this should be elementary stuff but can't seem to get it working.
There are only two rows in the table 'postage_price' - and two columns : price | ref
Select statement is as follows:
$get_postage="SELECT price FROM postage_price ORDER BY ref DESC";
$get_postage_result=mysqli_query($dbc, $get_postage) or die("Could not get postage");
while($post_row=mysqli_fetch_array($dbc, $get_postage_result))
{
$post1[]=$post_row;
}
I am then trying to echo the results out:
echo $post1['0'];
echo $post1['1'];
this is not showing anything. My headache doesn't help either.
while($post_row = mysqli_fetch_array($dbc, $get_postage_result))
{
$post1[] = $post_row['price'];
}
As you see: $post_row in this line: = mysqli_fetch_array($dbc, $get_postage_result) is an array. You are trying to save the whole array value to another array in a block. :)
EDIT
while($post_row = mysqli_fetch_array($get_postage_result))
...
You have $post1[]=$post_row; and $post_row is itself an array. So you can access post data with following: $post1[NUMBER][0] where NUMBER is a $post1 array index and [0] is 0-index of $post_row returned by mysqli_fetch_array.
Probably you wanted to use $post1[]=$post_row[0]; in your code to avoid having array of arrays.
You are passing 1 and 0 as string indexes, this would only work if you had a column called 0 or 1 in you database. You need to pass them as numeric indexes.
Try:
print_r($post1[0]);
print_r($post1[1]);
or
print_r($post['price']);
print_r($post['ref']);
with all your help I have found the error - it is in the mysqli_fetch_array where I had the $dbc which is not required.
$get_postage="SELECT price FROM postage_price ORDER BY ref DESC";
$get_postage_result=mysqli_query($dbc, $get_postage) or die("Could not get postage");
while($post_row=mysqli_fetch_array($get_postage_result))
{
$post1[]=$post_row['price'];
}
instead of:
$get_postage="SELECT price FROM postage_price ORDER BY ref DESC";
$get_postage_result=mysqli_query($dbc, $get_postage) or die("Could not get postage");
while($post_row=mysqli_fetch_array($dbc, $get_postage_result))
{
$post1[]=$post_row['price'];
}
Bad day for me :(
Thanks all
If something does not work in a PHP script, first thing you can do is to gain more knowledge. You have written that
echo $post1['0'];
echo $post1['1'];
Is showing nothing. That could only be the case if those values are NULL, FALSE or an empty string.
So next step would be to either look into $post1 first
var_dump($post1);
by dumping the variable.
The other step is that you enable error display and reporting to the highest level on top of your script so you get into the know where potential issues are:
ini_set('display_errors', 1); error_reporting(~0);
Also you could use PHP 5.4 (the first part works with the old current PHP 5.3 as well, the foreach does not but you could make query() return something that does) and simplify your script a little, like so:
class MyDB extends mysqli
{
private $throwOnError = true; # That is the die() style you do.
public function query($query, $resultmode = MYSQLI_STORE_RESULT) {
$result = parent::query($query, $resultmode);
if (!$result && $this->throwOnError) {
throw new RuntimeException(sprintf('Query "%s" failed: (#%d) %s', $query, $this->errno, $this->error));
}
return $result;
}
}
$connection = new MyDB('localhost', 'testuser', 'test', 'test');
$query = 'SELECT `option` FROM config';
$result = $connection->query($query);
foreach ($result as $row) {
var_dump($row);
}

Strange error "sqlsrv_fetch_array(): 16 is not a valid ss_sqlsrv_stmt resource" since ReturnDatesAsStrings

I am using the sqlsrv driver for IIS so I can connect to a MS SQL server in PHP.
I've managed to convert a lot of my original mysql_ code and all going well, until I tried to SELECT some DateTime fields from the database. They were coming back as Date objects in PHP rather than strings, I found the fix which is adding this to the connection array:
'ReturnDatesAsStrings'=>1
Since doing that though my code is broken when trying to populate my recordset:
function row_read($recordset) {
if (!$recordset) {
die('<br><br>Invalid query :<br><br><bold>' . $this->sql . '</bold><br><br>' . sqlsrv_error());
}
$rs = sqlsrv_fetch_array($recordset);
return $rs;
}
The error is: sqlsrv_fetch_array(): 16 is not a valid ss_sqlsrv_stmt resource
There is such little amount of help on that error in Google so this is my only shot! I just don't get it.
row_read is called from within a While: while ($row = $db->row_read($rs)) {
Any ideas?
Just to add more code and logic - I do a simple SELECT of all my orders, then as it loops through them, I do another 2 SELECT's on the orders table then the customer table. It's falling down when I try these extra 2 'gets':
$this->db->sql = "SELECT * FROM TicketOrders";
$rs = $this->db->query($this->db->sql);
$this->htmlList->path("skin/search.bookings");
if ($this->db->row_count != 0) {
while ($row = $this->db->row_read($rs)) {
// Load the order row
$this->TicketOrders->get($this->db, $row['Id']);
// Load the customer row
$this->Customers->get($this->db, $row['CustomerId']);
Did you pass this resource variable by another function? If yes, you can try by executing the sqlsrv_query and executing sqlsrv_fetch_array in one function; don’t pass the ss_sqlsrv_stmt resource by another function. Hope that it will help.
Does your program involves a nested query function?
If so, the next question is: are you opening the same database in the inner query function?
Try these changes:
comment out the lines that open the database, including the { and } that enclose the function,
change the name of connection and array variables between the outer loop and the inner loop.
In other words, the outer loop may have:
$tring = sqlsrv_query($myConn, $dbx_str1);
while( $rs_row1 = sqlsrv_fetch_array($tring, SQLSRV_FETCH_ASSOC))
and the inner loop would have:
$tring2 = sqlsrv_query($myConn, $dbx_str2);
while( $rs_row2 = sqlsrv_fetch_array($tring2, SQLSRV_FETCH_ASSOC))
sqlsrv_fetch_array need a ss_sqlsrv_stmt resource. There must be something wrong with your SQL.

Using mysql_fetch_assoc and mysql_result together?

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

Categories