Putting a SQL query in a PHP function - php

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

Related

Can't print full results (everything after a space is gone)

I'll try to be as specific as possible.
I have a database table from which I'm going to print information. The easiest way to do this is by doing something like this:
$con=mysqli_connect("server","user","pass","dbname");
$users_result = mysqli_query($con,"SELECT * FROM table blabla");
while($row = mysqli_fetch_array($users_result))
echo $row['column_to_echo'];
}
mysqli_close($con);
If this query returned one row, with an address, the outcome on the screen would be something like this "My street 14" Right? And that's how it works as well. So that's great. Exactly what I want.
HOWEVER:
I need to have these SQL queries in functions, because the queries are dynamic based on who's loading the page.
So a function like that looks something like this;
function getUserAddress($userid)
{
$con=mysqli_connect("server","user","pass","dbname");
$users_result = mysqli_query($con,"SELECT * FROM table blabla");
while($row = mysqli_fetch_array($users_result)) {
return $row['column_to_echo'];
}
mysqli_close($con);
}
And I use it by doing this:
<?php $address = getUserAddress(current_user_id); echo $address; ?>
So in this case, we can safely assume that the string being returned by the function is the same string as used in my first example, right? (given the correct ID is being sent into the function).
This is NOT the case.. I would only get the first word on my screen. Meaning the function isn't returning the full string, and I have no idea why.
On my screen it would appear as "My", instead of "My street 14". And that is my problem.
Does anyone have any clue as to why this is happening?
Rewrite your function like this
function getUserAddress($userid)
{
$con=mysqli_connect("server","user","pass","dbname");
$users_result = mysqli_query($con,"SELECT * FROM table blabla");
while($row = mysqli_fetch_array($users_result)) {
$str.=$row['column_to_echo']." ";
}
mysqli_close($con);
return($str);
}
Problem :
You were actually making use of a return inside the while loop which just returned the first value.
Try this instead:
function getUserAddress($userid)
{
$con=mysqli_connect("server","user","pass","dbname");
$users_result = mysqli_query($con,"SELECT `column` FROM table blabla");
$row = mysqli_fetch_row($users_result)
mysqli_close($con);
return $row;
}
Let me know if that works.

How can i show only hour and minutes?

I am working in php in which i am using mysql.
This is my function which is returning result in json format.
function getTiming($placeId) {
$sql = "SELECT * from place_timing where placeId='$placeId'";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
if (mysql_num_rows($result)==0)
{
echo '['.json_encode(array('placeId' => 0)).']';
//this is for null result
}
else
{
while($row = mysql_fetch_assoc($result))
{
$records[] = $row;
}
echo json_encode($records); //this concerts in json
}
}
output of this function is like this:-
[{"placeId":"31","sun_open_time":"00:00:00","sun_close_time":"00:00:00","mon_open_time":"00:00:00","mon_close_time":"23:00:00","tue_open_time":"00:00:00","tue_close_time":"00:00:00"}]
But I want to show only hour:minutes. means I don't want to show seconds.
please suggest me how can I change my above function so I can show only hour:minutes.
Thank you in advance.
There are many ways to do it, the "cleanest" would be to specify the columns in the SELECT clause and pass the dates with DATE_FORMAT() like this: DATE_FORMAT(sun_open_time, '%H:%i').
Adjust your query to select the actual fields, rather then * and then use TIME_FORMAT() on the time fields, like:
SELECT TIME_FORMAT(`sun_open_time`, '%H %i') AS `opentime`;
That will return the desired values directly from the query without any PHP hacks.
It seems your fields of table place_timing (sun_open_time, sun_close_time and so on..) have only hh:mm:ss formated time. so you have to use SUBSTRING() function of MySql.
So you query could be as follows.
$sql = "SELECT SUBSTRING(sun_open_time,1,5),
SUBSTRING(sun_close_time,1,5), SUBSTRING(mon_open_time,1,5),
SUBSTRING(mon_close_time,1,5),
SUBSTRING(tue_open_time,1,5),SUBSTRING(tue_close_time,1,5) from
place_timing where placeId='$placeId'";

Having trouble echoing different data using the function method

I'm writing a PHP file which will putt from multiple table rows, data which it must echo on one page.
I wrote a function command because I a loop wont work as the information isn't outputting in the same manner every time.
here is how it looks so far.
include("dbconnect.php");
function get_table_data($id)
{
$row = mysql_query('SELECT row FROM table WHERE id = '.$id.'');
$row2 = mysql_fetch_array($row);
};
$sss = 18; // this is the ID
echo get_table_data($sss);
My issue is that nothing echos and I have no errors
first of all, you need to return something:
function get_table_data($id) {
$row = mysql_query('SELECT row FROM table WHERE id = '.$id.'');
return mysql_fetch_array($row);
}
then, you need to access the row:
$result = get_table_data($sss);
echo $result['row'];
Hope this helps!
Your function get_table_data should return some value to be echoed in your statement echo get_table_data($sss);

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