While loop inside a while loop in two different functions? - php

I have two mysql_queries who have two while loops in fetch_assoc. One written inside another. I want to take one while loop inside a function and another inside another function. How to do that? Help. Here's an example of what I'm trying to say.
$query1 = mysql_query('...');
while($row1 = mysql_fetch_assoc($query1)){
$id = $row1['id'];
$query2 = mysql_query('...');
while($row2 = mysql_fetch_assoc($query2)){
$picture = $row2['picture'];
echo $id.' '.$picture;
}
}
I want to take these two inside two different functions..
function query1(){
1st query with 1st while loop
}
function query2(){
2nd query with 2nd while loop
}
So that I can execute them just the way it is supposed to be..
query1();
query2();
echo $id.' '.$picture;
How to achieve this? Help.

You could structure it as follows:
function query2(){
//do inner stuff
}
function query1(){
//do stuff
query2();
}
query1();
Let me know if you need more context!

Related

PHP array created inside for loop but not printing

I created a script to get data from a mysql table for every year and put into array of respective year. I checked the sql and the while loop iteration is working.
<?php
mysql_select_db($database_hari,$hari);
$start=2013 ;
$end=2015;
$xdata=array();
for($year=$start;$year<=$end;$year++){
${"y".$year}=array();
$i=0;
$query=mysql_query("SELECT tld_master.location,tld_dose.year, AVG(tld_dose.dose)*4 as avgdose from tld_master left join tld_dose on tld_master.tldno=tld_dose.tldno where tld_master.site='F' and tld_dose.year=$year GROUP BY tld_dose.year, tld_dose.tldno");
while($result=mysql_fetch_array($query)){
$xdata[$i]=$result['location'];
${"y".$year."[".$i."]"}=$result['avgdose'];
$i++;
}
}
print_r($y2015);
?>
Print displays "Array()"
But if I am echoing each array value inside for loop it prints. Where is the mistake?
Although there are ways to solve your problem with variable variables, I suggest you take different approach. What if year is a value you do not expect? It can easily lead to confusion. Instead you can use an array that you can iterate through without knowing the exact value of the year.
$yearArray = array();
for($year=$start;$year<=$end;$year++){
$sql = "SELECT
tld_master.location,tld_dose.year, AVG(tld_dose.dose)*4 as avgdose
FROM tld_master
LEFT JOIN tld_dose on tld_master.tldno=tld_dose.tldno
WHERE tld_master.site='F' and tld_dose.year={$year}
GROUP BY tld_dose.year, tld_dose.tldno";
$query = mysql_query($sql);
$yearArray[$year] = array();
while($result=mysql_fetch_array($query)){
$xdata[] = $result['location'];
$yearArray[$year][] = $result['avgdose'];
}
}
Now you can print the $yearArray variable to see your actual results. And you can use it easily.
print_r($yearArray["2015"]);
${"y".$year} = array()
creates a variable named $y2015, holding an array. The code
${"y".$year."[".$i."]"} = ...
creates an oddly named variable $y2015[0], which is completely unrelated to the variable $y2015. You want:
${"y".$year}[$i] = ...
You override your array value with this statement ${"y".$year."[".$i."]"}=$result['avgdose']; Try to use this one instead: ${"y".$year."[".$i."]"}[]=$result['avgdose'];

loop through the data in PDO

I am having difficult loop through the data in PDO and print the data as long as there it has more data for a specific user. I create a function which performs the select. Here is the code that contain the select function, http://pastebin.com/GiAyCBys. I am trying to use that function in cartexe.php using the following code,
while($row = select($conn, 'user', 'cart', $user,':user','*'))
{
echo 'Hello';
}
but I got stuck in an infinite loop. I am grateful for any help I can get.
The solution is to change select to return all rows , since fetch() only return a single row at the time.
Option 1:
$result = array();
while($row = $smtp->fetch(PDO:: FETCH_ASSOC)){
$result[]=$row;
}
return $result;
option 2:
$result = $smtp->fetchAll(PDO:: FETCH_ASSOC);
return $result;
use your function like this
$rows = select($conn, 'user', 'cart', $user,':user','*');
foreach($rows as $row){
//do something with $row
}

Putting a SQL query in a PHP function

I've got several queries I want to run on a single page. I obviously don't want to put the actual queries in my template file, so I think what I want to do is construct a function and call it wherever I want the query results to show up. Right?
So, for example, I'll have <?php sidebar_query()?> in the sidebar, <?php footer_query()?> in the footer, etc.
So, I just make a file called functions.php, do PHP include, and put something like this in there?
<?php
function sidebar_query(){
$query = ("SELECT sidebarposts FROM table;");
return $query;
}
?>
or do you use echo and not return anything?
<?php
function sidebar_query(){
$query = ("SELECT sidebarposts FROM table;");
echo $query;
}
?>
Along the exact same line, I'd like to count the results that get returned, and display a 'There were X posts returned!' message below. Seems like it would make sense to put this in a function too. How would I make a 'generic' function that I could reuse for each query?
<?php
function number_of_results(){
$num_rows = mysql_num_rows();
echo $num_rows;
}
?>
I'd be extremely grateful if someone could give me the theoretical gist of what I should be trying to achieve here.
Thanks for helping a beginner.
Terry
I think I get what you mean.
Return the value instead like this
function sidebar_query(){
$rValue = "";
$query = ("SELECT sidebarposts FROM table;");
$result = mysql_query($query);
if ($row = mysql_fetch_array($result)){
$rValue = $row['sidebarposts'];
}
return $rValue;
}
Now you can echo sidebar_query(); or whatever you want to do with it.
By doing ("SELECT sidebarposts FROM table;")you're not actually doing anything, you just have a string stored as a variable.
A simple example is
function sidebar_query()
{
$query = mysql_query("SELECT title,post FROM table;"); //query the db
$resArr = array(); //create the result array
while($row = mysql_fetch_assoc($query)) { //loop the rows returned from db
$resArr[] = $row; //add row to array
}
return $resArr;
}
Then to use it you can do
$sideBarPosts = sidebar_query(); //get the result array
foreach($sideBarPosts as $post) { //loop the array
echo '<h1>'. $post['title']. '</h1>';
echo '<p>'. $post['post']. '</p>';
}
EDIT. I see you want to let the function print it directly, you can do that instead of returning the array, if you like.
function sidebar_query(){
$query = mysql_query("SELECT * FROM table;");
$result = $conn->query($query);
$resArr = array(); //create the result array
while($row = $result->fetch_assoc()) { //loop the rows returned from db
$resArr[] = $row; //add row to array
}
return $resArr;
}
and that :
$sideBarPosts = sidebar_query(); //get the result array
foreach($sideBarPosts as $post) { //loop the array
echo '<h1>'. $post['title']. '</h1>';
echo '<p>'. $post['post']. '</p>';
}
// Set Connection with database
$conn = mysql_pconnect($servername,$username,$password) or die("Can not Connect MySql Server!");
// Select database you want to use
mysql_select_db($databasename,$conn) or die("Can not select Data Base!");
// When you want to query SQL inside php function, you need to pass connection($conn) to the function as below.
function sidebar_query($condb)
{
$strSql = "SELECT sidebarposts FROM table";
$result = mysql_query($strSql,$condb);
return $result;
}
// Call function
sidebar_query($conn);
This is work for me as i use with my webpage.
Read the php doc on how to run mysql query.
Yay you have the query, now you need to do something with it:
mysql_query($query); for example might work for you :-)
You want to run the query and return the result in whatever format you want to use in your template.. so for the raw number you want to return an integer, for the sidebar posts return an array of posts OR the mysql result.
You should make the "'There were X posts returned!' " thing a completely different function which you can pass in an integer an an optional string. This way you can reuse it for a ton of stuff. for example:
function format_nb_records($nb_records, $format = 'There were %s posts returned!'){
return sprintf($format, $nb_records);
}
Although in this case i dont think there is really enough extra logic to warrant wrapping it in a function. I would probably just do this directly in my template.
A good example of where something like this is useful is if you want to do "time in words" functionality like "Yesterday" or "10 minutes ago" then you would pass in the time calculate which string to use, format it and return it.
Although in this case i dont think there is really enough extra logic to warrant wrapping it in a function. I would probably just do this directly in my template.
A good example of where something like this is useful is if you want to do "time in words" functionality like "Yesterday" or "10 minutes ago" then you would pass in the time calculate which string to use, format it
You need to pass database connection name to function like this,
You already have a connection name, mine is $connect_name
$connect_name= mysql_connect( 'host', 'user', 'password');
function getname($user,$db){
$data= mysql_query("SELECT $user...", $db);
//your codes
//return bla bla
}
echo getname("matasoy",$connect_name);
This work for me.
I also use this for medoo.min sql system. You can use medoo with functions like this;
function randevu($tarih,$saat,$db){
$saat_varmi = $db->count("randevu",array("AND"=>array("tarih"=>$tarih,"saat"=>$saat)));
if($saat_varmi>0)
return 3;
else
return 2;
}
have a nice day, Murat ATASOY

PHP OOP Mysql Query

I'm quite new to PHP OOP and I have a question regarding a simple MYSQL query.
I have an index.php page where I want to output my results from my query.class file.
Here is my method,
public function Query($rowName) {
$q = mysql_query("SELECT * from p_tuts");
while($row = mysql_fetch_array($q)) {
echo $row[$rowName];
}
}
Now this works fine and I can call it though my index.php file
$Database->Query('tut_content');
But my issue is I want to wrap each content block in DIV containers and don't want to have to echo the HTML code in the class file, so I want to really echo the row's data in the index file, but unsure how to do this.
Kind regards
Pass the rows back as an array.
public function Query($colName) {
$q = mysql_query("SELECT * from p_tuts");
$rows = array();
while($row = mysql_fetch_assoc($q)) {
$rows[] = $row[$colName];
}
return $rows;
}
It's better this way anyway, because it keeps database code away from output code (i.e. echo).
Then output it like so:
<?php
$results = $Database->Query('tut_content');
foreach ($results as $result): ?>
<div><?php echo $result; ?></div>
<?php endforeach; ?>
You dont want to be doing the echo in your class.
You want to return the row...
This way
$Database->Query('tut_content');
Can be wrapped in the DIV / whatever you need...
OOP functions are the same as normal function. The function as you have it only echos $row[$rowname]. You either want to modify it to have it echo <div>$row[$rowname]</div> or have it return the row values as an array:
while($row = mysql_fetch_array($q)) {
$output[] = $row[$rowName];
}
return $output;
use the MVC pattern.
http://php-html.net/tutorials/model-view-controller-in-php/
the database belongs to the Model
Good Luck
Or you can use my favorite database layer http://dibiphp.com/. It's small but smart :-)

Mysql database retrieve multiple rows

I use a mysql database. When I run my query I want to be able to put each row that is returned into a new variable. I dont know how to do this.
my current code:
<?php
$result=mysql_query("SELECT * FROM table WHERE var='$var'");
$check_num_rows=mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result))
{
$solution=$row['solution'];
}
?>
The thing is that check num rows can return a row of an integer 0-infinity. If there are more solutions in the database how can I assign them all a variable. The above code works fine for 1 solution, but what if there are more? Thanks.
You can't give each variable a different name, but you can put them all in an array ... if you don't know how this works I suggest looking at a basic tutorial such as http://www.w3schools.com/php/php_arrays.asp as well as my code.
A very simple way (obviously I haven't included mysql_num_rows etc):
$solutions = array()
while($row = mysql_fetch_assoc($result)) {
$solutions[] = $row['solution'];
}
If you have three in your result solutions will be:
$solutions[0] -> first result
$solutions[1] -> second
$solutions[2] -> third
<?php
$result=mysql_query("SELECT * FROM table WHERE var='$var'");
$solution = array();
$check_num_rows=mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result))
{
$solution[]=$row['solution'];
}
?>

Categories