PHP - Mysqli_stmt_fetch() Couldn't Fetch Mysqli_stmt
Hi Everyone,
I've been using prepared statements to insert data into my database and they have been working just fine. I wanted to try prepared statements for select queries and began testing with the code provided at the PHP site. There are a couple of examples in the manual - one for mysqli_prepare() and another for mysqli_stmt_fetch(). The code looks like this: Code: [Select] <?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $city = "Amersfoort"; /* create a prepared statement */ if ($stmt = mysqli_prepare($link, "SELECT District FROM City WHERE Name=?")) { /* bind parameters for markers */ mysqli_stmt_bind_param($stmt, "s", $city); /* execute query */ mysqli_stmt_execute($stmt); /* bind result variables */ mysqli_stmt_bind_result($stmt, $district); /* fetch value */ mysqli_stmt_fetch($stmt); printf("%s is in district %s\n", $city, $district); /* close statement */ mysqli_stmt_close($stmt); } /* close connection */ mysqli_close($link); ?> I am testing this code with a database and using SHA1 encryption for passwords. My code is as follows: Code: [Select] $username = "somename"; $passwd = "somepass"; // Check if username is unique $stmt = mysqli_prepare($conn, "select verify from users where user_name=? and password=sha1(?)"); mysqli_stmt_bind_param($stmt, "ss", $username, $passwd); mysqli_stmt_execute($stmt); mysqli_stmt_bind_result($stmt, $verify); mysqli_stmt_fetch($stmt); echo "The registration varification is ".$verify."<br />"; // Close the statement mysqli_stmt_close($stmt); // Close the link mysqli_close($conn); The results are not as expected as I get the error message, Warning: mysqli_stmt_fetch() Couldn't fetch mysqli_stmt. I've looked up the error and I haven't found anything on the web that explains what's causing it. I can echo the value of $verify, which I'll need farther down the script, but mysqli_stmt_fetch is returning "false", and I need a return of "true" as a conditional to test the state of a users account (in this case the state of the account should return "true"). I have used the hash version of the password and that yields the same result. Could someone please clue me in? I have no idea what the issue is. Thanks much for your time! cheers, Rick Similar TutorialsI am getting the error message "Couldn't fetch mysqli on line 48". Here's the script: By the way the uploading of the first file does work, but the upload of the second file so it updates and refreshes with a new avatar file name does not work. Code: [Select] <?php // This file gets included into profile_content.php // AVATAR code define ('AVATAR_UPLOADPATH', 'avatar/'); define ('AVATAR_MAXFILESIZE', '32768'); // _UPLOAD_ and _MOVE_ avatar to target location - START if (isset($_POST['submit'])) { $avatar = $_FILES['avatar_upload']['name']; $avatar_type = $_FILES['avatar_upload']['type']; $avatar_size = $_FILES['avatar_upload']['size']; // file type + file size + file upload + width & height VALIDATION if ((($avatar_type == 'image/gif') || ($avatar_type == 'image/jpeg') || ($avatar_type == 'image/pjeg') || ($avatar_type == 'image/png') && ($avatar_size > 0) && ($avatar_size <= AVATAR_MAXFILESIZE))) { if ($_FILES['avatar_upload']['error'] == 0) { list($width, $height, $type, $attr) = getimagesize($_FILES['avatar_upload']['tmp_name']); if ($width == 64 && $height == 64) { // UPLOAD + MOVE //////////////////////// HERE IS THE LINE ///////////////////////////////////////////// // Update the file name $query3 = "UPDATE user SET avatar = '$avatar' WHERE user_id = '$user_id'"; $row3 = mysqli_query ($dbc, $query3) or die (mysqli_error($dbc)); // Move the uploaded file on the disk to its folder move_uploaded_file ($_FILES['avatar_upload']['tmp_name'], $target . $avatar); // Rename the file into a more usable file name $avatar = rename($avatar, $user_name . '_' . rand(111111, 999999)); // Success echo "Your avatar has been successfully uploaded. Please refresh the page to see the changes."; // error messages // width and height error } else { echo "Your avatar has to have a width and height of 64 pixels, please crop it or use a different avatar."; } // file upload error } else { echo "Error: " . $_FILES['avatar_upload']['error']; } // file type error } else { echo "The avatar must be a GIF, JPEG or PNG image file and no greater than " . AVATAR_MAXFILESIZE / 1024 . " KB in size."; } } // END ?> Any ideas why I am getting the error message. I marked the corresponding line with ///// HERE IS THE LINE //// in the mid area. 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 have this code that uses mysqli_stmt_store_result and mysqli_stmt_fetch This code does NOT work: $query = "SELECT userid FROM customer LIMIT 1"; $stmt = mysqli_prepare($connectstring, $query); mysqli_stmt_execute($stmt); mysqli_stmt_store_result($stmt); mysqli_stmt_bind_result($stmt, $returnedval); mysqli_stmt_close($stmt); This code DOES work: $query = "SELECT userid FROM customer LIMIT 1"; $stmt = mysqli_prepare($connectstring, $query); mysqli_stmt_execute($stmt); mysqli_stmt_bind_result($stmt, $returnedval); mysqli_stmt_fetch($stmt); mysqli_stmt_close($stmt); I have some other code where the mysqli_stmt_store_result($stmt); does work and I thought that was a way of storing the result of the execute. Can someone explain the difference between the two statements. PHP says to always use the store but it does not work. Thanks JT Well I have a library file class_database.php which defines a class called 'database' and a method called 'get' to retrieve database info. It was originally designed to return a two-dimensional array with the format of $array['index']['associative']. Right now I want to change this so as to return a result, which can then be used in other script files to retrieve data by using the fetch_array() method after getting this result. It doesnt work though, and I got this error 'Call to undefined method mysqli_stmt::get_result()', which confuses me... The two methods get() and _buildQuery are shown below, please help me figure out how to return an Mysql result so that I can use while($row = $db->get()->fetch_array()) on it with flexibility... The method get() Code: [Select] public function get($tableName, $numRows = NULL) { $this->_query = "SELECT * FROM $tableName"; $stmt = $this->_buildQuery($numRows); $stmt->execute(); $results = $stmt->get_result(); $this->reset(); return $results; } The method _buildQuery is shown below: Code: [Select] protected function _buildQuery($numRows = NULL, $tableData = NULL) { (gettype($tableData) === 'array') ? $hasTableData = true : $hasTableData = false; (!empty($this->_where )) ? $hasConditional = true : $hasConditional = false; // Did the user call the "where" method? if (!empty($this->_where)) { // if update data was passed, filter through and create the SQL query, accordingly. if ($hasTableData) { $i = 1; $pos = strpos($this->_query, 'UPDATE'); if ( $pos !== false) { foreach ($tableData as $prop => $value) { // determines what data type the item is, for binding purposes. $this->_paramTypeList .= $this->_determineType($value); // prepares the reset of the SQL query. ($i === count($tableData)) ? $this->_query .= $prop . ' = ?': $this->_query .= $prop . ' = ?, '; $i++; } } } //Prepair the where portion of the query $this->_query .= ' WHERE '; $i = 1; foreach ($this->_where as $column => $value) { // Determines what data type the where column is, for binding purposes. $this->_whereTypeList .= $this->_determineType($value); // Prepares the reset of the SQL query. ($i === count($this->_where)) ? $this->_query .= $column . ' = ?': $this->_query .= $column . ' = ? AND '; $i++; } } // Determine if is INSERT query if ($hasTableData) { $pos = strpos($this->_query, 'INSERT'); if ($pos !== false) { //is insert statement $keys = array_keys($tableData); $values = array_values($tableData); $num = count($keys); // wrap values in quotes foreach ($values as $key => $val) { $values[$key] = "'{$val}'"; $this->_paramTypeList .= $this->_determineType($val); } $this->_query .= '(' . implode($keys, ', ') . ')'; $this->_query .= ' VALUES('; while ($num !== 0) { ($num !== 1) ? $this->_query .= '?, ' : $this->_query .= '?)'; $num--; } } } // Did the user set a limit if (isset($numRows)) { $this->_query .= " LIMIT " . (int) $numRows; } // Prepare query $stmt = $this->_prepareQuery(); // Prepare table data bind parameters if ($hasTableData) { $this->_bindParams[0] = $this->_paramTypeList; foreach ($tableData as $prop => $val) { array_push($this->_bindParams, &$tableData[$prop]); } } // Prepare where condition bind parameters if($hasConditional) { if ($this->_where) { $this->_bindParams[0] .= $this->_whereTypeList; foreach ($this->_where as $prop => $val) { array_push($this->_bindParams, &$this->_where[$prop]); } } } // Bind parameters to statment if ($hasTableData || $hasConditional){ call_user_func_array(array($stmt, 'bind_param'), $this->_bindParams); } return $stmt; } update.php <?php // Include config file require_once "config.php"; // Define variables and initialize with empty values $head = $content = $date = $time = ""; $head_err = $content_err = $date_err = $time_err = ""; // Processing form data when form is submitted if(isset($_POST["id"]) && !empty($_POST["id"])){ // Get hidden input value $id = $_POST["id"]; // Validate head $input_head = trim($_POST["head"]); if( strlen($input_head) > 200){ $head_err = "Max character length is 200."; } elseif(!filter_var($input_head, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){ $head_err = "Please enter a valid head."; } else{ $head = $input_head; } // Validate content $input_content = trim($_POST["content"]); if(empty($input_content)){ $content_err = "Please enter an content."; } else{ $content = $input_content; } // Validate date $input_date = trim($_POST["date"]); if(empty($input_date)){ $date_err = "Please enter an date."; } else{ $date = $input_date; } // Validate time $input_time = trim($_POST["time"]); if(empty($input_time)){ $time_err = "Please enter an time."; } else{ $time = $input_time; } // Check input errors before inserting in database if(empty($head_err) && empty($content_err) && empty($date_err) && empty($time_err)){ // Prepare an update statement $sql = "UPDATE list SET head=?, content=?, date=?, time=?, WHERE id=?"; if($stmt = mysqli_prepare($link, $sql)){ // Bind variables to the prepared statement as parameters mysqli_stmt_bind_param($stmt, "ssssi", $param_head, $param_content, $param_date, $param_time, $param_id); // Set parameters $param_head = $head; $param_content = $content; $param_date = $date; $param_time = $time; $param_id = $id; // Attempt to execute the prepared statement if(mysqli_stmt_execute($stmt)){ // Records updated successfully. Redirect to landing page header("location: index.php"); exit(); } else{ echo "Something went wrong. Please try again later."; } } // Close statement mysqli_stmt_close($stmt); } // Close connection mysqli_close($link); } else{ // Check existence of id parameter before processing further if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){ // Get URL parameter $id = trim($_GET["id"]); // Prepare a select statement $sql = "SELECT * FROM list WHERE id = ?"; if($stmt = mysqli_prepare($link, $sql)){ // Bind variables to the prepared statement as parameters mysqli_stmt_bind_param($stmt, "i", $param_id); // Set parameters $param_id = $id; // Attempt to execute the prepared statement if(mysqli_stmt_execute($stmt)){ $result = mysqli_stmt_get_result($stmt); if(mysqli_num_rows($result) == 1){ /* Fetch result row as an associative array. Since the result set contains only one row, we don't need to use while loop */ $row = mysqli_fetch_array($result, MYSQLI_ASSOC); // Retrieve individual field value $head = $row["head"]; $content = $row["content"]; $date = $row["date"]; $time = $row["time"]; } else{ // URL doesn't contain valid id. Redirect to error page header("location: error.php"); exit(); } } else{ echo "Oops! Something went wrong. Please try again later."; } } // Close statement mysqli_stmt_close($stmt); // Close connection mysqli_close($link); } else{ // URL doesn't contain id parameter. Redirect to error page header("location: error.php"); exit(); } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Update Record</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css"> <link rel="icon" type="image/png" href="https://www.htmlhints.com/image/fav-icon.png"> <meta name="msvalidate.01" content="B7807734CA7AACC0779B341BBB766A4E" /> <meta name="p:domain_verify" content="78ad0b4e41a4f27490d91585cb10df4a"/> <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-145078782-1"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-145078782-1'); </script> <style> .wrapper{ width: 500px; margin: 0 auto; } .hh_button { display: inline-block; text-decoration: none; background: linear-gradient(to right,#ff8a00,#da1b60); border: none; color: white; padding: 10px 25px; font-size: 1rem; border-radius: 3px; cursor: pointer; font-family: 'Roboto', sans-serif; position: relative; margin-top: 30px; margin: 0px; position: absolute; right: 20px; top: 1.5%; } header { color: white; padding: 20px; margin-bottom: 20px; } header a, header a:hover { text-decoration: none; color: white; } </style> </head> <body> <header> <strong><i class="fas fa-chevron-left"></i> <a href="https://www.htmlhints.com/"></a> <i class="fas fa-chevron-right"></i></strong> </header> <div class="wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div class="page-header"> <h2>Update Record</h2> </div> <p>Please edit the input values and submit to update the record.</p> <form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post"> <div class="form-group <?php echo (!empty($head_err)) ? 'has-error' : ''; ?>"> <label>head</label> <input type="text" name="head" class="form-control" value="<?php echo $head; ?>"> <span class="help-block"><?php echo $head_err;?></span> </div> <div class="form-group <?php echo (!empty($content_err)) ? 'has-error' : ''; ?>"> <label>content</label> <textarea name="content" class="form-control"><?php echo $content; ?></textarea> <span class="help-block"><?php echo $content_err;?></span> </div> <div class="form-group <?php echo (!empty($date_err)) ? 'has-error' : ''; ?>"> <label>date</label> <input type="date" name="date" class="form-control" value="<?php echo $date; ?>"> <span class="help-block"><?php echo $date_err;?></span> </div> <div class="form-group <?php echo (!empty($time_err)) ? 'has-error' : ''; ?>"> <label>time</label> <input type="time" name="time" class="form-control" value="<?php echo $time; ?>"> <span class="help-block"><?php echo $time_err;?></span> </div> </div> <input type="hidden" name="id" value="<?php echo $id; ?>"/> <input type="submit" class="btn btn-primary" value="Submit"> <a href="index.php" class="btn btn-default">Cancel</a> </form> </div> </div> </div> </div> <ins class="adsbygoogle my-3" style="display:block" data-ad-format="fluid" data-ad-layout-key="-fb+5w+4e-db+86" data-ad-client="ca-pub-1506739985879215" data-ad-slot="5016195832"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> </body> </html> database.sql -- phpMyAdmin SQL Dump -- version 5.0.3 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Nov 19, 2020 at 09:41 PM -- Server version: 10.4.14-MariaDB -- PHP Version: 7.4.11 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `tododb` -- -- -------------------------------------------------------- -- -- Table structure for table `list` -- CREATE TABLE `list` ( `id` int(20) NOT NULL, `head` varchar(200) NOT NULL, `content` text NOT NULL, `date` date NOT NULL, `time` time NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `list` -- INSERT INTO `list` (`id`, `head`, `content`, `date`, `time`) VALUES (69, 'task', 'test123', '2222-12-13', '22:22:00'); -- -- Indexes for dumped tables -- -- -- Indexes for table `list` -- ALTER TABLE `list` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `list` -- ALTER TABLE `list` MODIFY `id` int(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=70; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Warning: mysqli_stmt_close() expects parameter 1 to be mysqli_stmt, bool given in C:\xampp\htdocs\todolist\update.php on line 75 Code: [Select] $params = array(); $type=array(); $fragments = array(); while (list($chiave,$val) = each($_POST)){ if($val!=""){ $fragments[] = $chiave." = ?"; //echo $chiave; if($chiave=="ritiro" or $chiave=="data") $params[] = normalToDbDate($val); else $params[] = $val; if($chiave=="legale") $type[]='i'; else $type[]='s'; } } $prova=implode("",$type); foreach($params as $param) echo "<p>".$param."</p>"; //echo "val(".count($params).")-->".implode(',',$params); //echo "type(".strlen($prova).")-->".implode("",$type); $sql = $db->prepare("..... AND ".implode(" AND ", $fragments)); array_unshift($params,$prova) call_user_func_array( array( $sql, 'bind_param' ),$params); //$sql->bind_param($prova,$params); $sql->execute(); hi all, with the tructure above i've tried to implement the cration of a dynamic query for a search form. i debugged with echoes and che numbers of bind_param and the those in the prepared statement match in sense that count($params)=strlen($prova). having said that i get this error: Code: [Select] Warning: call_user_func_array() expects parameter 2 to be array, integer given in and no results are shown to me even when the filter match. Hi everyone,I want to learn PHP hook and I try hook examples.I tired this example but I saw only white page.It has a problem but I can't understand it Codes; hook.php <?php class Hooks { public function add($hook,$class=null,$method=null,$args=null) { if (empty($method)) error("You must include a method (function) when defining add_hook."); $this->hooks[$hook][]=array((!empty($class)?array($class,$method):$method),$args); return $this; } public function clear($hook=null) { if (!empty($hook)) unset($this->hooks[$hook]); else $this->hooks=null; } public function run($hook) { if (empty($this->hooks[$hook])) return $this; foreach ($this->hooks[$hook] as $hkey=>$hvalue) { if (is_array($hvalue[0])) $hvalue[0]=array($hvalue[0][0],$hvalue[0][1]); if (!empty($hvalue[1])) if (!is_array($hvalue[1])) call_user_func($hvalue[0],$hvalue[1]); else call_user_func_array($hvalue[0],$hvalue[1]); else call_user_func($hvalue[0]); } return $this; } } ?> script.php <?php // For a function: function doTitle() { echo $current->title; } $hooks->add('head_title',null,'doTitle'); // For a class: class Output { function body_final() { echo implode("\n",$this->body); } } $hooks->add('page_body','Output','body_final'); // To pass multiple arguments into a function, you must use: function test($arg1,$arg2) { echo "Arg1: {$arg1}, Arg2: {$arg2}"; } $hooks->add('page_body',null,'test',array('test','ing')); ?> index.php <?php // You must include the hook file here, or you can make an includes file to do all of your startup (as is normally done). include 'hook.php'; include 'script.php'; ?><!DOCTYPE html> <html> <head> <?php run('head_meta'); ?> <title><?php $hooks->run('head_title'); ?></title> <?php $hooks->run('head_links'); $hooks->run('head_scripts'); ?> </head> <body> <?php $hooks->run('page_body'); ?> </body> </html> Thank you I'm trying to build a landing page with php & js validation - i create the html/php & etc, but the .JS script always hangs on the last "else"... and gives the "123" alert... i debugged it for syntax problem for hundred of time with any online debugging site i know - but it's seems to be something else.... Hi; why does this snippet of code doesn't measure the time required to include the file in milliseconds. The problem is unknown for me because the variable $diff always have the wrong value. Here is the code :
<?php $start = microtime(true); include('/path/to/my/script.php'); $end = microtime(true); $diff = ($end-$start)*1000; echo 'The script took ' . $diff . 'ms to proceed.'; ?>The problem is that the variable $diff return a big number instead of a couple of milliseconds, for example it return a value such as 1416110398494 which is illogical why ? Regards Hello,
I have problem durring binding update query. I can't find what is causing problem.
public function Update(Entry $e) { try { $query = "update entry set string = $e->string,delimiter=$e->delimiter where entryid= $e->id"; $stmt = $this->db->mysqli->prepare($query); $stmt->bind_param('ssi',$e->string,$e->delimiter,$e->id); $stmt->close(); } catch(Exception $ex) { print 'Error: ' .$ex->getMessage(); } }When I run function update I'm getting next error:Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement Can you help me to solve this problem ? Edited by danchi, 17 October 2014 - 10:25 AM. Okay so, I have always been curious, just never have taken the time to ask someone / learn what the differences are in fetches. What does mysql_fetch_array and mysql_fetch_row do thats different from each other? When pulling data from the database, would I like fetch array, or fetch row? or even fetch assoc? Thanks! Hello, i have a query that returns multiple results but in my php query it only returns the first result...ive been checking google on while loops but still havent gotten it to work...would love if someone could look at it...thanks Code: [Select] // while ($result= mysql_fetch_array($stmt)){ while ($stmt->fetch()) { break; // $stmt->close(); // Return unlock code, encoded with JSON $result[] = array( "l_name"=>$l_name, "f_name"=>$f_name, "birth"=>$birth, "expires"=>$expires, ); sendResponse(200, json_encode($result)); return true; sendResponse(400, 'Invalid request'); return false I have this code and Im using a while to fetch all the data where users comments are but i want to change it to fetch only 25 rows at a time and each time it refreshes it fetch's 25 more different rows. Code: [Select] <?php include "../../connect.php"; Header('Cache-Control: no-cache'); Header('Pragma: no-cache'); $username = mysql_real_escape_string($_GET['username']); //If friend is set, then query for it, otherwise return all of the friends comments. $friend = (isset($_GET['friend'])) ? ' AND b.friend = \'' . mysql_real_escape_string($_GET['friend']) . '\' ' : NULL; $sql = "SELECT a.username,a.comment,a.timestamp,a.title,a.picture,a.pic_status,a.pic_url,b.id,c.avatar,c.atimestamp,c.onlinestatus FROM (user_comments as a JOIN accounts as c USING(username))JOIN `user_friends_list` as b ON (b.friend = a.username)WHERE (b.username = '$username' $friend AND b.status = 1) ORDER BY a.id DESC"; $result = mysql_query($sql); $user_xml = "<?xml version=\"1.0\"?>\n"; //$user_xml .= "<root>\n"; if(mysql_num_rows($result) > 0) { while ($row = mysql_fetch_assoc($result)) { $user_xml .= "<comment>\n"; $user_xml .= "<image>" . $row['avatar'] . "</image>\n"; $user_xml .= "<name>" . $row['username'] . "</name>\n"; $user_xml .= "<text>\n"; $user_xml .= "<![CDATA[ ". $row['comment'] ."]]>\n"; $user_xml .= "</text>\n"; $user_xml .= "<time>" . $row['timestamp'] . "</time>\n"; $user_xml .= "<title>" . $row['title'] . "</title>\n"; $user_xml .= "<picture>" . $row['picture'] . "</picture>\n"; $user_xml .= "<status>" . $row['pic_status'] . "</status>\n"; $user_xml .= "<url>" . $row['pic_url'] . "</url>\n"; $user_xml .= "<ntimestamp>" . $row['atimestamp'] . "</ntimestamp>\n"; $user_xml .= "<online>" . $row['onlinestatus'] . "</online>\n"; $user_xml .= "</comment>\n"; } } //$user_xml .= "</root>\n"; echo $user_xml; ?> So i think i can do something like this but im not to sure. just add a if statement Code: [Select] while ($row = mysql_fetch_assoc($result)) { $user_xml .= "<comment>\n"; $user_xml .= "<image>" . $row['avatar'] . "</image>\n"; $user_xml .= "<name>" . $row['username'] . "</name>\n"; $user_xml .= "<text>\n"; $user_xml .= "<![CDATA[ ". $row['comment'] ."]]>\n"; $user_xml .= "</text>\n"; $user_xml .= "<time>" . $row['timestamp'] . "</time>\n"; $user_xml .= "<title>" . $row['title'] . "</title>\n"; $user_xml .= "<picture>" . $row['picture'] . "</picture>\n"; $user_xml .= "<status>" . $row['pic_status'] . "</status>\n"; $user_xml .= "<url>" . $row['pic_url'] . "</url>\n"; $user_xml .= "<ntimestamp>" . $row['atimestamp'] . "</ntimestamp>\n"; $user_xml .= "<online>" . $row['onlinestatus'] . "</online>\n"; $user_xml .= "</comment>\n"; } I only wnat to read 25 comments at a time and when i click a button to read more then it reads 25 more rows but it dose not read the data unless requested... can any one help me? Hi. I am a little confused about PDO, its classes and the general oop aspects of it. If you at the below code:
<?php try { $handler = new PDO('mysql:host=127.0.01;dbname=app', 'root',''); $handlser->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); }catc(PDOException $e) { echo $e->getMessage(): die(); } $query = $handler->query('SELECT * FROM table'); while($r = $query->fetch(PDO::FETCH_OBJ)) { echo $r->message; }What's confusing me is that the fetch method is a method within the PDOSTATEMENT class so how come an object hasn't been created before hand in order to use the method? Furthermore it appears the method is a static method within the PDOSTATEMENT class so how come the double semi colon is being used such as: PDOSTATEMENT::FETCH? Any help would be appreciated. Thanks. There is a school locator script at https://www.ocps.net/parents/pages/FindaSchool.aspx When we input any address it returns schools located in that locality. For example: Use these details and submit the form Street Number : 3902 Street Name : Bobolink Street Type : Lane City : Orlando It returns a row having three schools Elementary,Middle and High school On clicking the more button it takes to the respective school details So for each school I need the respective school names Audobon Elementary Glenridge Middle Winter Park High Please suggest some ways to achieve this functionality Thanks _________________________________________________ ____________________ http://travelinfo.techserveglobal.com/ http://blog.techserveglobal.com/ Im not sure where to post this but since it includes php il post it here instead of in the mysql forum. ok so, i have a table and i get the values using while($row = mysql_fetch_array($result)){ and then echo them in rows. that works fine but i need to add a class to the last row of my table. I would need somehow to fetch the last row of the array and make it echo something different. Any help is appreciated Thank you Hi, I am quite new to PHP and to learn more about it I decided I would make a little project to easy my life a little bit I want to make a site that fetches lunch menus from the restaurants nearby my work. I would just like some help getting pointed in the right direction on how to make this happen Thanks! Br, Niklas Well lets say I have a class called Private_Item with a property like $owner. The class itself and constructor will look like the way below: (Note the Private_Item class extends from a parent class called Item, this is not to be worried here) Code: [Select] class Private_Item extends Item{ private $iid; // The itemname and category properties already exist for parent class private $owner; private $quantity; private $status = "Available"; public function __construct($name, $owner, $quantity){ parent::__construct($name); $this->owner = new User($owner); $this->quantity = $quantity; } } Whenever I define a variable like $item = new Private_Item($itemname, $itemowner, $quantity), the $itemowner is used as reference to instantiate a User object, and then passed to the property $this->owner. In this way, I have actually instantiated two objects at once. One for the item, the other for the user who owns this item. I have a question about using PDO's fetch class method though. I'd like to use it to retrieve database info and instantiate a Private_Item object immediately after fetching it from MySQL database. The code looks like below: Code: [Select] $item = $stmt->fetch(PDO::FETCH_CLASS, "Private_Item"); The real question is, can the user object still be instantiated in the meantime? I am not quite sure about this, and I may end up having only one $item object but its property $item->owner is not. For those of you familiar with advanced PDO stuff, please lemme know if I can instantiate a subsequent object with the method fetch(PDO::FETCH_CLASS). Thanks. Hi all, I need some help with my code as I have a hard time with fetching the value from the stdclass. I am using json data to convert it to PHP so I would like to fetch the "appears" data from the stdclass object. When I try this: echo $data->appears;
I'm getting this: Notice: Trying to get property of non-object in /home/username/public_html/foldername/script.php on line 22
I have also tried this: echo $data[0]->appears->value;
And this: echo $data->appears[0]->value;
I am still get the same error so I dont know what to do to resolve it.
Full code: <?php ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); $json = '{"data":{"185.220.101.46":{"domains_count":0,"domains_list":null,"updated":"2019-12-02 22:04:25","spam_rate":1,"frequency":6827,"frequency_time_24h":106,"frequency_time_1h":2,"network_type":"hosting","in_antispam":1,"in_security":0,"appears":1,"country":"DE","submitted":"2018-01-11 20:34:37","frequency_time_10m":2,"sha256":"e39d4a9be2f210d1a75ba2b5ece08a4b35e99002b03aeb6ceaad1d98de87c248"}}}'; // Converts it into a PHP object $data = json_decode($json, true); //print_r($data); echo $data["appears"]->value ."<br/>"; //var_dump($data[1]->{'updated'}); //echo $data->updated[1]->value; ?>
STDClass object: Array ( [data] => Array ( [185.220.101.46] => Array ( [domains_count] => 0 [domains_list] => [updated] => 2019-12-02 22:04:25 [spam_rate] => 1 [frequency] => 6827 [frequency_time_24h] => 106 [frequency_time_1h] => 2 [network_type] => hosting [in_antispam] => 1 [in_security] => 0 [appears] => 1 [country] => DE [submitted] => 2018-01-11 20:34:37 [frequency_time_10m] => 2 [sha256] => e39d4a9be2f210d1a75ba2b5ece08a4b35e99002b03aeb6ceaad1d98de87c248 ) ) )
Var_dump: array(1) { ["data"]=> array(1) { ["185.220.101.46"]=> array(15) { ["domains_count"]=> int(0) ["domains_list"]=> NULL ["updated"]=> string(19) "2019-12-02 22:04:25" ["spam_rate"]=> int(1) ["frequency"]=> int(6827) ["frequency_time_24h"]=> int(106) ["frequency_time_1h"]=> int(2) ["network_type"]=> string(7) "hosting" ["in_antispam"]=> int(1) ["in_security"]=> int(0) ["appears"]=> int(1) ["country"]=> string(2) "DE" ["submitted"]=> string(19) "2018-01-11 20:34:37" ["frequency_time_10m"]=> int(2) ["sha256"]=> string(64) "e39d4a9be2f210d1a75ba2b5ece08a4b35e99002b03aeb6ceaad1d98de87c248" } } }
Can you please show me an example how I can fetch the `appears` from the stdclass object? Any advice would be much appreciated. Edited December 2, 2019 by mark107Hi, I'm wondering if theres a shortcut to a potential problem I have. I'm currently running a query on my website to pull all the fields from a table in my database, for the data to be used on various parts of the page. Usually I would do something as follows Code: [Select] $result = mysql_query("SELECT * FROM table WHERE page='1'"); while ($row=mysql_fetch_array($result)) { $title = $row["title"]; $data = $row["data"]; } And so on and so forth. I would then call the appropriate data by echoing $data for example. However, my table contains a lot more rows than i've mentioned (Around 25 or so). Rather than assigning each to a variable and having a large portion of variable assignments at the top of the page, is there any clever way of putting all of these values inside of an array. So for example, I could call $array_data["title"] or $array_data["data"]?? So it keeps the same key, but puts it inside of an array that I don't have to loop through each time? Hope that makes sense! Thanks, Edd |