PHP - Passing Mysqli Connection To A Class.
Hey Guys, So I am working on implementing zip codes to my database. I found a zip code calculator script, and I am forced to pass the database connection to the class. Although, I realize I use a mysqli connection and the zipcodes class uses mysql...
Appreciate if anyone could assist me in solving my issue. THANKS! ERRORS... Quote Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in /home/bleeping/public_html/gregstechservices.com/gregphp/ZipCodesRange.class.php on line 287 Warning: mysql_errno(): supplied argument is not a valid MySQL-Link resource in /home/bleeping/public_html/gregstechservices.com/gregphp/ZipCodesRange.class.php on line 289 Warning: mysql_error(): supplied argument is not a valid MySQL-Link resource in /home/bleeping/public_html/gregstechservices.com/gregphp/ZipCodesRange.class.php on line 289 MySql Error #: zip.php <?php require_once("class/mysql_connect.php"); $mysql = New MySQL(); require_once("ZipCodesRange.class.php"); //initialization, pass in DB connection, from zip code, distance in miles. $zip = new ZipCodesRange($mysql,'98303',50); //configuration $zip->setTableName('zipcodes'); //optional, default is zips. $zip->setZipColumn('ZipCode'); //optional, default is zip. $zip->setLonColumn('Longitude'); //optional, default is lon. $zip->setLatColumn('Latitude'); //optional, default is lat. //do the work $zip->setZipCodesInRange(); //call to initialize zip array //zip code output, other processing can be done from this array. $zipArray = $zip->getZipCodesInRange(); echo '<pre>'; print_r($zipArray); echo '</pre>'; ?> mysql_connect.php <?php require_once ("includes/constants.php"); class MySQL { private $conn; /** * MySQL::__construct() * * @return */ function __construct() { $this->conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME) or die("Problem connecting to database"); $dbc = $this->conn; } /* * Query the database * Example: $result = $mysql->query($q); */ /** * MySQL::query() * * @param mixed $q * @return */ function query($q) { return $this->conn->query($q); } ...CONTINUED ZipCodesRange.class.php <?php /** * Class to find zip codes within an approximate * distance of another zip code. This can be useful * when trying to find retailers within a certain * number of miles to a customer. * * This class makes some assumptions that I consider * pretty safe. First it assumes there is a database * that houses all of the zip code information. * Secondly it assumes there is a way to validate a * zip code for a given country. It makes one bad * assumption and that is that the world is flat. See * comments below for an explanation. * * @author Scott Mattocks * @created 2004-05-03 * @updated 2004-05-14 * @updated 2006-05-22 - MySQL Conversion by Allan Bogh * - Added precisionDistance() function to make calculations * more accurate (within 2 miles). * - Modified class initialization to make custom database settings * more effective. * New initialization steps: * $zip = new ZipCodesRange($appconf['dbconnection'],'98303',50); * $zip->setTableName('zip_codes'); //optional * $zip->setZipColumn('zip'); //optional * $zip->setLonColumn('longitude'); //optional * $zip->setLatColumn('latitude'); //optional * $zip->setZipCodesInRange(); //call to initialize zip array * echo '<pre>'; * print_r($zip->getZipCodesInRange()); * echo '</pre>'; */ class ZipCodesRange { /** * The conversion factor to go from miles to degrees. * @var float */ var $milesToDegrees = .01445; /** * The zipcode we are starting from. * @var string */ var $zipCode; /** * The maximum distance in miles to return results for. * @var float */ var $range; /** * The country the zip code is in. * @var string Two character ISO code. */ var $country; /** * The result of our search. * array(zip1 => distance, zip2 =>distance,...) * @var array */ var $zipCodes = array (); /** * The database table to look for zipcodes in. * @var string */ var $dbTable = 'zips'; /** * The name of the column containing the zip code. * @var string */ var $dbZip = 'zip'; /** * The name of the column containing the longitude. * @var string */ var $dbLon = 'lon'; /** * The name of the column containing the latitude. * @var string */ var $dbLat = 'lat'; var $db; /** * Constructor. Calls initialization method. * * @access private * @param resource $db The link identifier for the database. * @param string $zipCode * @param float $range * @param string $country Optional. Defaults to US. * @return object */ function ZipCodesRange($db, $zipCode, $range, $country = 'US') { $this->_initialize($db, $zipCode, $range, $country); } /** * Initialization method. * Checks data and sets member variables. * * @access private * @param resource $db The link identifier for the database. * @param string $zipCode * @param float $range * @param string $country Optional. Defaults to US. * @return boolean */ function _initialize($db, $zipCode, $range, $country) { //set up the database connection $this->db = $db; // Check the country. if ($this->validateCountry($country)) { $this->country = $country; } else { trigger_error('Invalid country: ' . $country); return FALSE; } // Check the zipcode. if ($this->validateZipCode($zipCode, $country)) { $this->zipCode = $zipCode; } else { trigger_error('Invalid zip code: ' . $zipCode); return FALSE; } // We don't need a special method to check the range. if (is_numeric($range) && $range >= 0) { $this->range = $range; } else { trigger_error('Invalid range: ' . $range); return FALSE; } // Set up the zip codes. //return $this->setZipCodesInRange(); } /** * Get all of the zip codes from the database. * Currently this method is called on construction but * it doesn't have to be. * * @access public * @return boolean */ function setZipCodesInRange() { // First check that everything is set. if (!isset($this->zipCode) || !isset($this->range) || !isset($this->country)) { trigger_error('Cannot get zip codes. Class not initialized properly.'); return FALSE; } // Get the max longitude and latitude of the starting point. $maxCoords = $this->getRangeBox(); // The query. $query = 'SELECT ' . $this->dbZip . ', ' . $this->dbLat . ', '; $query.= $this->dbLon . ' '; $query.= 'FROM ' . $this->dbTable . ' '; $query.= ' WHERE '; $query.= ' (' . $this->dbLat . ' <= ' . $maxCoords['max_lat'] . ' '; $query.= ' AND '; $query.= ' ' . $this->dbLat . ' >= ' . $maxCoords['min_lat'] . ') '; $query.= ' AND '; $query.= ' (' . $this->dbLon . ' <= ' . $maxCoords['max_lon'] . ' '; $query.= ' AND '; $query.= ' ' . $this->dbLon . ' >= ' . $maxCoords['min_lon'] . ') '; // Query the database. $qry = mysql_query($query,$this->db); // Check for errors. if (!$qry) { trigger_error('MySQL Error #'.mysql_errno($this->db).': '.mysql_error($this->db), E_USER_ERROR); } // Process each row. while ($result = mysql_fetch_array($qry)) { // Get the distance form the origin (imperfect see below). $distance = $this->precisionDistance($result[$this->dbLat], $result[$this->dbLon]); // Double check that the distance is within the range. if ($distance < $this->range) { // Add the zip to the array $this->zipCodes[$result[$this->dbZip]] = $distance; } } return TRUE; } /** * Return the array of results. * * @access public * @param none * @return &array */ function &getZipCodesInRange() { return $this->zipCodes; } /** * Calculate the distance from the coordinates are from the * origin zip code. * * The method is quite imperfect. It assumes as flat Earth. * The values are quite accurate (depending on the conversion * factor used) for zip codes close to the equator. I found * some crazy formula for calulating distance on a sphere * but I am not good enough at calculus to convert that into * working code. * * @access public * @param float $lat The latitude you want to know the distance to. * @param float $lon The longitude you want to know the distance to. * @param float $zip The zip code you want to know the distance from. * @param int $percision The number of decimals places in the distance. * @return float The distance from the zip code to the coordinates. */ function calculateDistance($lat, $lon, $zip = NULL, $percision = 2) { // Check the zip first. if (!isset ($zip)) { // Make it default to the origin zip code. // Could be used to calculate distances from other points. $zip = $this->zipCode; } // Get the coordinates of our starting zip code. list ($starting_lon, $starting_lat) = $this->getLonLat($zip); // Get the difference in miles for both coordinates. $diffLonMiles = ($starting_lon - $lon) / $this->milesToDegrees; $diffLatMiles = ($starting_lat - $lat) / $this->milesToDegrees; // Calculate the distance between two points. $distance = sqrt(($diffLonMiles * $diffLonMiles) + ($diffLatMiles * $diffLatMiles)); // Return the distance rounded to the defined percision. return round($distance, $percision); } /** * See the report for calculateDistance function. */ function precisionDistance($lat, $lon, $zip = NULL, $precision = 2){ $earthsradius = 3963.19; // Check the zip first. if (!isset ($zip)) { // Make it default to the origin zip code. // Could be used to calculate distances from other points. $zip = $this->zipCode; } // Get the coordinates of our starting zip code. list ($starting_lon, $starting_lat) = $this->getLonLat($zip); $pi = pi(); $c = sin($starting_lat/(180/$pi)) * sin($lat/(180/$pi)) + cos($starting_lat/(180/$pi)) * cos($lat/(180/$pi)) * cos($lon/(180/$pi) - $starting_lon/(180/$pi)); $distance = $earthsradius * acos($c); return round($distance,$precision); } /** * Get the longitude and latitude for a single zip code. * * @access public * @param string $zip The zipcode to get the coordinates for. * @return array Numerically index with longitude first. */ function getLonLat($zip) { // Get the longitude and latitude for the zip code. $query = 'SELECT ' . $this->dbLon . ', ' . $this->dbLat . ' '; $query.= 'FROM ' . $this->dbTable . ' '; $query.= 'WHERE ' . $this->dbZip . ' = \'' . addslashes($zip) . '\' '; $qry = mysql_query($query,$this->db); if(!$qry){ echo "MySql Error #".mysql_errno($this->db).': '.mysql_error($this->db).'<br>'; die; } return mysql_fetch_array($qry); } /** * Check to see if the country is valid. * * Not implemented in any useful manner. * * @access public * @param string $country The country to check. * @return boolean */ function validateCountry($country) { return (strlen($country) == 2); } /** * Check to see if a zip code is valid. * * Not implemented in any useful manner. * * @access public * @param string $zip The code to validate. * @param string $country The country the zip code is in. * @return boolean */ function validateZipCode($zip, $country = NULL) { // Set the country if we need to. if (!isset($country)) { $country = $this->country; } // There should be a way to check the zip code for every // acceptabe country. return TRUE; } /** * Get the maximum and minimum longitude and latitude values * that our zip codes can be in. * * Not all zipcodes in this box will be with in the range. * The closest edge of this box is exactly range miles away * from the origin but the corners are sqrt(2(range^2)) miles * away. That is why we have to double check the ranges. * * @access public * @param none * @return &array The edges of the box. */ function &getRangeBox() { // Calculate the degree range using the mile range $degrees = $this->range * $this->milesToDegrees; // Get the coords for our starting zip code. list($starting_lon, $starting_lat) = $this->getLonLat($this->zipCode); // Set up an array to return. $ret_array = array (); // Lat/Lon ranges $ret_array['max_lat'] = $starting_lat + $degrees; $ret_array['max_lon'] = $starting_lon + $degrees; $ret_array['min_lat'] = $starting_lat - $degrees; $ret_array['min_lon'] = $starting_lon - $degrees; return $ret_array; } /** * Allow users to set the name of the database table holding * the information. * * @access public * @param string $table The name of the db table. * @return void */ function setTableName($table) { $this->dbTable = $table; } /** * Allow users to set the name of the column holding the * latitude value. * * @access public * @param string $lat The name of the column. * @return void */ function setLatColumn($lat) { $this->dbLat = $lat; } /** * Allow users to set the name of the column holding the * longitude value. * * @access public * @param string $lon The name of the column. * @return void */ function setLonColumn($lon) { $this->dbLon = $lon; } /** * Allow users to set the name of the column holding the * zip code value. * * @access public * @param string $zips The name of the column. * @return void */ function setZipColumn($zip) { $this->dbZip = $zip; } /** * Set a new origin and re-get the data. * * @access public * @param string $zip The new origin. * @return void */ function setNewOrigin($zip) { if ($this->validateZipCode($zip)) { $this->zipCode = $zip; $this->setZipCodesInRange(); } } /** * Set a new range and re-get the data. * * @access public * @param float $range The new range. * @return void */ function setNewRange($range) { if (is_numeric($range)) { $this->range = $range; $this->setZipCodesInRange(); } } /** * Set a new country but don't re-get the data. * * It isn't any good to check a zip code in two * countries cause the rules for zip codes vary from * country to country. * * @access public * @param string $country The new country. * @return void */ function setNewCountry($coutry) { if ($this->validateCountry($country)) { $this->country = $country; } } /** * Allow users to set the converstion ratio. * Hopefully you are changing the percision * and not setting a bad value. * * @access public * @param float $rate The new value. * @return void */ function setConversionRate($rate) { if (is_numeric($rate)) { $this->milesToDegrees = $rate; } } } /* Debugging lines $zcr = new ZipCodesRange(10965, 10); print_r($zcr); */ ?> Similar TutorialsI don't know why it won't work.. as the topic titles says that I am trying to pass a mysqli object to a property in another class but it keeps me getting an error.
here's the code for the mysqli object that i want to pass to another class
class ConnectMe2Db { public $dbname = 'somedatabase'; public $dbuname = 'root'; public $dbpass = ''; public $dbhost = 'localhost'; function __construct() { $mysqli = new mysqli($this->dbhost,$this->dbuname,$this->dbpass,$this->dbname) or die ('ERROR: '.$mysqli->connect_errno); return $mysqli; } # OTHER CODES... }and here is the class that i want the Mysqli object to pass to: class DatabaseUsers { private $dbconnection; function __construct() { $this->dbconnection = new ConnectMe2Db();#mysqli object will be passed to this attribute '$dbconnection' } public function session($username, $password) { $UserName = mysqli_real_escape_string($this->dbconnection,$username); $Password = mysqli_real_escape_string($this->dbconnection,md5($password)); $querry = "SELECT * FROM trakingsystem.login WHERE username='$username' and password='$password'"; $result = mysqli_query($this->dbconnection,$querry) or die (mysqli_error($this->dbconnection)); $count = mysqli_num_rows($result); $row = mysqli_fetch_array($result); if ($count > 0) { #some code here } } #some other code here }and this outputs 4 errors: #outputs 2 of these: Warning: mysqli_real_escape_string() expects parameter 1 to be mysqliand some mysqli_query() expects parameter 1 to be mysqli mysqli_error() expects parameter 1 to be mysqliis there something wrong with the logic that I've made? please help thanks Hi,
I'm trying to write a better PHP code to create and manage my website.
I would like to start a MVC approach with PHP, using OOP. So I can manage the updates in a better way. For example, to begin my project, I would try with the shipping cost of our products, using a Class without merge the PHP and HTML code.
Something like this:
$shippingcost=new ShippingCost(); $shippingcost->state="Italy"; $shippingcost->get(); // here I have an array with cost, discount, time ecc.And If I need it in JSON, I write: $shippingcost->get("JSON"); // here I have the JSON with cost, discount, time ecc.I wrote the Class in this way: class ShippingCost { public $state; private $arrayReturned; public function __construct() { $this->stato="Italy"; // the default state } public function __destruct() { } public function get($format="array") { $this->arrayReturned=array( "cost" => 3.99, "costDiscounted" => 7.99, "discount" => "50%" ); if (strtolower($formato)=="json") { $this->arrayReturned=json_encode($this->arrayReturned); } return $this->arrayReturned; } }It works well, but I need to get the values from a MySQL db. How can pass the MySQL connection to the Class? I'm not able to do this. Thanks in advance and have a great 2015. Rob. Hi, 3 different tutorials teach 3 different ways on how to get php mysqli echo connection errors.
Which one should I memorise out of these 3 you advise ?
1. $link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db"); if (!$link) { echo "Error: Unable to connect to MySQL." . PHP_EOL; echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL; echo "Debugging error: " . mysqli_connect_error() . PHP_EOL; exit; } mysqli_close($link);
2. $link = mysqli_connect("localhost", "root", ""); // Check connection if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // Print host information echo "Connect Successfully. Host info: " . mysqli_get_host_info($link); // Close connection mysqli_close($link);
3. mysqli_connect("localhost", "root", "", "GFG"); if(mysqli_connect_error()) echo "Connection Error."; else echo "Database Connection Successfully.";
Q2. On the connection point check, you give your rankings on these following 3 based on your preference.
A. if(mysqli_connect_error())
B. if($link === false){
C. if (!$link) {
A. die("ERROR: Could not connect. " . mysqli_connect_error());
B. echo "Connection Error.";
C. echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL; echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
Briefly, let me know: A). Which connection error checking point to use and which error message echoing point to use. B). If you got your own that is better and more helpful then explain why it is better over these 3 and any others. Sets up a mysqli connection script which I retrieve with included. If a user enters the wrong password or username then the connection to the database will be interrupted, and a message will be given about this. I want to do this in a different way. I want the .php connection script to work so that the script lets me or the ser know if it is the password that is incorrect or the username that is not authenticated. This way the user can find out if he / she has entered the wrong password or username. If both are incorrect, notice of this will be given. connection file is a fairly standard script. I have no clue about how to solve this problem. Is it posible at all? Do you know how to do it?
<? Hi, i made a singleton class to make connecting to the db easyer.
I got some questions.
1: is this the right way i wrote this class?
2: how can i easy implement mysqli prepare in this class?
I've looked everywhere but prepared staments need more lines of code to make it work and i don't know how to implement that in the singleton class.
<?php require_once(dirname(dirname(__FILE__)) . "/config.php"); class Database { public static $instance; private $mysqli, $query, $results, $count = 0; public static function getInstance() { if (!self::$instance) { self::$instance = new Database(); } return self::$instance; } public function __construct() { $this->mysqli = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE); if ($this->mysqli->connect_error) { die($this->mysqli->connect_error); } } public function query($sql) { if ($this->query = $this->mysqli->query($sql)) { while ($row = $this->query->fetch_assoc()) { $this->results[] = $row; } $this->count = $this->query->num_rows; } return $this; } public function results() { return $this->results; } public function count() { return $this->count; } } ?>usage: <?php include('database.php'); $r = Database::getInstance()->query('SELECT * FROM users'); foreach ($r->results() as $row) { echo $row['name'] . '</br>'; } echo $r->count(); ?> I have a function that performs a SELECT query on a MySQL database and populates the results in an array of Class. At the moment it is using PDO. Trouble is that PDO is not supported by the server the code will run on. Changing server is not an option, nor is installing PDO.
I have tried splitting the function to use the PDO method if installed or MySQLi if not. I am struggling to get the MySQLi part working though. Can anyone help me with this?
Here is the function I have so far which basically returns nothing from the MySQLi part:
public function mysqlSelectToClass($query, $className, $args = NULL) { include (dirname(__FILE__) . "/../config.php"); if (class_exists('PDO')) { $db = new PDO('mysql:host=' . $db_host . ';dbname=' . $db_name . ';charset=utf8', $db_user, $db_pass); $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $dbQuery = $db->prepare($query); if (isset($args)) { foreach ($args as $arg) { $dbQuery->bindParam(array_values($arg)[0], array_values($arg)[0], PDO::PARAM_STR); } } $dbQuery->execute(); return $dbQuery->fetchAll(PDO::FETCH_CLASS, $className); } else { $db = mysqli_connect($db_host, $db_user, $db_pass, $db_name); $dbQuery = $db->prepare($query); if (isset($args)) { // Type is a string of parameter types e.g. "is" $type = array_values($args)[0]; // Params is an array of parameters e.g. array(1, 'value') $params = array_values($args)[1]; call_user_func_array('mysqli_stmt_bind_param', array_merge(array($dbQuery, $type), $this->byrefValues($params))); $result = mysqli_stmt_execute($dbQuery); mysqli_close($db); } elseif ($dbResult = mysqli_query($db, $query)) { $result = mysqli_fetch_object($dbResult, $className); mysqli_close($db); } return $result; } }the byrefValues function is simply swapping a value array to a reference array and seems to be working fine. I can paste that too if required. Thanks Jay Edited by jay20aiii, 24 September 2014 - 12:41 PM. I have a singleton class that I am revamping and need a little help with. I want to use the following syntax for my queries without having to declare a global object. Below is my current code: Code: [Select] /** * The db database object * * @access private * @var object */ private $db; /** * MySQLi database object * * @access private * @var object */ private static $instance; /** * Current result set * * @access private * @var object */ private $result; /** * The last result (processed) * * @access private * @var array */ private $last_result; /** * The number of rows from last result * * @access private * @var int */ private $row_count; /** * Last error * * @access private * @var string */ private $last_error; /** * PHP5 Constructor * * Making this function 'private' blocks this class from being directly created. * * @access private */ private function __construct() { } /** * Creates and references the db object. * * @access public * @return object MySQLi database object */ public static function instance() { if ( !self::$instance ) self::$instance = new db(); return self::$instance; } /** * Connect to the MySQL database. * * @param string $host MySQL hostname * @param string $user MySQL username * @param string $password MySQL password * @param string $name MySQL database name * @return bool True if successful, false on error. */ public function connection($host, $user, $password, $name) { // Connect to the database $this->db = new mysqli($host, $user, $password, $name); // Check connection if ( mysqli_connect_errno() ) { $this->last_error = mysqli_connect_error(); return false; } return true; } public function query($sql) { $this->result = $this->db->query($sql); return $this->result; } So then, what would I need to change in my class so that I will not have to declare a global variable for other classes and functions to use like db::query->();? Thanks in advance for your help. Hi,
I am trying to connect to a database using mysqli from a web developing software package called Sellerdeck.
This software is purely windows based, it has PHP configured to a certain extent it seems.
I ran the phpinfo(); command and can't find anything to do with MYSQL in the settings of the version.
So i tried to download the php_mysql.dll and libmysql.dll files, I have referenced them in the php.ini file by using
extension_dir="./"
extension=php_mysql.dll
extension=libmysql.dll
(Also best to mention that " extension_dir="./" " was the only line of text in the php.ini file by default)
This didn't seem to make a difference at all, still get the same error.
Is there anything I can try to do? I really can't understand it as php 5 comes with mysql built in, but it seems that Sellerdeck have stripped that usability from the php version!
Any advice appreciated
Edited by engy123, 30 January 2015 - 03:58 AM. Hello all, I'm an amateur at PHP coding, and am currently enrolled in a PHP and MySQL class that uses the PHP Programming with MySQL textbook, by Don Gosselin. I'm trying to get this simple Shopping Cart script to work, because it's the step-by-step example script for Chapter 11, but I keep getting the following errors on ShowCart.php when I try to add an item to the cart. Quote Warning: mysqli_query() [function.mysqli-query]: Couldn't fetch mysqli in C:\xampplite\htdocs\ShoppingCart.php on line 78 Warning: mysqli_errno() [function.mysqli-errno]: Couldn't fetch mysqli in C:\xampplite\htdocs\ShoppingCart.php on line 80 Warning: mysqli_error() [function.mysqli-error]: Couldn't fetch mysqli in C:\xampplite\htdocs\ShoppingCart.php on line 81 Line 78: $QueryResult = mysqli_query($this->DBConnect, $SQLstring) Line 80 and 81: . "<p>Error code " . mysqli_errno($this->DBConnect) . ": " . mysqli_error($this->DBConnect)) . "</p>"; I've read "Couldn't fetch mysqli" errors are because the connection was closed prior to those lines, but I don't see any indication of a connection closure. I have no idea what to do, as all the code was given to me in the book, I merely copied it down. Here's the ShoppingCart.php code:<?php class ShoppingCart { private $DBConnect = ""; private $DBName = ""; private $TableName = ""; private $Orders = array(); private $OrderTables = array(); function construct() { $this->DBConnect = mysqli_connect("localhost", "root", "passHere"); if (mysqli_connecT_errno()) die("<p>Unable to connect to the database server.</p>" . "<p>Error code " . mysqli_connect_errno() . ": " . mysqli_connect_error()) . "</p>"; } public function setDatabase($Database) { $this->DBName = $Database; $this->DBConnect->select_db($this->DBName) Or die("<p>Unable to select the databbase.</p>" . "<p>Error code " . mysqli_errno($this->DBConnect) . ": " . mysqli_error($this->DBConnect)) . "</p>"; } public function setTable($Table) {echo $table."<br />"; $this->TableName = $Table; } public function getProductList() { $SQLstring = "SELECT * FROM $this->TableName"; $QueryResult = $this->DBConnect->query($SQLstring) Or die("<p>Error code " . mysqli_errno($this->DBConnect) . ": " . mysqli_error($DBConnect)) . "</p>"; echo "<table width='100%' border='1'>"; echo "<tr><th>Product</th><th>Description</th><th>Price Each</th><th>Select Item</th></tr>"; $Row = $QueryResult->fetch_row(); do { echo "<tr><td>{$Row[1]}</td>"; echo "<td>{$Row[2]}</td>"; printf("<td align='center'>$%.2f</td>", $Row[3]); echo "<td align ='center'> <a href='ShowCart.php?PHPSESSID=" . session_id() . "&operation=addItem&productID=" . $Row[0] . "'>Add</a></td></tr>"; $Row = $QueryResult->fetch_row(); } while ($Row); echo "</table>"; } public function addItem() { $ProdID = $_GET['productID']; if (array_key_exists($ProdID, $this->Orders)) exit("<p>You already selected that item! Click your browser's back button to return to the previous page.</p>"); $this->Orders[$ProdID] = 1; $this->OrderTable[$ProdID] = $this->TableName; } function _wakeup() { $this->DBConnect = new mysqli("localhost", "staticlo_shane", "shinfoosh"); if (mysqli_connect_errno()) die("<p>Unable to connect to the database server.</p>" . "<p>Error code " . mysqli_connect_errno() . ": " . mysqli_connect_error()) . "</p>"; $this->DBConnect->Select_db($this->DBName) Or die("<p>Unable to select the database.</p>" . "<p>Error code " . mysqli_errno($$this->DBConnect) . ": " . mysqli_error($this->DBConnect)) . "</p>"; } public function showCart() { if (empty($this->Orders)) echo "<p>Your shopping cart is empty!</p>"; else { echo "<table width='100%' border='1'>"; echo "<tr><th>Remove Item</th><th>Product</th><th>Quantity</th><th> Price Each</th></tr>"; $Total = 0; foreach($this->Orders as $Order) { $SQLstring = "SELECT * FROM " . $this->OrderTable[key($this->Orders)] . " WHERE productID='" . key($this->Orders) . "'"; $QueryResult = mysqli_query($this->DBConnect, $SQLstring) Or die("<p>Unable to perform the query.</p>" . "<p>Error code " . mysqli_errno($this->DBConnect) . ": " . mysqli_error($this->DBConnect)) . "</p>"; $Row = mysqli_fetch_row($QueryResult); echo "<td align='center'>"; echo "<a href='ShowCart.php?PHPSESSID=" . session_id() . "&operation=removeItem&productID=" . $Row[0] . "'>Remove</a></td>"; echo "<td>{$Row[1]}</td>"; echo "<td align='center''>$Order "; echo "<a href='ShowCart.php?PHPSESSID=" . session_id() . "&operation=addOne&productID=" . $Row[0] . "'>Add</a>"; echo "<a href='ShowCart.php?PHPSESSID=" . session_id() . "&operation=removeOne&productID=" . $Row[0] . "'>Remove</a>"; echo "</td>"; printf("<td align='center'>$%.2f</td></tr>", $Row[3]); $Total += $Row[3] * $Order; next($this->Orders); echo "<td align='center' colspan='2'><strong>Your shopping cart contains " . count($this->Orders) . " product(s).</strong></td>"; printf("<td align='center'><strong>Total: $%.2f</stong> </td>", $Total); echo "</table>"; } echo "<tr><td align='center'><a href='ShowCart.php?PHPSESSID=" . session_id() . "&operation=emptyCart'><strong> Empty Cart</strong></a></td>"; } } public function removeItem() { $ProdID = $_GET['productID']; unset($this->Orders[$ProdID]); unset($this->OrderTable[$ProdID]); } function emptyCart() { $this->Orders = array(); $this->OrderTale = array(); } function _destruct() { $this->DBConnect->close(); } public function addOne() { $ProdID = $_GET['productID']; $this->Orders[$ProdID] += 1; } public function removeOne() { $ProdID = $_GET['productID']; $this->Orders[$ProdID] -= 1; if ($this->Orders[$ProdID] == 0) $this->removeItem(); } } ?> Here is the ShowCart.php code:<?php session_start(); require_once("ShoppingCart.php"); if (!isset($_SESSION['curCart'])) header("location:GosselinGourmetGoods.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <meta name="Robots" content="nofollow, noindex" /> <link rel="stylesheet" type="text/css" media="screen" href="php_styles.css" /> </head> <body> <h1>Gosselin Gourmet Goods</h1> <h2>Shop by Category</h2> <p><a href="GosselinGourmetCoffees.php">Gourmet Coffees</a><br /> <a href="GosselinGourmetOlives.php">Specialty Olives</a><br /> <a href="GosselinGourmetSpices.php">Gourmet Spices</a></p> <?php $Cart = unserialize($_SESSION['curCart']); if (isset($_GET['operation'])) { if ($_GET['operation'] == "addItem") $Cart->addItem(); if ($_GET['operation'] == "removeItem") $Cart->removeItem(); if ($_GET['operation'] == "emptyCart") $Cart->emptyCart(); if ($_GET['operation'] == "addOne") $Cart->addOne(); if ($_GET['operation'] == "removeOne") $Cart->removeOne(); } $Cart->showCart(); $_SESSION['curCart'] = serialize($Cart); ?> </body> </html> Here is the product page for "Specialty Olives" which is identical to the Coffees and Spices pages, save for the Table name changed to their respective products: <?php session_start(); require_once("ShoppingCart.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Gosselin Gourmet Goods</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <meta name="Robots" content="nofollow, noindex" /> <link rel="stylesheet" type="text/css" media="screen" href="php_styles.css" /> </head> <body> <h1>Gosselin Gourmet Goods</h1> <h2>Shop by Category</h2> <p><a href="GosselinGourmetCoffees.php">Gourmet Coffees</a><br /> <a href="GosselinGourmetOlives.php">Specialty Olives</a><br /> <a href="GosselinGourmetSpices.php">Gourmet Spices</a></p> <h2>Speciality Olives</h2> <?php $Database = "gosselin_gourmet"; $Table = "olives"; $Cart=!empty($_SESSION['curCart'])?unserialize($_SESSION['curCart']):new ShoppingCart(); $Cart->construct(); $Cart->setDatabase($Database); $Cart->setTable($Table); $Cart->getProductList(); $_SESSION['curCart'] = serialize($Cart); ?> <p><a href='<?php echo "ShowCart.php?PHPSESSID=" . session_id() ?>'>Show Shopping Cart</a></p> </body> </html> I created a database class to connect to a database. The code is below. I'm not sure how to call this connection in other classes. Do I use: $db->pdo = $conn->prepare($sql); or what? Note that the db object is instantiated at the end of the class file. Here is the class:
class DB { public $pdo = ''; //public $message = 'A message from db'; // Debug function __construct() { // Database info located elsewhere $servername = "localhost"; $username = "root"; $password = ""; $dbname = "dbname"; try { $this->pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // set the PDO error mode to exception $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } // End Try catch(PDOException $e) { echo "Error: " . $e->getMessage(); } //echo '<h3>Everything wnet OK.</h3>'; // Debug } // End __construct } // End class definition DB.php $db = new DB; Thanks,
--Kenoli I've searched all over for the past few days trying to figure out what I'm doing wrong. Basically what I'm trying to do is create a prepared statement inside my User class. I can connect to the database, but my query does not execute as expected. Here's the code for my User class Code: [Select] <?php include '../includes/Constants.php'; ?> <?php /** * Description of User * * @author Eric Evas */ class User { var $id, $fname, $lname, $email, $username, $password, $conf_pass; protected static $db_conn; //declare variables public function __construct() { $host = DB_HOST; $user = DB_USER; $pass = DB_PASS; $db = DB_NAME; //Connect to database $this->db_conn = new mysqli($host, $user, $pass, $db); //Check database connection if ($this->db_conn->connect_error) { echo 'Connection Fail: ' . mysqli_connect_error(); } else { echo 'Connected'; } } function regUser($fname, $lname, $email, $username, $password, $conf_pass) { if ($stmt = $this->db_conn->prepare("INSERT INTO USERS (user_fname,user_lname, user_email,username,user_pass) VALUES (?,?,?,?,?)")) { $stmt->bind_param('sssss', $this->fname, $this->lname, $this->email, $this->username, $this->password); $stmt->execute(); $stmt->store_result(); $stmt->close(); } } } ?> And here's the file that I created to instantiate an instance of the user class. Code: [Select] <?php include_once 'User.php'; ?> <?php //Creating new User Object $newUser = new User(); $newUser->fname = $_POST['fname']; $newUser->lname = $_POST['lname']; $newUser->email = $_POST['email']; $newUser->username = $_POST['username']; $newUser->password = $_POST['password']; $newUser->conf_pass = $_POST['conf_pass']; $newUser->regUser($newUser->fname, $newUser->lname, $newUser->email, $newUser->username, $newUser->password, $newUser->conf_pass); ?> And lastly heres the form that I want to get info from the user to insert into the database Code: [Select] <html> <head> <title></title> <link href="stylesheets/styles.css" rel="stylesheet" type="text/css"/> </head> <body> <form action = "Resources/testClass.php" method="post" enctype="multipart/form-data"> <label>First Name: </label> <input type="text" name="fname" id="fname" size="25" maxlength="25"/> <label>Last Name: </label> <input type="text" name="lname" id="lname" size="25" maxlength="25"/> <label>Email: </label> <input type="text" name="email" id="email" size="25" maxlength="40"/> <label>Username: </label> <input type="text" name="username" id="username" size="25" maxlength="32"/> <label>Password: </label> <input type="password" name="password" id="password" size="25" maxlength="32"/> <label>Re-enter Password: </label> <input type="password" name="conf_pass" id="conf_pass" size="25" maxlength="32"/> <br /><br /> <input type="submit" name="submit" id="submit" value="Register"/> <input type="reset" name="reset" id="reset" value="Reset"/> </form> </body> </html> Mon Aug 24, 2020 2:41 pm I'm using php_serial.class.php, called once require_once("php_serial.class.php"); and call it $serial: $serial = new phpSerial;
The above are in a global.php file that sets up the serial com parameters. Function checkInput($serial){ And one in the Function: $read = $serial->readPort();
This throws an error: "PHP Fatal error: Uncaught Error: Call to a member function readPort() on string" hello. i have posted something similar before and people said i should go away and learn oop. I have since done the entire Linda training on oop, watched countless videos and build a photo gallery (from the training videos) but im still stuck on this silly little thing. so please please could some one help. thanks ok, so i have 2 classes. 1 called Pages and 1 called Templates. each page has an id for the layout it wants to use. so i want to get the layoutTemps_id from the pages class and use it in a function WHERE clause to get the correct layout for that page. I cant seem to pass the layoutTemps_id into my Templates class from my Pages Class ??? i tried using a global but couldnt get it to work. ANY IDEAS ?? thanks this is the Pages class function that gets all the information for each page. Code: [Select] public static function find_by_pageName($pName){ global $database; $sql = "SELECT * FROM ".self::$table_name." WHERE pageName='".$database->escape_value($pName)."'"; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } that works just fine. it gets the $pName on the page and is different each time. i.e Code: [Select] $pName = "adminHome"; $page = Pages::find_by_pageName($pName); echo $page->id."<br />"; echo $page->layoutTemps_id.'<br/>'; so that all seems to work fine. now i want to use the $page->layoutTemps_id in my Templates class. this is the class class Templates extends Pages { this is the function im trying to write. i thought that because class Templates extends Pages i could put in $page->layoutTemps_id with no problem but in stuck. Code: [Select] public static function find_layoutTemp(){ $layoutTemps_id = Pages::layoutTemps_id; $sql = "SELECT * FROM ".self::$table_name." WHERE id='".$database->escape_value($layoutTemps_id)."'"; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } this is the page where im echoing the layoutTemps_id Code: [Select] <?PHP require_once("../includes/initialize.php"); $temp = Templates::find_layoutTemp(); echo "layoutTemp id " .$temp->id . " <br />"; echo "layoutTemp name " .$temp->name ." <br />"; now, i'm 100% sure there's lots wrong with my code but i'm ill be happy if someone could help. thanks rick I closed everything down last night and it was all fine, website was working as normal etc, but I've turned on the Xxamp server today and I am getting this error. Seems very random as nothing has changed since it was last on? Does anyone know how to sort this out and why I'm now getting this error? Thanks! I have mysqli object in Database class base: [color=]database class:[/color] class Database { private $dbLink = null; public function __construct() { if (is_null($this->dbLink)) { // load db information to connect $init_array = parse_ini_file("../init.ini.inc", true); $this->dbLink = new mysqli($init_array['database']['host'], $init_array['database']['usr'], $init_array['database']['pwd'], $init_array['database']['db']); if (mysqli_connect_errno()) { $this->dbLink = null; } } } public function __destruct() { $this->dbLink->close(); } } Class derived is Articles where I use object dBLink in base (or parent) class and I can't access to mysqli methods (dbLink member of base class): Articles class: require_once ('./includes/db.inc'); class Articles extends Database{ private $id, .... .... $visible = null; public function __construct() { // Set date as 2009-07-08 07:35:00 $this->lastUpdDate = date('Y-m-d H:i:s'); $this->creationDate = date('Y-m-d H:i:s'); } // Setter .... .... // Getter .... .... public function getArticlesByPosition($numArticles) { if ($result = $this->dbLink->query('SELECT * FROM articles ORDER BY position LIMIT '.$numArticles)) { $i = 0; while ($ret = $result->fetch_array(MYSQLI_ASSOC)) { $arts[$i] = $ret; } $result->close(); return $arts; } } } In my front page php I use article class: include_once('./includes/articles.inc'); $articlesObj = new articles(); $articles = $articlesObj->getArticlesByPosition(1); var_dump($articles); [color=]Error that go out is follow[/color] Notice: Undefined property: Articles::$dbLink in articles.inc on line 89 Fatal error: Call to a member function query() on a non-object in articles.inc on line 89 If I remove constructor on derived class Articles result don't change Please help me Hi Can you call Class A's methods or properties from Class B's methods? Thanks. If a class has a constructor but also has a static method, if I call the static method does the constructor run so that I can use an output from the constructor in my static method? --Kenoli Ok. I know you can pass the object of a class as an argument. Example: class A { function test() { echo "This is TEST from class A"; } } class B { function __construct( $obj ) { $this->a = $obj; } function test() { $this->a->test(); } } Then you could do: $a = new A(); $b = new B($a); Ok so that's one way i know of. I also thought that you could make a method static, and do this: (assuming class A's test is 'static') class B { function test() { A::test(); } } But that is not working. I'd like to know all possible ways of accomplishing this. Any hints are appreciated. thanks I have an existing instance of my class Database, now I want to call that instance in my Session class, how would I go about doing this? Hi, I need to be able to call a class based on variables. E.G. I would normally do: Code: [Select] $action = new pattern1() but i would like to be able to do it dynamicaly: Code: [Select] $patNum = 1; $action = new pattern.$patNum.() Im wondering if that's possible? If so what would the correct syntax be? Many Thanks. |