PHP OOP Mysql Query - php

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 :-)

Related

How to use the same variable in a loop

I have set up a MySql database containing several tables (needed for uploading tons of data that is entered in excel). I would like to use each table name as a variables that automatically updates each time a new table is added to the database. However, I don't know how to prevent PHP from overwriting my $tableName variable in loops. This is what I got so far:
<?php
if (!mysql_connect($host, $username, $password)) {
echo 'Could not connect to mysql';
exit;
}
$sql = "SHOW TABLES FROM $database";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_row($result)) {
$tableName = $row[0];
include('../design.php');
}
?>
In other words: On the frontpage of the website I would like to include data from every single database table. I have organized a framework for extracting that data and presenting it neatly in design.php. However, this file makes use of the $tableName variable for extracting the data and I think that variable is being overwritten at each loop causing the error (only the number one table will be displayed).
Instead, if I just separate the code in their own php objects, then everything works just fine:
<?php
$tableName = tablename1;
include('../design.php');
?>
<?php
$tableName = tablename2;
include('../design.php');
?>
etc..
Can anyone explain to me how this works? Or if there is some smarter way of doing things?
Thanks in advance!
include the design.php file at the beginning of the script. Inside this file, define a function.
function doSomethingWithTableName ($table)
{
// do something with it
}
Then, in your frontend file, you would do this:
$sql = "...";
$result = mysql_query ($sql);
while ($row = mysql_fetch_row($result))
{
$processed_data = doSomethingWithTableName ($row[0]);
// do something with $processed_data
}
Hope this helps.
I've no idea what's inside design.php but instead of including it inside the loop I'd create a function, something like:
function designFunction($tableName){
//put the design.php here
return $something;
}
Now use the designFunction inside your loop
while ($row = mysql_fetch_row($result)) {
$tableName = $row[0];
$someResult = designFunction($tableName);
//etc...
}

While loop inside a while loop in two different functions?

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!

Using a variable outside of the while loop (scope)

Small problem regarding scope in PHP, I can't seem to call the variable $report outside of the while loop. I have tried various things, including return. This doesn't work, the only two functions that work here are if I echo the variable $report inside the loop, or if I print it. Which I do not want to do, although it solves the problem, but I don't want random gibberish on the user's screen.
I have been looking around for the last 15 or so minutes, and I haven't seen any problems quite like this one on here.
Any help would be appreciated.
<?
require "functions2.php";
require "members.php";
$query = "SELECT MAX(DOCid) as prevDOCid from reports";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$prevDOCid = $row[prevDOCid];
$thisDOCid = $prevDOCid+1;
$report = "a"."b".$thisDOCid;
}
echo $report;
?>
You could try to define the variable before the loop, e.g.
$report = "";
while ($row = mysql_fetch_array($result)) {
$report .= "a"."b".$row["prevDOCid"]+1;
}
echo $report;
I hope this helps you!
Edit Use .= not +=

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

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