How to Retrieve 1 Result from Custom MySQL fetch Function - php

Yesterday another user helped out with building a generic function for handling MySQL Queries. It looks like this:
function fetchAll($query) {
$res = mysql_query($query) or trigger_error("db: ".mysql_error()." in ".$query);
$a = array();
if ($res) {
while($row = mysql_fetch_assoc($res)) {
$a[]=$row;
}
}
return $a;
}
And to output the returned results I simply do the following:
$data = fetchAll("SELECT * FROM news_table ORDER BY id LIMIT 10");
foreach ($data as $row) {
echo $row['title'];
}
My question relates to outputting the result when there's only one result in the array. Like when displaying the current blog post of a page. I want to know if I can do it without first calling the foreach loop? Is there a way to output just the first result from the array as I do not need to loop through it.
Perhaps I could have an alternate function, as opposed to the fetchAll() one above? One that just outputs one row?
Cheers,
Scott

Yes. For example:
echo $data[0]['title'];
Basically your $data is a two-dimensional array, with the first dimension being the row number (count starts with 0), so you can access any of the rows directly if you know its number. If you only have one row, it's necessarily 0.

Just count the array
if(count($data) == 1) {
// Only one dataset
} else if(count($data) > 0) {
// foreach
} else {
// no content
}

echo $data[0]['title'];
Should print exactly what your looking for. In 2D arrays the first dimension is the array index and as array index start at 0, the above code will echo the first row in that array.

Related

Unsure what PHP array is doing upon assigning

I have a DB snippit of code here... I'll post the relevant lines without error checking to make it smaller...
if ($stmt->bind_result($row[0], $row[1]) === false) etc...
then below I have...
<pre><code>
//fill the array up with an array of rows, then increment $ddp.
//$data[$ddp] is the row,
//$data[$dpp][0] is the rows first argument,
//$data[$dpp][1] is the rows 2nd argument returned etc...
$ddp = 0; // this increments up every fetch
while ($stmt->fetch()) {
$data[$ddp][0] = $row[0];
$data[$ddp][1] = $row[1];
$ddp++;
}
</code></pre>
The way I have it above WORKS.... but here is how I did it before and something weird was happening...
<pre><code>
$ddp = 0; // this increments up every fetch
while ($stmt->fetch()) {
$data[$ddp++] = $row;
// I ECHOd out $row here... and it did fetch 2 different rows...
}
</code></pre>
What happens is... when I did this...
$data[$ddp++] = $row;
$data[0][0] was the same as $data[1][0].
Why then if $row had different values on the 2 fetches... how did $data end up with 2 arrays the same?
I even tried
$data[] = $row;
and the same results. My fix was...
while ($stmt->fetch()) {
$data[$ddp][0] = $row[0];
$data[$ddp][1] = $row[1];
$ddp++;
}
WHY?
Sorry if this isn't the right place to put this but I did find a solution ahead of time and to save time I posted the answer and my question together.
Your two assignments are doing two subtly different things.
while ($stmt->fetch()) {
$data[$ddp][0] = $row[0];
$data[$ddp][1] = $row[1];
$ddp++;
}
This creates two entries in the array - the first will have the index [0][0], and be assigned the value in $row[0], and so on.
On the other hand, this:
while ($stmt->fetch()) {
$data[$ddp++] = $row;
// I ECHOd out $row here... and it did fetch 2 different rows...
}
is adding a single row to the database, and adding the whole of $row to $data[0] on the first run through. So whatever is returned from the database is added as it is - if you're getting an array back from fetch(), then you're adding an array inside your array.

Search PHP Array from results of SQL

I currently have an array in php that stores product names, normally 5 - 10. I would like to create something where the results of a SQL query is matched against the array to make sure they are all correct, and if not to show an error.
So far I have put the results into an array, then ran the query to get the results. I believe I need to put some sort of while loop with the results of the query and check the array in that while loop?
You have the array with the product name($products) and the results of the query($row).
While you loop trough the results you can check if the element is present,otherwise echo error and break the loop:
While(...) {
if(!in_array($row['retrivedprod'],$products)) {
echo 'error';
break;
}
}
You can cycle while receiving results from db with a while loop and checking results with the in_array function http://php.net/manual/en/function.in-array.php
$availability = 0;
$cart_products = array("book", "album");
$available_products = array();
while($row = mysql_fetch_array($result)) {
$available_products[] = $row['product'];
}
foreach($cart_products as $key => $value){
if (in_array($value, $available_products)){
$availability = 1;
}
}

MYSQL PHP while loop, do something if there aren't a given amount of rows returned

I'm trying to figure out the best way to do something like this. Basically what I want to do (in a simple example) would be query the database and return the 3 rows, however if there aren't 3 rows, say there are 0, 1, or 2, then I want to put other data in place of the missing rows.
Say my query returns 2 rows. Then there should be 1 list element returned with other data.
Something like this:
http://i42.tinypic.com/30xhi1f.png
$query = mysql_query("SELECT * FROM posts LIMIT 3");
while($row = mysql_fetch_array($query))
{
print "<li>".$row['post']."</li>";
}
//(this is just to give an idea of what i would likkeee to be able to do
else
{
print "<li>Add something here</li>";
}
You can get the number of items in the resultset with mysql_num_rows. Just build the difference to find out how many items are "missing".
There are three ways I can think of, get the row count with mysql_num_rows, prime an array with three values and replace them as you loop the result set, or count down from three as your work, and finish the count with a second loop, like this:
$result = db_query($query);
$addRows = 3;
while ($row = mysql_fetch_assoc($result){
$addRows--;
// do your stuff
}
while ($addRows-- > 0) {
// do your replacement stuff
}
If you dont find a row, Add extra information accordingly.
$query = mysql_query("SELECT * FROM posts");
for($i=0;$i<3;$i++){
$row = mysql_fetch_array($query);
if($row){
print "<li>".$row['post']."</li>";
}
//(this is just to give an idea of what i would likkeee to be able to do
else{
print "<li>Add something here</li>";
}
}
Assuming you store the rows in an array or somesuch, you can simply do some padding with a while loop (depending how you generate the other data):
while (count($resultList) < 3) {
// add another row
}

How to select multiple rows from mysql with one query and use them in php

I currently have a database like the picture below.
Where there is a query that selects the rows with number1 equaling 1. When using
mysql_fetch_assoc()
in php I am only given the first is there any way to get the second? Like through a dimesional array like
array['number2'][2]
or something similar
Use repeated calls to mysql_fetch_assoc. It's documented right in the PHP manual.
http://php.net/manual/function.mysql-fetch-assoc.php
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
If you need to, you can use this to build up a multidimensional array for consumption in other parts of your script.
$Query="select SubCode,SubLongName from subjects where sem=1";
$Subject=mysqli_query($con,$Query);
$i=-1;
while($row = mysqli_fetch_array($Subject))
{
$i++;
$SubjectCode[$i]['SubCode']=$row['SubCode'];
$SubjectCode[$i]['SubLongName']=$row['SubLongName'];
}
Here the while loop will fetch each row.All the columns of the row will be stored in $row variable(array),but when the next iteration happens it will be lost.So we copy the contents of array $row into a multidimensional array called $SubjectCode.contents of each row will be stored in first index of that array.This can be later reused in our script.
(I 'am new to PHP,so if anybody came across this who knows a better way please mention it along with a comment with my name so that I can learn new.)
This is another easy way
$sql_shakil ="SELECT app_id, doctor_id FROM patients WHERE doctor_id = 201 ORDER BY ABS(app_id) ASC";
if ($result = $con->query($sql_shakil)) {
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["app_id"], $row["doctor_id"]);
}
Demo Link
It looks like the complete solution has not been suggested yet
$Query="select SubCode,SubLongName from subjects where sem=1";
$Subject=mysqli_query($con,$Query);
$Rows = array ();
while($row = mysqli_fetch_array($Subject))
{
$Rows [] = $row;
}
The $Rows [] = $row appends the row to the array. The result is a multidimensional array of all rows.

Disappear the arrays generated with mysql_fetch_array() after use?

I have a typical database query:
$query = mysql_query('SELECT titulo,referencia FROM cursos WHERE tipo=1 AND estado=1');
and I can convert it in an array and print the data:
while ($results=mysql_fetch_array($query)): ?>
echo $results['referencia'];
// and so...
endwhile;
but in some cases I need to print the same data in another part of the web page, but the $results array seems to be empty (I use var_dump($results) and I get bool(false)). I plan to use what I learned reading Create PHP array from MySQL column, but not supposed to mysql_fetch_array() creates an array? So, what happen?
Tae, the reason that your $result is false at the end of the while loop is that mysql_fetch_array returns false when it reaches the end of the query set. (See the PHP Docs on the subject) When you reach the end of the query set $results is set to false and the while loop is exited. If you want to save the arrays (database row results) for later, then do as Chacha102 suggests and store each row as it is pulled from the database.
$data = array();
while($results = mysql_fetch_array($query)) {
$data[] = $results;
}
foreach ($data as $result_row) {
echo $result_row['referencia'];
... etc.
}
Try this
while($results = mysql_fetch_array($query))
{
$data[] = $results;
}
Now, all of your results are in $data, and you can do whatever you want from there.
As Anthony said, you might want to make sure that data is actually being retrieved from the query. Check if any results are being returned by echo mysql_num_rows($query). That should give you the number of rows you got

Categories