PHP - Warning: Mysqli_stmt::bind_param(): Number Of Variables Doesn't Match Number Of Parameters In Prepared Statement
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. Similar TutorialsI'm getting the dreaded " Invalid parameter number: number of bound variables does not match number of tokens" error and I've looked at this for days. Here is what my table looks like:
| id | int(4) | NO | PRI | NULL | auto_increment | | user_id | int(4) | NO | | NULL | | | recipient | varchar(30) | NO | | NULL | | | subject | varchar(25) | YES | | NULL | | | cc_email | varchar(30) | YES | | NULL | | | reply | varchar(20) | YES | | NULL | | | location | varchar(50) | YES | | NULL | | | stationery | varchar(40) | YES | | NULL | | | ink_color | varchar(12) | YES | | NULL | | | fontchosen | varchar(30) | YES | | NULL | | | message | varchar(500) | NO | | NULL | | | attachment | varchar(40) | YES | | NULL | | | messageDate | datetime | YES | | NULL |Here are my params: $params = array( ':user_id' => $userid, ':recipient' => $this->message_vars['recipient'], ':subject' => $this->message_vars['subject'], ':cc_email' => $this->message_vars['cc_email'], ':reply' => $this->message_vars['reply'], ':location' => $this->message_vars['location'], ':stationery' => $this->message_vars['stationery'], ':ink_color' => $this->message_vars['ink_color'], ':fontchosen' => $this->message_vars['fontchosen'], ':message' => $messageInput, ':attachment' => $this->message_vars['attachment'], ':messageDate' => $date );Here is my sql: $sql = "INSERT INTO messages (user_id,recipient, subject, cc_email, reply, location,stationery, ink_color, fontchosen, message,attachment) VALUES( $userid, :recipient, :subject, :cc_email, :reply, :location, :stationery, :ink_color, :fontchosen, $messageInput, :attachment, $date);"; And lastly, here is how I am calling it: $dbh = parent::$dbh; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); if (empty($dbh)) return false; $stmt = $dbh->prepare($sql); $stmt->execute($params) or die(print_r($stmt->errorInfo(), true)); if (!$stmt) { print_r($dbh->errorInfo()); }I know my userid is valid and and the date is set above (I've echo'd these out to make sure). Since the id is auto_increment, I do not put that in my sql (though I've tried that too), nor in my params (tried that too). What am I missing? I feel certain it is something small, but I have spent days checking commas, semi-colons and spelling. Can anyone see what I'm doing wrong? 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, Actually I am working on text annotation tool, for this I have downloaded from github (https://github.com/ag-sc/SANTO), after ran the code I am getting error while uploading file into tool like Warning*: array_combine(): Both parameters should have an equal number of elements in *C:\xampp\htdocs\SANTO\blocks\importpub.ui.inc.php* on line *141* *Fatal error*: Uncaught mysqli_sql_exception: Column 'Text' cannot be null in C:\xampp\htdocs\SANTO\blocks\importpub.ui.inc.php:145 Stack trace: #0 C:\xampp\htdocs\SANTO\blocks\importpub.ui.inc.php(145): mysqli_stmt->execute() #1 C:\xampp\htdocs\SANTO\index2.php(36): include('C:\\xampp\\htdocs...') #2 C:\xampp\htdocs\SANTO\index2.php(54): action_include('importpub.ui') #3 {main} thrown in *C:\xampp\htdocs\SANTO\blocks\importpub.ui.inc.php* on line *145* Please can anyone please help me how to fix this issue, actually they have given readme file I didn't get the solution. Thank you in advance. I wrote a code with prepared statements MySQLi: Code: [Select] <?php include_once 'dbinfo.php'; if(isset($_POST['kuldes'])) { $name = trim($_POST['nev']); $username = $_POST['felh_nev']; $password = $_POST['jelszo']; $email = $_POST['email']; $phone = $_POST['telefon']; $gender = $_POST['sex']; $hobby = $_POST['hobby']; $regfelt = $_POST['regfelt']; $name = strip_tags($name); $name = stripslashes($name); $username = strip_tags($username); $email = strip_tags($email); $phone = strip_tags($phone); $date = date("d-m-Y"); if($name == NULL || $username == NULL || $password == NULL || $email == NULL || $phone == NULL || $gender == NULL) { echo "Please complete the form below or one of the boxes is empty."; } elseif(strlen($username) <= 3 || strlen($username) >= 30){ $final_report.="Your username must be between 3 and 30 characters.."; } elseif($stmt = $connect->prepare('SELECT * FROM users WHERE username=?')) { $stmt->bind_param('s', $username); $stmt->execute(); $stmt->bind_result($username); while ($stmt->fetch()) { printf("Name: %s\n", $name); $final_report.="The username is already in use!"; } $stmt->close(); }elseif(strlen($password) <= 6 || strlen($password) >= 12){ $final_report.="Your password must be between 6 and 12 digits and characters.."; } elseif(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){ $final_report.="Your email address was not valid.."; } elseif(!eregi("^[0-9]{1,3}-[0-9]{1,3}-[0-9]{1,10}$",$phone)){ $final_report.="Phone number is invalid. Only numbers with hyphen. Allowed format: countrycode-areacode-phonenumber"; } elseif(!isset($hobby)){ $final_report.="Youd didn't select any hobbies"; } elseif(!isset($regfelt)){ $final_report.="You didn't accept the terms"; } else { if ($stmt = $connection->prepare('INSERT INTO users(name,sex,email,phone_number,username,password,hobby) VALUES(?, ?, ?, ?, ?, ?, ?)')) { $stmt->bind_param('sssssss', $name, $sex, $email, $phone_number, $username, $password, $hobby); $stmt->execute(); $stmt->close(); } }}?> <h1>Registration Form</h1> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" name="registration_form" method="POST"> <p>Name: <input type="text" name="nev" value="<?php echo (isset($name) ? $name : ''); ''?>" size=25></p> <p>Username: <input type="text" name="felh_nev" value="<?php echo (isset($username) ? $username : ''); ?>" size=10></p> <p>Password: <input type="password" name="jelszo" size=10></p> <!--<p>Password again:<input type="password" name="password_confirmation"></p>--> <p>E-mail: <input type="text" name="email" value="<?php echo (isset($email) ? $email : ''); ?>"/></p> <p>Phone number: <input type="text" name="telefon" value="<?php echo (isset($phone) ? $phone : ''); ?>"/></p> <p>Sex: <label><input type="radio" name="sex" value="no" >Female</label> <label><input type="radio" name="sex" value="ferfi" >Male</label></p> <p>Favorite hobbies (Using CTRL you can select more than one):</p> <select name="hobby[]" size="4" multiple> <option value="sport">Sport</option> <option value="mozi">Movies</option> <option value="kirandulas">Hiking</option> <option value="olvasas">Reading</option> </select> <p><input name="regfelt" type="checkbox" value="elfogad">I accept the terms!</p> <p><input name="kuldes" type="submit" value="Submit form"> <input name="reset" type="reset" value="delete"></p> <table width="501" border="1"> <tr> <td><?php echo $final_report; ?></td> </tr> </table> <p> </p> </form>And I get the following error message: Warning: mysqli_stmt::bind_result() [mysqli-stmt.bind-result]: Number of bind variables doesn't match number of fields in prepared statement in I don't understand what's the problem is, many people can't give solution for this? Anyone who can help me? It's brain racking. This is my preg_match code:
preg_match("/(\d+)|(T)|(A)/", $link, $matches, PREG_OFFSET_CAPTURE, ($off-30)
It works and matches the number I want, except it only returns the first character in the $matches array. For instance, if the number it finds is 10, it only returns 1. Now I understand that is what preg_match does, but how would I make that regex ungreedy? I tried adding a *, but it just made an error, and preg match all would keep searching for strings after the first one. All I want is for the first number, regardless of the length of it, to be returned in full. Thanks for any help.
I need to display a number(the number is retrieved from the db) in the form input field such that only the last 4 digits is visbile, the remaining can be masked as * or X or whatever is applicable. I know the last 4 can be obtained as follows: Code: [Select] $number=substr($number,-4,4); But when i hit the submit button the form validates the input field and checks if the number is a valid number of a specific format. Therefore when I click on the submit button then I should still be able to unmask the masked numbers or do something similar that would help me validate the whole number. Code: [Select] <input type="text" name="no" value="<?php if(!empty($number)){ echo $number;} ?>"> My code keeps giving me and error on 22 saying: Warning: mysqli_stmt_bind_param() [function.mysqli-stmt-bind-param]: Number of variables doesn't match number of parameters in prepared statement in E:\xampp\htdocs\m9\findRecords2.php on line 22 Code: [Select] <html> <head> <title>Display Records</title> </head> <body> <?php $conn = new mysqli("localhost", "proxy_user", "my*password", "m9"); if (mysqli_connect_errno()){ echo 'Cannot connect to database: ' . mysqli_connect_error($conn); } else{ //read keyword from user if(!empty($_POST["keyword"])){ $keyword = $_POST["keyword"]; // create prepared statement if ($query = mysqli_prepare($conn, "SELECT FirstName, LastName, Age, Hometown, Job FROM people WHERE age <='" . $keyword ."' " )) { // bind parameters mysqli_stmt_bind_param ($query, "i", $keyword); //run the query and keep results in $result variable mysqli_stmt_execute($query); // bind variables to prepared statement mysqli_stmt_bind_result($query, $FirstName, $LastName, $Age, $Hometown, $Job); // fetch values while (mysqli_stmt_fetch($query)) { echo "<strong>$LastName, $FirstName</strong> from $Hometown<br/>age: $Age, occupation: $Job <br/><br/>"; } //free memory used by a result handle mysqli_stmt_close ($query); } else //problem with a query echo "Error: " . mysqli_error($conn); } else { //no keyword echo "No keyword was specified"; } mysqli_close($conn); } ?> </body> </html> keyword and age are ints can anybody please help 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 Hey everyone, I'm new to PHP so excuse me if this is an obvious question: I've got a horizontal scrolling image gallery as an include, as it will be used in dozens of pages. Each page that includes the image gallery will be using different pictures and in different numbers (anywhere from 1 - 15 images). In each page that includes the image gallery, I've turned each image to be used into a variable.. $image 1 = "images/image1.jpg"; $image 2 = "images/image2.jpg"; ... $image 7 = "images/image7.jpg"; etc. Now, I imagine I need to write a loop in the include that will account for as many pictures as there are variables in each page, without adding links for variables that aren't in the page in question. Something like (simplified): Defined on page: $image 1 = "images/image1.jpg"; $image 2 = "images/image2.jpg"; $image 3 = "images/image3.jpg"; $image 4 = "images/image4.jpg"; Loop in photo gallery include: <?php for($i = 1; $i <=15; $i++) { $imagei = ("$" ."image".$i); if (defined($imagei)) { echo '<li><a href="' .$imagei.'">'; echo '<img src=" '.$imagei.'" >'; echo '</a></li>'; } } ?> I know this doesn't work because $imagei isn't referring to the defined variables on the external page, but I'm not sure exactly where to go from here. As in, $imagei in the first execution of the loop is equal to "$image1", but how do I link that to the $image1 variable defined in the page (as "image/image1.jpg") to display the image? Does that make sense? Thanks! Hey I have a string that looks like the following: Quote top-php-tutorials-2.html I have a script that cycles through each page. The 2 in the quote above is the page number. How can I extract the number between the - and the .html and replace it with another number? I've tried Code: [Select] substr($engine->selectedcaturl, 0,-6).$v.".html"But then I realised this only works for numbers that are 1 digit long Any input would be appreciated hello, i have a start time and an end time (no dates). the following works great, except for when the start time is at night, and the end time is in the morning. im thinking if i can do an if the number is negative, add 24, that it will resolve my issue. any ideas? Code: [Select] $tbilled = $tfinish - $tstart; Hello all! New here and new to PHP. I have an old script that was built for PHP 5.X and need some help getting it to work with PHP 7.X. According to the PHP manual I need to pass the db connection as the first argument. I do get the display error "SQL Error: Can't select DB" and in the logs show "PHP Warning: mysqli_select_db() expects exactly 2 parameters, 1 given". <?php extract($_REQUEST); $DB_HOST="localhost"; //Host $DB_DATABASE="babyyoda"; //database name $DB_USER="mando"; //database username $DB_PASSWORD="password"; //databse password $ADMIN_EMAIL='admin@example.com'; $TEMPLATES='./templates/'; $URL_BASE='http://example.com/banners/'; $PATH='/var/www/vhosts/example.com/httpdocs/banners/'; $BANNERS_PATH=$PATH.'banners/'; $BANNERS_URL=$URL_BASE.'banners/'; $DB_TABLE_CATEGORIES='ban_categories'; $DB_TABLE_SUBCATEGORIES='ban_subcategories'; $DB_TABLE_SUBCATEGORIES_BANNERS='ban_subcategories_banners'; $DB_TABLE_BANNERS='ban_banners'; $DB_TABLE_USERS='ban_users'; $DB_TABLE_SETTINGS='ban_settings'; $IMAGE_MAGICK_PATH='/usr/bin/'; //$IMAGE_MAGICK_PATH='/usr/local/bin/'; // on some servers it may be like this $TEMPLATE_EXECUTE_PHP=1; // set to 1 to allow use of php inside of templates $CRYPT_SALT='ef&dF%HGRTSvsw35'; $TYPES[1]='Jpeg'; $TYPES[2]='Gif'; $TYPES[3]='Flash'; // dont change flash should be "3" //$LINKED_SCRIPTS['Galleries Manager']='/galleries/admin/'; //$LINKED_SCRIPTS['Flash Manager']='/flash/admin/'; $NATS=0; //$PASS_VARIABLES=array('campaign','program'); define('CONFIG_INCLUDED',1); mysqli_connect($DB_HOST, $DB_USER, $DB_PASSWORD) or die("SQL ERROR: Can't Connect to DB"); mysqli_select_db($DB_DATABASE) or die("SQL ERROR: Can't select DB"); error_reporting(0); ini_set('session.gc_maxlifetime',3600); ?>
I came up with the below but I don't know where to insert these two statements and what to remove. $link = mysqli_connect($DB_HOST, $DB_USER, $DB_PASSWORD); mysqli_select_db($link, $DB_DATABASE);
Hi guys, I have coded this, however I have received an error msg, can someone advice me in this? Thank you Warning: mysqli_query() expects at least 2 parameters, 1 given in D:\inetpub\vhosts\abc.com\httpdocs\report.php on line 166 Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in D:\inetpub\vhosts\abc.com\httpdocs\report.php on line 167 <?php $sql = mysqli_query("SELECT * FROM tutor_preferred_district ORDER BY district_id ASC"); while($data = mysqli_fetch_array($sql)) { echo '<input name="district" type="checkbox" id="'.$data['district_id'].'" value="'.$data['district_id'].' class="required" title="Please check at least 1 location."> <label for="'.$data['district_id'].'">'.$data['district_name'].'</label>'; } ?> I am trying to create a simple forum in a MVC architecture. After deciding to venture into the realm of prepared statements, I have this line in my script Quoteif ($stmt = $conn->prepare('SELECT username FROM users WHERE username = ?')) { Everything was working fine. I reviewed my code to adjust it to my old habits, and realized that I had hardcoded the TABLE NAME rather than using a variable. I updated my code to Quote$table = "users"; if ($stmt = $conn->prepare('SELECT username FROM $table WHERE username = ?')) { and results from my SELECT statement vanished. Is the use of a variable for a table's name outdated? Even possible?? So I wrote my first PHP Function early tonight and now I'm getting all excited! Is there any reason why I could not put a Prepared Statement in a Function so I could pass in a "member_id", run a query, and determine the "# of Posts" the Member has in total and then return that? Debbie For some reason this just isn't inserting... HTML snippet: Code: (HTML) [Select] <form name="testimonials_form" method="post" action="insert/"> Name <input type="text" name="from" maxlegnth="100" /> Location <input type="text" name="where" maxlegnth="100" /> Text Snippet <input type="text" name="text" maxlegnth="255"> <input type="submit" name="submit" value="Continue" /> </form> PHP Snippet: Code: (PHP) [Select] <?php $from = $_POST['from']; $where = $_POST['where']; $text = $_POST['text']; if (!$from || !$where || !$text) { $error = "You have missed some fields."; $solution = "Please go back and <a href=\"javascript:history.go(-1)\" target=\"_self\">try again</a>."; } else { $data_array = array( ':from' => $from, ':where' => $where, ':text' => $text); $insert_testimonial = $connect->prepare("INSERT INTO `testimonials` (text, from, where) VALUES (:text, :from, :where)"); $insert_testimonial->execute($data_array); $amount = $insert_testimonial->rowCount(); if ($amount < 1) { $error = "Something went wrong."; $solution = "Please go back and <a href=\"javascript:history.go(-1)\" target=\"_self\">try again</a>."; } else { header ("Location: ../"); } } ?> All I keep getting back is my custom error "Something went wrong." so there's no 500 error (internal server error) and if I echo $from, $where and $text it displays what I typed in the form, I've re-written it about 5 times in case I wrote it wrong or something but still no luck. I know there can't be a symbol missing or in the wrong place since it would return a 500 error. Does anyone have any clue as to what's up with it? I've written codes like this countless times but this just doesn't seem to be working, so I must be missing something. Hello there! I've got this code: <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); error_reporting(E_ALL); if (isset($_POST["id"]) && !empty($_POST["id"])) { require_once "login.php"; $stmt = $conn->prepare("DELETE FROM teamlid WHERE lidnummer = ?"); $stmt->bind_param("i", $param_id); $param_id = $_POST["id"]; $stmt->execute(); if ($stmt) { header("location: teamsTabel.php"); exit(); } else { echo "Oeps, er is iets verkeerds gegaan. Probeer het later nog een keer."; } mysqli_close($conn); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Gegevens inzien</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css"> <style type="text/css"> .wrapper { width: 500px; margin: 0 auto; } </style> </head> <body> <div class="wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div class="page-header"> <h1>Gegevens verwijderen</h1> </div> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> <div class="alert alert-danger fade in"> <input type="hidden" name="id" value="<?php echo trim($_POST["id"]); ?>" /> <p>Weet je zeker dat je deze gegevens wilt verwijderen?</p><br> <p> <input type="submit" name="submitDeleteBtn" value="Ja" class="btn btn-danger"> <a href="teamsTabel.php" class="btn btn-default">Nee</a> </p> </div> </form> </div> </div> </div> </div> </body> </html> Another PHP script I tried didn't work either: <?php if (isset($_POST["id"]) && !empty($_POST["id"])) { require_once "login.php"; // DELETE query om op basis van lid.lidnummer en postcode.postcode de tabellen te legen. $sql = "DELETE lid, postcode FROM lid INNER JOIN postcode WHERE lid.postcode = postcode.postcode AND lid.lidnummer = ?"; if ($stmt = mysqli_prepare($conn, $sql)) { mysqli_stmt_bind_param($stmt, "s", $param_id); $param_id = trim($_POST["id"]); if (mysqli_stmt_execute($stmt)) { header("location: read.php"); exit(); } else { echo "Oeps, er is iets verkeerds gegaan. Probeer het later nog een keer."; } } mysqli_stmt_close($stmt); mysqli_close($conn); } else { if (empty(trim($_GET["id"]))) { header("location: error.php"); exit(); } } ?> But they're both not doing what I want: deleting the rows in the "teamlid" table where the id matches the column "lidnummer". I'm not getting any errors. When using the delete statement directly in MySQL using a hardcoded "lidnummer" it works. But it's not using the lidnummer here to delete the corresponding columns in the table. I can't get my head around it. Do you guys have any ideas? Thanks! Edited May 28, 2020 by DeckDekkI have an array that has comma sep values. I am wanting to run a select statement that includes a NOT IN function. SELECT user_firstname, user_lastname, user_id FROM ssm_user WHERE user_role_id = ? and where user_id NOT IN(?) Is this possible, oir does the ? just represent a literal string. If so do i need to convert the array to a string before running the above? Hi
I wonder if someone may help, I have already had a good look online, but not found a solution that works with what i'm trying to do
At the moment I have the following code and it works great
$stmt = $mysqli->prepare("SELECT d.id,d.val FROM datalog pd LEFT JOIN datafeeds d ON d.id = pd.did WHERE pd.pid = ? AND pd.aa = ? AND pd.bb = ?"); $stmt->bind_param('sii', $id,$aa=1,$bb=1); $stmt->execute(); $stmt->bind_result($id,$val); mysqli_stmt_store_result($stmt); if(mysqli_stmt_num_rows($stmt) != 0) { while ($stmt->fetch()) { $array[] = array('numA'=>$id, 'numB'=>$val); } } return $array;but what I would like to do is use an array, which could be any length $array = array(1,2,4,7,9);and change my query to include d.type IN ($array)could someone give me some help? thanks |