PHP - Oop In Php Using Mysqli Connection
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. Similar TutorialsHi, 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. 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); */ ?> 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?
<? 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> When running the following code i get the error: Call to undefined method mysqli::errno() the code: $conn = new mysqli(HOST, USER, PASSWORD, DATABASE); if ($conn->errno() !== 0) { $msg = $conn->error(); throw new connErrorException($msg, 'Connect'); } I am fairly new to classes but as i understand it this should be correct. I am using mysql 5.1 so mysqli is on by default. I have even checked the php ini and everything looks fine there in respect to this. Any advice? I am using mysqli, OO, to connect to MySQL. I have only today started looking at this and am used to: Code: [Select] <?php $con = mysql_connect();//etc mysql_close($connection); ?> Am I right that with mysqli (OO) that I don't need to set a connection variable wither when connecting or closing?? Code: [Select] <?php mysqli::connect();//etc mysqli::close(); ?> What about with multiple databases, does mysqli keep track for me, as I am used to this: Code: [Select] <?php $con1 = mysql_connect();//db1 $con2 = mysql_connect();//db2 ?> //etc Hello everyone, For two weeks now, I'm trying to get this database connection in my query. Can someone give me a solution and tell me what I've done wrong? Am I overlooking something? <?php class Mysql{ public function connect(){ $mysqli = new mysqli('localhost','root','','login'); } } class Query extends Mysql{ public function runQuery(){ $this->result = parent::connect()->query("select bla bla from bla bla"); } } $query = new Query; $query->runQuery(); ?> I have just started using MySQLi and am clueless it is giving me the follow errors in which i do not understand
Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\xampp\htdocs\Login\connect.php on line 23 Notice: Trying to get property of non-object in C:\xampp\htdocs\Login\connect.php on line 25 Notice: Use of undefined constant mysqli - assumed 'mysqli' in C:\xampp\htdocs\Login\connect.php on line 32 Warning: mysqli_query() expects parameter 1 to be mysqli, string given in C:\xampp\htdocs\Login\connect.php on line 32 Warning: mysql_fetch_assoc() expects parameter 1 to be resource, null given in C:\xampp\htdocs\Login\connect.php on line 33 can someone please explain to me why i am getting these? and my code is $mysqli_db = mysqli_select_db("$db_name"); if($mysqli_db->connect_errno) { printf("Database not found: %s\n", $mysql->connect_error); exit(); } $sql = "SELECT * FROM $tbl_name WHERE username='$username' AND password='$password'"; $result = mysqli_query($sql); $row = mysqli_fetch_assoc($result);I just got rid off most the errors the only ones left are Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\xampp\htdocs\Login\connect.php on line 32 Fatal error: Call to undefined function mysqli_result() in C:\xampp\htdocs\Login\connect.php on line 33 Code Updated: $mysqli_db = mysqli_select_db($mysqli_connect, $db_name); if(!$mysqli_db) { printf("Database not found: %s\n", $mysqli->connect_error); exit(); } $sql = "SELECT * FROM $tbl_name WHERE username='$username' AND password='$password'"; $query = mysqli_query($sql); $result = mysqli_result($query); $row = mysqli_fetch_assoc($result); Edited by Tom8001, 30 November 2014 - 12:43 PM. hello , I'm starting to use mysqli and i have few questions. is there a guide for mysqli? and how do i use this functions at mysqli ? mysql_num_rows mysql_query mysql_fetch_assoc mysql_fetch_array thanks , Mor. Hi, The following code is what I want in that it creates a menu and I can select and display a table row.
I still need to use that selection to update the "lastused". I really appreciate your help. <!DOCTYPE><html><head><title>email menu</title></head> <body><center> <form name="form" method="post" action=""> <?php $con=mysqli_connect("localhost","root","cookie","homedb"); //============== check connection if(mysqli_errno($con)) {echo "Can't Connect to mySQL:".mysqli_connect_error();} else {echo "Connected to mySQL</br>";} //This creates the drop down box echo "<select name= 'target'>"; echo '<option value="">'.'--- Select email account ---'.'</option>'; $query = mysqli_query($con,"SELECT target FROM emailtbl"); $query_display = mysqli_query($con,"SELECT * FROM emailtbl"); while($row=mysqli_fetch_array($query)) {echo "<option value='". $row['target']."'>".$row['target'] .'</option>';} echo '</select>'; ?> <input type="submit" name="submit" value="Submit"/><!-- update "lastused" using selected "target"--> </form></body></html> <!DOCTYPE><html><head><title>email menu</title></head> <body><center> <?php $con=mysqli_connect("localhost","root","cookie","homedb"); if(mysqli_errno($con)) {echo "Can't Connect to mySQL:".mysqli_connect_error();} if(isset($_POST['target'])) { $name = $_POST['target']; $fetch="SELECT target,username,password,emailused,lastused, purpose, saved FROM emailtbl WHERE target = '".$name."'"; $result = mysqli_query($con,$fetch); if(!$result) {echo "Error:".(mysqli_error($con));} $lastused = "CURDATE()"; // update "lastused" using selected "target" //display the table echo '<table border="1">'.'<tr>'.'<td bgcolor="#ccffff align="center">'. 'Email menu'. '</td>'.'</tr>'; echo '<tr>'.'<td>'.'<table border="1">'.'<tr>'.'<td bgcolor="#ccffff align="center">'.'target'.'</td>'.'<td bgcolor="#ccffff align="center">'.'username'.'</td>'.'<td bgcolor="#ccffff align="center">'.'password'.'</td>'.'<td bgcolor="#ccffff align="center">'.'emailused'.'</td>'.'<td bgcolor="#ccffff align="center">'.'lastused'.'</td>'.'<td bgcolor="#ccffff align="center">'.'purpose'. '</td>'.'<td bgcolor="#ccffff align="center">'. 'saved' .'</td>'.'</tr>'; while($data=mysqli_fetch_row($result)) {echo ("<tr><td>$data[0]</td><td>$data[1]</td><td>$data[2]</td><td>$data[3]</td><td>$data[4]</td><td>$data[5]</td><td>$data[6]</td></tr>");} echo '</table>'.'</td>'.'</tr>'.'</table>'; } ?> </body></html> I dont know whether the statement is correct.....i just tried it.....and it didn't work. $stmt->bind_param('ssiiiss',$_POST['name'],$_POST['email'],$_POST['d'],$_POST['m'],$_POST['y'],$_POST['add'],$_POST['phone']); here my first two values are strings and next 2 tiny int's next is int and last 2 again strings. Ok I am trying to use mysqli instead of the usual mysql. Mysql would be outdated. With mysqli, sgl-injection is impossible if you use the "?" in those codes. I would normally use a function but I've made a simple script to find the error. I use $parameters and $sql because these are the data I need to give as parameters to the function, so I used it here too but without the function actually. Code: [Select] ini_set('display_errors',1); // 1 == aan , 0 == uit error_reporting(E_ALL | E_STRICT); # sql debug define('DEBUG_MODE',true); // true == aan, false == uit $userid = 11; $lang = 1; $newLink = "testing123"; $db_host = "localhost"; $db_gebruiker = "root"; $db_wachtwoord = ''; $db_naam = "projecteasywebsite"; $sql= "INSERT tbl_link(userid,linkcat,linksubid,linklang,linkactive,linktitle) VALUES(?, ?, ?, ?, ?, ?)"; $parameters = '"iiisis", $userid, 1, 0, $lang, 1, $newLink'; echo $parameters; $mysqli = new mysqli($db_host, $db_gebruiker, $db_wachtwoord, $db_naam); $stmt = $mysqli->prepare($sql); $stmt->bind_param($parameters); $stmt->execute(); echo "<br><br>". mysqli_connect_errno(); echo "<br><br>". mysqli_report(MYSQLI_REPORT_ERROR); $stmt->close(); $mysqli->close(); I got Wrong parameter count for mysqli_stmt::bind_param() So naturally a problem when we execute : Warning: mysqli_stmt::execute() [mysqli-stmt.execute]: (HY000/2031): No data supplied for parameters in prepared statement ($stmt->execute() Is someone using mysqli too ?
The below code produces a dropdown and when a selection is made and submitted produces --------------------------------------------------------------------------- <!DOCTYPE><html><head> <title>lookup menu</title> </head> <body><center><b> <form name="form" method="post" action=""> <?php // error_reporting(0); error_reporting(E_ALL ^ E_NOTICE); include 'homedb-connect.php'; //This creates the drop down box echo "<select name= 'target'>"; echo '<option value="">'.'--- Select account ---'.'</option>'; $query = mysqli_query($con,"SELECT target FROM lookuptbl"); $query_display = mysqli_query($con,"SELECT * FROM lookuptbl"); while($row=mysqli_fetch_array($query)) {echo "<option value='". $row['target']."'>".$row['target'] .'</option>';} echo '</select>'; ?> <input type="submit" name="submit" value="Submit"/> </form><center> <?php // error_reporting(0); error_reporting(E_ALL ^ E_NOTICE); include 'homedb-connect.php'; if(isset($_POST['target'])) { $name = $_POST['target']; $fetch="SELECT target, purpose, user, password, email, visits, date, saved FROM lookuptbl WHERE target = '".$name."'"; $result = mysqli_query($con,$fetch); if(!$result) {echo "Error:".(mysqli_error($con));} //display the table echo '<table border="1"><tr><td bgcolor="#ccffff" align="center">lookup menu</td></tr> <tr><td> <table border="1"> <tr> <td> Target </td> <td> Purpose </td> <td> User </td> <td> Password </td> <td> Email </td> <td> Visits </td> <td> Date </td> <td> Saved </td> </tr>'; while($data=mysqli_fetch_row($result)) { $url= "http://localhost/home/crud-link.php?target=". $data[0]; $link= '<a href="'.$url.'">'. $data[0]. '</a>'; echo ("<tr><td> $link </td><td>$data[1]</td><td>$data[2]</td><td>$data[3]</td> <td>$data[4]</td><td>$data[5]</td><td>$data[6]</td><td>$data[7]</td></tr>"); } echo '</table> </td></tr></table>'; } ?> </body></html>
Hey. I was writing my class object for a database connection and while I was writing the query part, I came to wonder whether I should use mysql_real_escape_string or mysqli_real_escape_string to make the query mysql friendly, what's the difference? I am trying to extend my knowledge from using basic mysql_connect etc. into something better. I am searching on Google, and looking up as much info as possible but find that I learn best with a brief overview that allows me to channel down my searches. (1) I know PDO v mysql_connect v mysqli isn;t right - I think PDO is a class, mysql_connect is a command and mysqli is something else. Am I on the right track? (2) What is the best solution? I am using a full OOP coding style and want to learn the best - I am a novice at this but would consider myself an 8/10 programmer at other parts of PHP. An very brief overview to get me started and channel my Google searches would be much appreciated. - I have heard PDO is slower. - I don't need support for different databases (only MySQL). Thanks in advance. I have some code I used to have in mysql and now im trying to convert to mysqli and I cant seem to find out what the problem is.
<?php $username = $_SESSION['username']; // Connect to server and select databse. include "db_connect.php"; include "db_config.php"; // items tables selection $sql = mysqli_query($my_database,"SELECT * FROM items_tbl WHERE level = '$account_info[player_level]' ORDER BY rand()"); //$result = mysqli_query($my_database,$sql); // Put info into array (This Works) while($item = mysqli_fetch_assoc($sql)){ //stats $items_id['itemid'] = $item['itemid']; $items_id['Level'] = $item['Level']; $items_id['name'] = $item['name']; $items_id['min_str'] = $item['min_str']; $items_id['min_int'] = $item['min_int']; $items_id['min_dex'] = $item['min_dex']; $items_id['type'] = $item['type']; $items_id['min_dmg'] = $item['min_dmg']; $items_id['max_dmg'] = $item['max_dmg']; $items_id['phys_defense'] = $item['phys_defense']; $items_id['mag_defense'] = $item['mag_defense']; } ?>here is the error im getting: Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given Hi,
Im using Mysqli and im trying to limit the results by 10 and order them from last to first from the database.
$sqlhorses = "SELECT Place FROM `*` WHERE `Horse` ='".$db->real_escape_string($row['horse']). "'";the above works but when i added the limit 6 to the end it shows errors. Can anyone help? Hello,
Got a code, need to insert a query for displaying links of posts in section. Category is 'blog', each post has it's 'id', and 'subject', which should be a name for link, such as "blog.php?p='id'".
<!doctype html> <html lang="en"> <head> </head> <body class="base"> <div class="container"> <!-- PRZETWARZANIE WYNIKÓW Z BAZY --> <?php $total_pages = $link->query('SELECT * FROM news WHERE category="blog"')->num_rows; $page = isset($_GET['page']) && is_numeric($_GET['page']) ? $_GET['page'] : 1; $num_results_on_page = 1; if ($stmt = $link->prepare('SELECT * FROM news WHERE category="blog" ORDER BY date DESC LIMIT ?,?')) { $calc_page = ($page - 1) * $num_results_on_page; $stmt->bind_param('ii', $calc_page, $num_results_on_page); $stmt->execute(); $result = $stmt->get_result(); } while ($row = $result->fetch_assoc()): $text = $row['news']; $text = str_replace('[video]','<div class="video-container">',$text); $text = str_replace('[/video]','</div>',$text); $text = str_replace('[media]','',$text); $text = str_replace('[/media]','',$text); $embera = new \Embera\Embera(); echo '<div class="container"> <div class="row">'; ?> <div class="col-sm-4"> /* here is a place for links to published posts */ </div> <?php echo '<div class="col-sm-8"><h3>'.$row['subject'].'</h3>'; echo '<div class="tresc embed-responsive">'; echo $embera->autoEmbed($text); echo '</div></div> </div> </div>'; endwhile; ?> <!-- KONIEC PRZETWARZANIA WYNIKÓW Z BAZY --> <hr class="pagination_divider"> <center> <!-- PAGINATION --> <?php if (ceil($total_pages / $num_results_on_page) > 0): ?> <div class="sect_paginate"><ul class="pagination"> <?php if ($page > 1): ?> <li class="prev"><a href="blog.php?page=<?php echo $page-1 ?>">◂ WSTECZ</a></li> <?php endif; ?> <li class="currentpage"><a href="blog.php?page=<?php echo $page ?>"><?php echo $page ?></a></li> <?php if ($page < ceil($total_pages / $num_results_on_page)): ?> <li class="next"><a href="blog.php?page=<?php echo $page+1 ?>">DALEJ ▸</a></li> <?php endif; ?> </ul></div> <?php endif; $stmt->close(); ?> </center> <!-- END OF PAGINATION --> </div> </body> </html>
This line of PHP mysqli::__construct($CFG->dbhost, $CFG->dbuser, $CFG->dbpass, $CFG->dbname); returns Quote Fatal error: Non-static method mysqli::mysqli() cannot be called statically in Why does it do this? I want to use the OOP MySQLi methods in PHP and NO procedural PHP Hi I'm trying to insert unique info retrieved to my database but seems like I'm doing something wrong with my quary my current setup is as follow
mxit.php
<?php $con=mysqli_connect("*****","*******","*******","******"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } mysqli_close($con); ?> <? define('TIMEZONE', 'Africa/Harare'); date_default_timezone_set(TIMEZONE); $ip = $_SERVER["REMOTE_ADDR"]; $post_time = date("U"); $mxitua = $_SERVER["HTTP_X_DEVICE_USER_AGENT"]; $mxitcont = $_SERVER["HTTP_X_MXIT_CONTACT"]; $mxituid = $_SERVER["HTTP_X_MXIT_USERID_R"]; $mxitid = $_SERVER["HTTP_X_MXIT_ID_R"]; $mxitlogin = $_SERVER["HTTP_X_MXIT_LOGIN"]; $mxitnick = $_SERVER["HTTP_X_MXIT_NICK"]; $mxitloc = $_SERVER["HTTP_X_MXIT_LOCATION"]; $mxitprof = $_SERVER["HTTP_X_MXIT_PROFILE"]; if(!isset($mxitid)) { $mxitid = "DEFAULT"; } mysqli_query($con,"INSERT INTO mxit (ip,time,user_agent,contact,userid,id,login,nick,location,profile) VALUES ($ip,$post_time,$mxitua,$mxitcont,$mxituid,$mxitid,$mxitlogin,$mxitnick,$mxitloc,$mxitprof)"); mysqli_close($con); ?> |