Integrating PHP functions with a database - php

I just submitted my work and my course leader has asked me to use PHP functions to query my database. How can I do this? Is it possible to add just "function getRooms" before my queries, and return the desired result. I need thorough briefing on functions with MySQL.
For example:
How will I add a function to this code:
<?php
// By Kelvin
include ("player.php");
$result = mysql_query("SELECT * FROM phplogin WHERE username = '$username'");
$row = mysql_fetch_assoc($result);
$medipack = $row['medipack'];
if ($_POST['object'] == "Use Medipack") {
if ($medipack != 0) {
mysql_query("UPDATE phplogin SET score = score + 50, health = health + 50, medipack = medipack - 1
WHERE username = '$username'");
echo ("<P>Medipack Used!</P>");
$RoomNumber =5;
}
else {
echo ("<P>You're all out of medipacks!</P>");
}
}
?>

If he's looking for a level of abstraction between the rest of your code and the code accessing the database, wrapping the database logic in functions should be on the right path:
function getRooms($link){
$sql = "SELECT * FROM rooms";
$data = array();
if($set = mysql_query($sql)){
while($row = mysql_fetch_assoc($set)){
$data[] = $row;
}
}
return empty($data)
? null
: $data;
}
$db_connection = mysql_connect('host', 'user', 'pass');
mysql_select_db('name', $db_connection);
$rooms = getRooms($db_connection);
Wrapping these functions into a class, and accessing them by methods is another step, as the instantiated object can manage its own connection, etc., but that may be a step further than necessary. Other functions (based on what I can guess) might be:
function getRoomById($link, $id){ }
function getRoomsByName($link, Array $names){ }

I would imagine your course leader is referring to the PHP's native MySQL functions - http://php.net/manual/en/book.mysql.php

You can wrap your queries inside PHP functions. For example, like this:
function &getRooms(){
$query="SELECT id,name FROM rooms";
$result=mysql_query($query);
$ar_out=array();
while ($row = mysql_fetch_assoc($result)) {
$ar_out[]=$row;
}
return $ar_out;
}
This said, you really should find a tutorial or a book on how to use MySQL and PHP together. There are many things to know about code organization and performance.

Related

how to get db all data using array in php

I create as the following function. how to get all data using this array. when run this function will appear only the first record. but, i want it to appear all the records. what is the error in this code.
public function get_All_Se($stId){
$query = "SELECT * FROM session WHERE stId = '$stId'";
$result = $this->db->query($query) or die($this->db->error);
$data = $result->fetch_array(MYSQLI_ASSOC);
return $data;
}
public function get_All_Se($stId){
$rows=array();
$query = "SELECT * FROM session WHERE stId = '$stId'";
$result = $this->db->query($query) or die($this->db->error);
while($data= $result->fetch_assoc()){
$rows[]=$data;
}
return $rows;
}
Run loop over all results and add to some return array.
$rows = array();
while(($row = $result->fetch_array($result))) {
$rows[] = $row;
}
As the documentation of mysqli::fetch_array() explains, it returns only one row (and not an array containing all the rows as you might think).
The function you are looking for is mysqli::fetch_all(). It returns all the rows in an array.
public function get_All_Se($stId)
{
$query = "SELECT * FROM session WHERE stId = '$stId'";
$result = $this->db->query($query) or die($this->db->error);
return $result->fetch_all(MYSQLI_ASSOC);
}
The code above still has two big issues:
It is open to SQL injection. Use prepared statements to avoid it.
or die() is not the proper way to handle the errors. It looks nice in a tutorial but in production code it is a sign you don't care about how your code works and, by extension, what value it provides to their users. Throw an exception, catch it and handle it (log the error, put some message on screen etc) in the main program.
Try this way...
<?php
// run query
$query = mysql_query("SELECT * FROM <tableName>");
// set array
$array = array();
// look through query
while($row = mysql_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
// OR just echo the data:
echo $row['<fieldName>']; // etc
}
// debug:
print_r($array); // show all array data
echo $array[0]['<fieldName>'];
?>

Looping through MySQL results and saving values to a $_SESSION

I am trying to store each column name in my database into its own $_SESSION. For example, say my column names are column_one, column_two, column_three, column_four, and column_five. I want these to be stored in a $_SESSION like $_SESSION['column_one'], $_SESSION['column_two'], etc. I am trying to do this in a loop but I have not been successful. How would I setup the loop to achieve this?
$query = "SELECT * FROM table WHERE user_id = $id";
$result = mysqli_query($dbc, $query);
$num = mysqli_num_rows($result);
if ($num == 1) {
//User was found
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$_SESSION['user_id'] = $row['user_id'];
}
}
Could you try this:
$id = mysqli_real_escape_string($dbc,$id);
$query = "SELECT * FROM table WHERE user_id = $id";
$result = mysqli_query($dbc, $query);
$num= mysqli_num_rows(result);
if ($num == 1) {
$row = mysqli_fetch_assoc($result);
$_SESSION['UserData'] = $row;
}else{
//handle error or user not found
}
echo '<pre>';
print_r($_SESSION['UserData']);
echo '</pre>';
You don't have necessity of use while or another loop, so is just one row
Something like this should work:
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
foreach($row as $column => $value) {
$_SESSION[$column] = $value;
}
}
Extra advice for safeguarding against SQL injection, the following two lines:
$id = mysqli_real_escape_string($dbc, $id);
$query = "SELECT * FROM table WHERE user_id = '$id'";
Update:
Thanks to EmilioGort who pointed out the missing connection parameter in mysqli_real_escape_string. See mysqli_real_escape_string docs.
While the other answers proposed a way to do, I'd strongly propose to not do this at all. Why?
First of all $row contains all details of the user in a well defined array form. It is generally good to keep this structure well prepared.
More important: Flattening $row might force name clashes like so:
Suppose $row has a property userName and somewhere else in your application you eventually set
$_SESSION[ 'userName' ] = $newUserName;
The new assignment to $_SESSION[ 'userName' ] might unintentionally change the property saved during the login process.
You might argue "Right now, my code doesn't use userName in $_SESSION'. Right! Unfortunately, you might use just this name for something else many month later on...
A better solution
I'd save the user detail like this:
$_SESSION[ 'sys$userDetails' ] = $row;
Imagine the prefix sys$ as being an indicator for framework generated properties of your session.
Thus, business logic related session data shouldn't have the sys$ prefix.

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 query function / class

It must be Monday, the heat or me being stupid (prob the latter), but for the life of me I cannot get a simple php function to work.
I have a simple query
$sql = mysql_query("SELECT * FROM table WHERE field_name = '$input'");
Which I want to run through a function: say:
function functionname($input){
global $field1;
global $field2;
$sql = mysql_query("SELECT * FROM table WHERE field_name = '$input'");
while($row = mysql_fetch_array($sql)) :
$field1[] = $row['field1'];
$field2[] = $row['field2'];
endwhile;
mysql_free_result($sql);
}
So that I can call the function in numerious places with differeing "inputs". Then loop through the results with a foreach loop.
Works fine the first time the function is called, but always gives errors there after.
As said "It must be Monday, the heat or me being stupid (prob the latter)".
Suggestions please as I really only want 1 function to call rather than rewrite the query each and every time.
This is the error message
Fatal error: [] operator not supported for strings in C:\xampp\htdocs\functions.php on line 270
function functionname($input){
$sql = mysql_query("SELECT field1,field2 FROM table WHERE field_name = '$input'");
$result = array('field1' => array()
'field2' => array()
);
while($row = mysql_fetch_array($sql)) :
$result['field1'][] = $row['field1'];
$result['field2'][] = $row['field2'];
endwhile;
mysql_free_result($sql);
return $result;
}
it seems that somewhere the $field1 or $field2 are converted to strings and you cant apply the [] to a string...
i'd say that you have to do:
$field1 = array();
$field2 = array();
before the WHILE loop
The problem is that you so called arrays are strings!
global $field1;
global $field2;
var_dump($feild1,$feild2); //Will tell you that there strings
Read the error properly !
[] operator not supported for strings
And the only place your using the [] is withing the $feild - X values
GLOBAL must work because the error is telling you a data-type, i.e string so they must have been imported into scope.
another thing, why you selecting all columns when your only using 2 of them, change your query to so:
$sql = mysql_query("SELECT feild1,feild2 FROM table WHERE field_name = '$input'");
another thing is that your using mysql_fetch_array witch returns an integer indexed array, where as you want mysql_fetch_assoc to get the keys.
while($row = mysql_fetch_assoc($sql)) :
$field1[] = $row['field1'];
$field2[] = $row['field2'];
endwhile;
What I would do
function SomeFunction($variable,&$array_a,&$array_b)
{
$sql = mysql_query("SELECT field1,field2 FROM table WHERE field_name = '$variable'");
while($row = mysql_fetch_assoc($sql))
{
$array_a[] = $row['field1'];
$array_b[] = $row['field2'];
}
mysql_free_result($sql);
}
Then use like so.
$a = array();
$b = array();
SomeFunction('Hello World',&$a,&$b);
In my opinion, it's pretty unusual and even useless approach at all.
This function is too localized.
To make a general purpose function would be a way better.
<?
function dbgetarr(){
$a = array();
$query = array_shift($args);
foreach ($args as $key => $val) {
$args[$key] = "'".mysql_real_escape_string($val)."'";
}
$query = vsprintf($query, $args);
$res = mysql_query($query);
if (!$res) {
trigger_error("dbgetarr: ".mysql_error()." in ".$query);
return FALSE;
} else {
while($row = mysql_fetch_assoc($res)) $a[]=$row;
}
return $a;
}
and then call it like this
$data = dbgetarr("SELECT field1,field2 FROM table WHERE field_name = %s",$input);
foreach ($data as $row) {
echo $row['field1']." ".$row['field1']."<br>\n";
}
To understand your issue, we need the error, however, are you sure you are going about this in the right way?
Why do you need to call the function multiple times if you are just changing the value of the input field?
You could improve your SQL statement to return the complete result set that you need the first time.. i.e. SELECT * FROM table GROUP BY field_name;
Not sure if that approach works in your scenario, but in general you should aim to reduce the number of round trips to your database.
I don't know, i right or not. But i advise to try this:
function functionname($input){
global $field1;
global $field2;
$sql = mysql_query("SELECT * FROM `table` WHERE `field_name` = '" . $input . "'");
while($row = mysql_fetch_assoc($sql)) :
$field1[] = $row['field1'];
$field2[] = $row['field2'];
endwhile;
mysql_free_result($sql);
}

How do you create a simple function to query the database? Mine isn't working!

I want to make a simple function that I can call on to query my database. I pass the "where" part of the query to it and in the code below, my $q variable is correct. However, what should I then do to be able to use the data? I'm so confused at how to do something I'm sure is extremely easy. Any help is greatly appreciated!
function getListings($where_clause)
{
$q = "SELECT * FROM `listings` $where_clause";
$result = mysql_query($q,$dbh);
foreach (mysql_fetch_array($result) as $row) {
$listingdata[] = $row;
}
return $listingdata;
}
Your function should be like this:
function getListings($where_clause, $dbh)
{
$q = "SELECT * FROM `listings` $where_clause";
$result = mysql_query($q, $dbh);
$listingdata = array();
while($row = mysql_fetch_array($result))
$listingdata[] = $row;
return $listingdata;
}
Improvements over your function:
Adds MySQL link $dbh in function arguments. Passit, otherwise query will not work.
Use while loop instead of foreach. Read more here.
Initialize listingdata array so that when there is no rows returned, you still get an empty array instead of nothing.
Do you have a valid db connection? You'll need to create the connection (apparently named $dbh) within the function, pass it in as an argument, or load it into the function's scope as a global in order for $result = mysql_query($q,$dbh); to work.
You need to use while, not foreach, with mysql_fetch_array, or else only the first row will be fetched and you'll be iterating over the columns in that row.
$q = "SELECT * FROM `listings` $where_clause";
$result = mysql_query($q,$dbh);
while (($row = mysql_fetch_array($result)) != false)
{
$listingdata[] = $row;
}
Always add error handling in your code. That way you'll see what is going wrong.
$result = mysql_query($q,$dbh);
if (!$result) {
trigger_error('Invalid query: ' . mysql_error()." in ".$q);
}
Here is a function which will save you some time. First Argument tablename, then condition(where), fields and the order. A simple query will look like this : query_db('tablename');
function query_db($tbl_name,$condition = "`ID` > 0",$fields = "*",$order="`ID` DESC"){
$query="SELECT ".$fields." FROM `".$tbl_name."` WHERE ".$condition." ORDER BY".$order;
$query=$con->query($query);
$row_data=array();
while($rows = $query->fetch_array()){
$row_data[] = $rows;
}
return $row_data;
}

Categories