PHP - Mysqli Prepared Statement - Join Tables
Hi,
I want to restructure my database tables so that I can have one table (t_incidents) to hold foreign keys instead of holding foreign keys in the table "t_persons" because one person can commit more than one offense. However, I need to know how the join should be implemented with MySQLi prepared statement. I need some one to review the following statement for me and advise: if ($stmt = $mysqli->prepare("Select t_persons.PersonID ,t_persons.FamilyName ,t_persons.FirstName ,t_persons.OtherNames ,t_persons.Gender ,t_persons.CountryID ,t_persons.ImagePath ,t_incidents.IncidentID ,t_incidents.Incident ,t_incidents.IncidentDate ,t_incidents.PersonID ,t_incidents.CountryID ,t_incidents.OffenceKeywordID ,t_incidents.StatusID ,t_incidents.AgencyID ,t_status.StatusID ,t_status.Status ,t_offencekeyword.KeywordID ,t_offencekeyword.Keyword ,t_countries.CountryID ,t_countries.Country ,t_agencies.AgencyID ,t_agencies.Agency From t_persons Inner Join t_incidents On t_persons.PersonID = t_incidents.PersonID Inner Join t_incidents On t_countries.CountryID = t_incidents.CountryID Inner Join t_incidents On t_status.StatusID = t_incidents.StatusID Inner Join t_incidents On t_offenceskeyword.KeywordID = t_incidents.KeywordID Inner Join t_incidents On t_agencies.AgencyID = t_incidents.AgencyID Where t_persons.PersonID = '$PersonID'")) {Regards. josephbupe Similar TutorialsI 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. Hi,
I have the following query
SELECT user_details.User_club_ID, user_details.fname, user_details.lname, user_details.email, user_details.club_No club.CLUBCODE, club.club_id FROM user_details, club WHERE club_id = $cid AND user_details.club_No = club.CLUBCODE AND user_status = 'active'";which I converted to a prepared statement as SELECT user_details.User_club_ID, user_details.fname, user_details.lname, user_details.email, user_details.club_No club.CLUBCODE, club.club_id FROM user_details, club WHERE club_id = ? AND user_details.club_No = club.CLUBCODE AND user_status = ?";Please note that user_status is a field in the table user_details. The original query (non -PDO) works correctly. I want to know if this is correct and that the comparison in the WHERE clause i.e. user_details.club_No = club.CLUBCODE is security safe. If not then how should this be modified. Also if there is a better way to write this statement, kindly show that as well. Thanks Thanks all ! Edited by ajoo, 11 December 2014 - 02:35 AM. I have just got hold of a MySQLi class (a wrapper to the built in one of course), and for EVERY query sent they have used prepared statements. Is this right? I expected it to just send using the mysqli_query function (with the prepared statements option if selected). Should you send ALL queries using a prepared statement? What (if any) are the downfalls of using prepared statements? I'm trying to work with prepared statements, but unfortunately I do not get any result back. I also tried while($stmt->fetch()) { ... }, with the same effect.
Does anyone have a suggestion?
Thanks in advance.
<?php MAKING CONNECTION if ($stmt = $mysqli->prepare("SELECT year FROM SOMETABLE WHERE id = ? LIMIT 1")) { $id = $_GET['id']; $stmt->bind_param("i", $id); $stmt->execute(); $stmt->bind_result($year); $stmt->fetch(); echo $year; $stmt->close(); } $mysqli->close(); ?> Hi ! I am trying to translate my mysqli count query that works perfectly into prepared statements. Unfortunately, after playing around and using my knowledge of PS, I have come up with this script which fails to execute and returns a http 500 error. I may have missed something very silly, I require some guidance on fixing the error.
<?php $conn = mysqli_connect("xxxx", "xxxx", "xxxx", "xxx"); $sel_query = "SELECT S1, B1 COUNT(IF(S1 = ?, 1, NULL)) 'Accepted', COUNT(IF(S1 = ?, 1, NULL)) 'Rejected', COUNT(IF(S1 = ?, 1, NULL)) 'Under_Review' FROM Enrol"; $stmt = $conn->prepare($sel_query); $Accepted="Accepted"; $Rejected="Rejected"; $Under_Review="Under Review"; $stmt->bind_param("sss",$Accepted, $Rejected, $Under_Review); $stmt->execute(); $result = $stmt->get_result(); // get the mysqli result if($result->num_rows === 0) exit('No records found!'); while($row = $result->fetch_assoc()) { ?> <tr> <td><?php echo $row["Accepted"]; ?></td> <td><?php echo $row["Rejected"]; ?></td> <td><?php echo $row["Under_Review"]; ?></td> </tr> </table>
Edited June 24, 2020 by PythonHelp I have a prepared statement class for MYSQL, since in PHP 5 this is now changing to mysqli; I'm looking for some help in changing the code from my existing class to the new mysqli.
I have done some research online about changing from mysql to mysqli but the changes I made seems to only cause issues with connecting to the database.
After many hours of changing the existing file using the research online, I've decided to start again and ask others if they would be ever so kind to help this noob out and point out which parts of the script needs to be changed.
Thank you for reading.
<?php class Database { private $host; private $user; private $pass; private $name; private $link; private $error; private $errno; private $query; function __construct($host, $user, $pass, $name = "", $conn = 1) { $this -> host = $host; $this -> user = $user; $this -> pass = $pass; if (!empty($name)) $this -> name = $name; if ($conn == 1) $this -> connect(); } function __destruct() { @mysql_close($this->link); } public function connect() { if ($this -> link = mysql_connect($this -> host, $this -> user, $this -> pass, TRUE)) { if (!empty($this -> name)) { if (!mysql_select_db($this -> name, $this->link)) $this -> exception("Could not connect to the database!"); } } else { $this -> exception("Could not create database connection!"); } } public function close() { @mysql_close($this->link); } public function query($sql) { if ($this->query = @mysql_query($sql, $this->link)) { return $this->query; } else { $this->exception("Could not query database!"); return false; } } public function num_rows($qid) { if (empty($qid)) { $this->exception("Could not get number of rows because no query id was supplied!"); return false; } else { return mysql_num_rows($qid); } } public function fetch_array($qid) { if (empty($qid)) { $this->exception("Could not fetch array because no query id was supplied!"); return false; } else { $data = mysql_fetch_array($qid); } return $data; } public function fetch_array_assoc($qid) { if (empty($qid)) { $this->exception("Could not fetch array assoc because no query id was supplied!"); return false; } else { $data = mysql_fetch_array($qid, MYSQL_ASSOC); } return $data; } public function fetch_object($qid) { if (empty($qid)) { $this->exception("Could not fetch object assoc because no query id was supplied!"); return false; } else { $data = mysql_fetch_object($qid); } return $data; } public function fetch_all_array($sql, $assoc = true) { $data = array(); if ($qid = $this->query($sql)) { if ($assoc) { while ($row = $this->fetch_array_assoc($qid)) { $data[] = $row; } } else { while ($row = $this->fetch_array($qid)) { $data[] = $row; } } } else { return false; } return $data; } public function last_id() { if ($id = mysql_insert_id()) { return $id; } else { return false; } } private function exception($message) { if ($this->link) { $this->error = mysql_error($this->link); $this->errno = mysql_errno($this->link); } else { $this->error = mysql_error(); $this->errno = mysql_errno(); } if (PHP_SAPI !== 'cli') { ?> <div class="alert-bad"> <div> Database Error </div> <div> Message: <?php echo $message; ?> </div> <?php if (strlen($this->error) > 0): ?> <div> <?php echo $this->error; ?> </div> <?php endif; ?> <div> Script: <?php echo @$_SERVER['REQUEST_URI']; ?> </div> <?php if (strlen(@$_SERVER['HTTP_REFERER']) > 0): ?> <div> <?php echo @$_SERVER['HTTP_REFERER']; ?> </div> <?php endif; ?> </div> <?php } else { echo "MYSQL ERROR: " . ((isset($this->error) && !empty($this->error)) ? $this->error:'') . "\n"; }; } } ?> <?php //COOKIE CHECKER if (isset($_COOKIE["person"])){ if (filter_var($_COOKIE["person"], FILTER_VALIDATE_INT)){ $user_id = $_COOKIE["person"]; //DATABASE CONNECTION VARIABLES $myserver ="localhost"; $myname = "username"; $mypassword = "password"; $mydb ="dbname"; /*SQL CONNECTION*/ // Create connection $conn = new mysqli($myserver, $myname, $mypassword, $mydb); // Check connection if ($conn->connect_error) { echo '<!DOCTYPE HTML> <HTML> <HEAD> <TITLE>test</TITLE> </HEAD> <BODY> <H1>Decline of the Han - Three Kingdoms</H1>'; die("Connection failed: " . $conn->connect_error); echo '</BODY> </HTML>'; } else { //COUNT USER $cquery = "SELECT COUNT(*) AS usercheck FROM Players WHERE ID = ?"; $cid = $conn->prepare($cquery); $cid->bind_param('i', $user_id); $cid->execute(); $cid->bind_result($usercheck); $cid->fetch(); if ($usercheck ==1){ if (isset($_POST["profile"])){ if(!filter_var($_POST["profile"], FILTER_SANITIZE_STRING)){ echo '<!DOCTYPE HTML> <HTML> <HEAD> <TITLE>test</TITLE> </HEAD> <BODY>'; echo '<P class="error">Unable to filter bio <a href="biography.php">return</a></P>'; echo '</BODY> </HTML>'; } else { $profile = $_POST["profile"]; $sql = "UPDATE Player_Data SET Bio =? WHERE ID=?"; $q = $conn->prepare($sql); $q->bind_param("si", $profile, $user_id); $q->execute(); echo '<P>Biography altered <a href="biography.php">return</a></P>'; //close connection $conn->close(); } } } else { echo '<!DOCTYPE HTML> <HTML> <HEAD> <TITLE>test</TITLE> </HEAD> <BODY>'; echo '<P class="error">'.$usercheck.' '.$user_id.'</P>'; echo '<P class="error">No such user found!</P>'; //close connection $conn->close(); //foot echo '</BODY> </HTML>'; } //end connection check } } else { echo '<!DOCTYPE HTML> <HTML> <HEAD> <TITLE>test</TITLE> </HEAD> <BODY>'; echo '<P class="error">ERROR invalid cookie!</P>'; echo '</BODY> </HTML>'; } } else { echo '<!DOCTYPE HTML> <HTML> <HEAD> <TITLE>test</TITLE> </HEAD> <BODY>'; echo '<P class="error">No cookie detected!<br><a href="login.php">login</a></P>'; echo '</BODY> </HTML>'; } ?>I have an error in the update, but I am not seeing where I made it. Its annoying because the update won't execute and anything beyond the update isn't visible in the html source code in the browser, so it is likely to be a syntax error, but where? <?php //COOKIE CHECKER if (isset($_COOKIE["person"])){ if (filter_var($_COOKIE["person"], FILTER_VALIDATE_INT)){ $user_id = $_COOKIE["person"]; //DATABASE CONNECTION VARIABLES $myserver ="localhost"; $myname = "username"; $mypassword = "password"; $mydb ="dbname"; /*SQL CONNECTION*/ // Create connection $conn = new mysqli($myserver, $myname, $mypassword, $mydb); // Check connection if ($conn->connect_error) { echo '<!DOCTYPE HTML> <HTML> <HEAD> <TITLE>test</TITLE> </HEAD> <BODY> <H1>Decline of the Han - Three Kingdoms</H1>'; die("Connection failed: " . $conn->connect_error); echo '</BODY> </HTML>'; } else { //COUNT USER $cquery = "SELECT COUNT(*) AS usercheck FROM Players WHERE ID = ?"; $cid = $conn->prepare($cquery); $cid->bind_param('i', $user_id); $cid->execute(); $cid->bind_result($usercheck); $cid->fetch(); if ($usercheck ==1){ if (isset($_POST["profile"])){ if(!filter_var($_POST["profile"], FILTER_SANITIZE_STRING)){ echo '<!DOCTYPE HTML> <HTML> <HEAD> <TITLE>test</TITLE> </HEAD> <BODY>'; echo '<P class="error">Unable to filter bio <a href="biography.php">return</a></P>'; echo '</BODY> </HTML>'; } else { $profile = $_POST["profile"]; $sql = "UPDATE Player_Data SET Bio =? WHERE ID=?"; $q = $conn->prepare($sql); $q->bind_param("si", $profile, $user_id); $q->execute(); echo '<P>Biography altered <a href="biography.php">return</a></P>'; //close connection $conn->close(); } } } else { echo '<!DOCTYPE HTML> <HTML> <HEAD> <TITLE>test</TITLE> </HEAD> <BODY>'; echo '<P class="error">'.$usercheck.' '.$user_id.'</P>'; echo '<P class="error">No such user found!</P>'; //close connection $conn->close(); //foot echo '</BODY> </HTML>'; } //end connection check } } else { echo '<!DOCTYPE HTML> <HTML> <HEAD> <TITLE>test</TITLE> </HEAD> <BODY>'; echo '<P class="error">ERROR invalid cookie!</P>'; echo '</BODY> </HTML>'; } } else { echo '<!DOCTYPE HTML> <HTML> <HEAD> <TITLE>test</TITLE> </HEAD> <BODY>'; echo '<P class="error">No cookie detected!<br><a href="login.php">login</a></P>'; echo '</BODY> </HTML>'; } ?>I have an error in the update, but I am not seeing where I made it. Its annoying because the update won't execute and anything beyond the update isn't visible in the html source code in the browser, so it is likely to be a syntax error, but where? I've searched all over for the past few days trying to figure out what I'm doing wrong. Basically what I'm trying to do is create a prepared statement inside my User class. I can connect to the database, but my query does not execute as expected. Here's the code for my User class Code: [Select] <?php include '../includes/Constants.php'; ?> <?php /** * Description of User * * @author Eric Evas */ class User { var $id, $fname, $lname, $email, $username, $password, $conf_pass; protected static $db_conn; //declare variables public function __construct() { $host = DB_HOST; $user = DB_USER; $pass = DB_PASS; $db = DB_NAME; //Connect to database $this->db_conn = new mysqli($host, $user, $pass, $db); //Check database connection if ($this->db_conn->connect_error) { echo 'Connection Fail: ' . mysqli_connect_error(); } else { echo 'Connected'; } } function regUser($fname, $lname, $email, $username, $password, $conf_pass) { if ($stmt = $this->db_conn->prepare("INSERT INTO USERS (user_fname,user_lname, user_email,username,user_pass) VALUES (?,?,?,?,?)")) { $stmt->bind_param('sssss', $this->fname, $this->lname, $this->email, $this->username, $this->password); $stmt->execute(); $stmt->store_result(); $stmt->close(); } } } ?> And here's the file that I created to instantiate an instance of the user class. Code: [Select] <?php include_once 'User.php'; ?> <?php //Creating new User Object $newUser = new User(); $newUser->fname = $_POST['fname']; $newUser->lname = $_POST['lname']; $newUser->email = $_POST['email']; $newUser->username = $_POST['username']; $newUser->password = $_POST['password']; $newUser->conf_pass = $_POST['conf_pass']; $newUser->regUser($newUser->fname, $newUser->lname, $newUser->email, $newUser->username, $newUser->password, $newUser->conf_pass); ?> And lastly heres the form that I want to get info from the user to insert into the database Code: [Select] <html> <head> <title></title> <link href="stylesheets/styles.css" rel="stylesheet" type="text/css"/> </head> <body> <form action = "Resources/testClass.php" method="post" enctype="multipart/form-data"> <label>First Name: </label> <input type="text" name="fname" id="fname" size="25" maxlength="25"/> <label>Last Name: </label> <input type="text" name="lname" id="lname" size="25" maxlength="25"/> <label>Email: </label> <input type="text" name="email" id="email" size="25" maxlength="40"/> <label>Username: </label> <input type="text" name="username" id="username" size="25" maxlength="32"/> <label>Password: </label> <input type="password" name="password" id="password" size="25" maxlength="32"/> <label>Re-enter Password: </label> <input type="password" name="conf_pass" id="conf_pass" size="25" maxlength="32"/> <br /><br /> <input type="submit" name="submit" id="submit" value="Register"/> <input type="reset" name="reset" id="reset" value="Reset"/> </form> </body> </html> I am trying to create a simple forum in a MVC architecture. This portion is kind of stumping me. Basically, I have a two tables in this DB: users and users_access_level (Separated for DB normalization) users: id / username / password / realname / access_level users_access_level: access_level / access_name What I'm trying to do, is echo the data onto an HTML table that displays users.username in one table data and then uses the users.access_level to find users_access_level.access_name and echo into the following table data, I would prefer not to use multiple queries if possible or nested queries. Example row for users: 1234 / tmac / password / tmac / 99 Example row for users_access_level: 99 / Admin Using the examples above, I would want the output to appear as such: Username: Access Name: Tmac Admin I am not 100% sure where to start with this, but I pick up quickly, I just need a nudge in the right direction. The code I attempted to create just shows my lack of knowledge of joining tables, but I'll post it if you want to see that I did at least make an effort to code this myself. Thanks for reading! To keep my website more secure, I am currently using Prepared Statement. The problem is that even the simplest query (e.g. retrieve Member's First Name) involves an INSANE amount of code. Here is an example of what my code looks like... // ********************** // Find Member Salt. * // ********************** // Build query. $q2 = 'SELECT salt FROM member WHERE email=?'; // Prepare statement. $stmt2 = mysqli_prepare($dbc, $q2); // Bind variables to query. mysqli_stmt_bind_param($stmt2, 's', $email); // Execute query. mysqli_stmt_execute($stmt2); // Store results. mysqli_stmt_store_result($stmt2); // Check # of Records Returned. if (mysqli_stmt_num_rows($stmt2)==1){ // Member found. // Bind result-set to variables. mysqli_stmt_bind_result($stmt2, $salt); // Fetch record. mysqli_stmt_fetch($stmt2); // Close prepared statement. mysqli_stmt_close($stmt2); }else{ $salt=''; // $errors['pass'] = 'A System Error has occurred.'; }// End of FIND MEMBER SALT I am wondering if there is a way to streamline things, perhaps by creating a Function where I can just pass arguments to my specific query needs. Of course if I do that, then a bad guy could pass arguments to the same Function and possibly doing something really bad?! Any ideas? Thanks, Debbie P.S. I am not ready to jump in to OOP, so please keep any responses using old-fashioned Procedural Programming. Thanks! 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 DeckDekkSo 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. I 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? 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?? 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 I can't get my Updated On timestamp to work in the following query... Code: [Select] // ****************************** // Create Temporary Password. * // ****************************** $tempPass = substr(md5(uniqid(rand(), true)), 3, 10); // Build query. $r = "UPDATE member SET pass=?, updated_on=? WHERE email=? LIMIT 1"; // Prepare statement. $stmt2 = mysqli_prepare($dbc, $r); // Bind variables to query. mysqli_stmt_bind_param($stmt2, 'sss', $tempPass, NOW(), $email); // Execute query. mysqli_stmt_execute($stmt2); I used similar code for an INSERT and it worked fine?! Now sure what is going on here... Debbie |