PHP echo query result in Class? - php

I have a question about PHP Class. I am trying to get the result from Mysql via PHP. I would like to know if the best practice is to display the result inside the Class or store the result and handle it in html.
For example, display result inside the Class
class Schedule {
public $currentWeek;
function teamQuery($currentWeek){
$this->currentWeek=$currentWeek;
}
function getSchedule(){
$connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$connection) {
die("Database connection failed: " . mysql_error());
}
$db_select = mysql_select_db(DB_NAME,$connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
$scheduleQuery=mysql_query("SELECT guest, home, time, winner, pickEnable FROM $this->currentWeek ORDER BY time", $connection);
if (!$scheduleQuery){
die("database has errors: ".mysql_error());
}
while($row=mysql_fetch_array($scheduleQuery, MYSQL_NUMS)){
//display the result..ex: echo $row['winner'];
}
mysql_close($scheduleQuery);
//no returns
}
}
Or return the query result as a variable and handle in php
class Schedule {
public $currentWeek;
function teamQuery($currentWeek){
$this->currentWeek=$currentWeek;
}
function getSchedule(){
$connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$connection) {
die("Database connection failed: " . mysql_error());
}
$db_select = mysql_select_db(DB_NAME,$connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
$scheduleQuery=mysql_query("SELECT guest, home, time, winner, pickEnable FROM $this->currentWeek ORDER BY time", $connection);
if (!$scheduleQuery){
die("database has errors: ".mysql_error());
// create an array }
$ret = array();
while($row=mysql_fetch_array($scheduleQuery, MYSQL_NUMS)){
$ret[]=$row;
}
mysql_close($scheduleQuery);
return $ret; // and handle the return value in php
}
}
Two things here:
I found that returned variable in php is a little bit complex to play with since it is two dimension array. I am not sure what the best practice is and would like to ask you experts opinions.
Every time I create a new method, I have to recreate the $connection variable: see below
$connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$connection) {
die("Database connection failed: " . mysql_error());
}
$db_select = mysql_select_db(DB_NAME,$connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
It seems like redundant to me. Can I only do it once instead of calling it anytime I need a query? I am new to php class. hope you guys can help me. thanks.

I treat classes like these as 'accessors' so they purely query the database and return the result. That way any PHP code which calls it can do whatever it likes with it. this may be displaying or it may be a check or it may be an update. This is good design as it separates the datastore from the logic from the display and means your code will be more flexible. But yes, it is a little more complex.
In regards to re-creating the connection each time. This may or may not be necessary. Depending on your setup you may be able to create a connection pool. To make it easier for you for now, you can abstract the creation of a connection to its own method. This way you only need to call this method at the start to get a connection handle. This saves you from having many copies of the same code all over the place.
If you are new to PHP classes I suggest doing a bit of research on object oriented design. This will give you an idea on why it would be beneficial to abstract some functions, and also why you would want to return the results instead of displaying them.

Its probably a bad idea to echo the result int he class nstead you should return the result or result set for echoing else where.
May the connection a mebmer of the class like:
protected $_connection = null;
Then in your constructor you can assign the database connection. Though normally your db connection would be wrapped by yet another class.
Additionally if i were you i would not use the mysql functions. Instead use the Mysqli or PDO_Mysql drivers. They encapsulate all this functionality in an object orientend manner by default. You can then extend those classes with your custom functionality instead of working from scratch.

Related

Query two databases with the same query

I need to run the same query on two different databases.
I edited my previous db class obtaining this
class Db {
function connect() {
$db = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("Error");
mysql_select_db(DB_NAME, $db);
return $db;
}
function connect2() {
$db = mysql_connect(DB_HOST2, DB_USER2, DB_PASSWORD2) or die("Error 2");
mysql_select_db(DB_NAME2, $db);
return $db;
}
function sql_query($sql) {
$result = mysql_query($sql, $this->connect()) or die(mysql_error());
$result2 = mysql_query($sql, $this->connect2()) or die(mysql_error());
} }
Is there a way to avoid the connection to the databases each time? I already tried using $GLOBALS to save the database links but it doesn't seem to work.
Thanks a lot
Take a look at the PHP PDO manual
http://www.php.net//manual/en/book.pdo.php
Using PDO you can make two connections at the same time then you can run two queries on two different databases too ;)
You could use mysql_pconnect() which will establish a persistent connection to your MySQL database. You could then save the link for future reference.
See http://www.php.net/manual/en/function.mysql-pconnect.php for more details.

PHP mysql_connection close

I am new to PHP but I am strong in classic ASP, so I am based on classic ASP to learn and pickup PHP.
Since I have only one database to connect, so I created a function to connect to it and return record set, then I want to close the record set after I finished with it. (I am following my classic ASP practice)
I made a function to connect to ODBC then the function will return the RS as follow:
function connection_open($strSQL)
{
$conn=odbc_connect('dbreadonly','dbreadonly','readonly');
if (!$conn)
{exit("Connection Failed: " . $conn);}
$myRS=odbc_exec($conn,$strSQL);
return $myRS;
}
$sql="SELECT * FROM TblUsers";
$rs=connection_open($sql);
if (!$rs)
{exit("Error in SQL");}
while (odbc_fetch_row($rs))
{
$username=odbc_result($rs,"UserName");
echo "<td>$username</td></tr>";
}
Now, how do I close the connection if outside the function?

PHP: Close mysql connection when using external connection file

So most basic php/mysql examples show something like this (taken from W3 Schools as a laymans example):
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
mysqli_close($con);
?>
When using external connection files, what is the correct way to close the connection (if needed at all).
Eg. We separate the above into a connection.php file which contains
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
And then have a Query.php file that contains:
<?php
require('connection.php');
$result = mysqli_query($con,"SELECT * FROM Persons");
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
?>
Is it necessary to close the connection. Should there be a mysqli_close($con); at the end of the query.php file, or does it go at the end of the connection.php file and theres some sort of way to link that the query.php file will run before the connection is closed?
And/or is closing the connection even needed? Does it just close automatically after the script is complete?
Open connections (and similar resources) are automatically destroyed at the end of script execution. However, you should still close or free all connections, result sets and statement handles as soon as they are no longer required. This will help return resources to PHP and MySQL faster.
Still, if your PHP script takes lots of time to execute, it's a good idea to close the connection when you don't have to do any request to the database anymore -- at least, if the long calculations are done after the queries.
This is especially true if your application is deployed on a shared hosting : your user account can generally only have a few connections opened at the same time. (That number of simultaneous opened connections can be pretty small on shared hosting ; it's generally bigger on private servers).
The reason we often don't close connections ourselfves is :
we generally don't really know when we have done all our queries --
this is especially true with pages that are made of lots of small
"blocks" ; each one of those is independant from the others, and can
do queries on its own ; so, when can we close the connection ?
web pages are generally quite fast to generate, so we don't really
bother about closing the connection to DB.
I think this may help you to resolve your problem.
It's better to use a class which perhaps extends Mysqli, for ie:
<?php
// Database class
class Database extends \mysqli
{
public function __construct($host, $user, $pass, $db)
{
//create connection
}
public function __destruct()
{
//close connection
//will call this function when class closes or PHP stops
}
}
//using the database
$db = new Database('localhost', 'user', 'pass', 'db');
$db->query("SELECT ....");

taking data from different tables and different dbs

I want to retrieve two different fields residing in different data bases. My db connection settings are this:
define ('DB_HOST', 'ipaddress1');
define ('DB_USER', 'username1');
define ('DB_PASSWORD', 'password1');
define ('DB_DATABASE', 'ecbooks');
$db_wink = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD, TRUE) or die("Connection Error: " . mysql_error());
mysql_select_db(DB_DATABASE) or die("Error connecting to Winkstore DB. " . mysql_error());
// DB configuration parameters : magonwink
define ('DB_REMOTE_HOST', 'ipaddress2');
define ('DB_REMOTE_USER', 'username2');
define ('DB_REMOTE_PASSWORD', 'password2');
define ('DB_REMOTE_DATABASE', 'magsonwink');
$db_magson = mysql_connect(DB_REMOTE_HOST, DB_REMOTE_USER, DB_REMOTE_PASSWORD, TRUE) or die("Connection Error: " . mysql_error());
mysql_select_db(DB_REMOTE_DATABASE, $db_magson) or die("Error connecting to magson wink DB. " . mysql_error());
define ('CMS_DB_HOST', 'ipaddress3');
define ('CMS_DB_USER', 'username3');
define ('CMS_DB_PASSWORD', 'password3');
define ('CMS_DB_DATABASE', 'mawinkcms');
$db_rp = mysql_connect(CMS_DB_HOST, CMS_DB_USER, CMS_DB_PASSWORD, true) or die("Connection Error: " . mysql_error());
mysql_select_db(CMS_DB_DATABASE, $db_rp) or die("Error connecting to DB. " . mysql_error());
but when I used this query
SELECT ecbooks.user.user_name AS field1, mawinkcms.purchase.USER_NAME AS field2 FROM ecbooks.user,mawinkcms.purchase
$result = mysql_query($query, $db_wink) or die("Couldn't execute query: " . mysql_error());
while($row = mysql_fetch_assoc($result)){
$users[] = $row;
}
I got an error could not execute the query. Thanks in advance.
You have to pass the correct link identifier to the mysql_query function as the second parameter: http://www.php.net/mysql_query
$ecbooks does not exist (based on the code you provided).
In your case if the table you want to access is in the ecbooks database, you have to pass $db_wink to mysql_query.
But since you are trying to access two different databases in the same query, you will have to connect to the database with a user that has access to both databases. Posting the actual error you get would also help.
ps: please stop usingng this extension to access MySQL. See here for details.
Firstly, when asking for help with an error, it's a good idea to include the error itself.
Secondly, your query doesn't appear to have a join condition, so you will get back the cartesian product if you do get it to go - that's probably not what you want.
Thirdly, when running a query, it runs against the database you connected to, regardless of whether you've connected to any others. So, in your example, you're running a query against $db_wink; the other two connections don't affect this at all.
For the query to work, the user who connected to $db_wink needs to have permissions on the databases ecbooks and mawinkcms, and mawinkcms must be running on the same server as ecbooks.
I'm guessing that either the permissions are not set up, or you're running them on different databases.

How do I create a database if it doesn't exist, using PHP?

How do I create a database if it doesn't exist, using PHP?
Presuming you're talking about a MySQL database - you want to use mysql_query and mysql_select_db.
Note that mysql_create_db is deprecated.
<?php
// Connect to MySQL
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// Make my_db the current database
$db_selected = mysql_select_db('my_db', $link);
if (!$db_selected) {
// If we couldn't, then it either doesn't exist, or we can't see it.
$sql = 'CREATE DATABASE my_db';
if (mysql_query($sql, $link)) {
echo "Database my_db created successfully\n";
} else {
echo 'Error creating database: ' . mysql_error() . "\n";
}
}
mysql_close($link);
?>
Since you mention WAMP I'll assume you're talking about MySQL.
It can be tricky. Assuming that your PHP script runs with all the required credentials (which is by itself a questionable idea), you can run this query:
SHOW DATABASES
If the DB does not show up there, you can assume it doesn't exist and create it with one of these queries:
CREATE DATABASE foo ....
or:
CREATE DATABASE IF NOT EXISTS foo ...
Right after that, you need to check the return value for whatever PHP function you are using (e.g. mysql_query). The above queries will fail if your user is now allowed to see all the existing databases or it's not allowed to create new databases.
In general, I find the whole concept kind of scary. Handle it with care! ;-)

Categories