I am very new to PHP and MySQL. I have the following code that works but now I need to incorporate prepared statements into. I have tried many things but with no luck.
The following is the original PHP code:
$sql = "SELECT name, address, city, phone, id FROM Lab7 WHERE name = '$name' ";
mysql_select_db('muftih_Registration');
$retval = mysql_query( $sql, $conn );
This is my attempt that did not work:
$sql = "SELECT name, address, city, phone, id FROM Lab7 WHERE name = ?";
$sql->bindParam('s', $name);
mysql_select_db('muftih_Registration');
$retval = mysql_query( $sql, $conn );
I keep getting:
Fatal error: Call to a member function bindParam() on a non-object
The mysql_ family does not support prepared statements, you'll need to migrate to mysqli_ which is a different driver library. Furthermore, you cannot mix mysql_ and mysqli_ libraries together.
Lastly, mysql_ has been deprecated for several years now, and has been removed in php 7.
Synopsis: do not use mysql_.
You need to use mysqli on order to use prepared.
Let me show an example.
$mysqli = new mysqli('localhost', 'username', 'password', 'database');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($stmt = $mysqli->prepare("SELECT name, address, city, phone, id FROM Lab7 WHERE name = ?")) {
$stmt->bind_param("s", $name);
$stmt->execute();
$stmt->bind_result($name, $address, $city, $phone, $id);
$stmt->fetch();
echo "$name, $address, $city, $phone, $id"; // Print the retrieved row
$stmt->close();
}
Hope this helps.
Peace! xD
Related
I'm building a login page where the username can be that of either a student or teacher, where student names are simply numeric (i.e. 45678). I've made a function account_type($user) which just returns "student" if $user is numeric, and "teacher" if otherwise.
Edit: To clarify, students will type in their SID (i.e. 12345) to log in, and so my function account_type() will determine them to be a student. As such, the MySQL query to access a student account is different than the one to access a teacher's account, wherein an email address is required.
The student log in works fine with the named parameters, but when I try using a string and looking for an email, I get the error:
Invalid parameter number: parameter was not defined
I've tried putting quotes around the :user in the query, but that didn't help. I've triple checked that the queries are right, and they work on MySQL. Any ideas what I should do? The obvious answer is to use mysqli or to not use named parameters, but I'm hoping for it to work with named parameters for more complex queries later on.
Here's my code:
try {
$pdo = new PDO($dsn, DB_USERNAME, DB_PASSWORD);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
die("Could not connect to database. " . $e->getMessage());
}
$user = mysqli_real_escape_string($link, $_POST['user']);
$pass = mysqli_real_escape_string($link, $_POST['pass']);
$account_Type = account_type($user);
if ($account_Type == "student") {
$query = "SELECT id, password FROM students WHERE sid = :user";
}
else if ($account_Type == "teacher") {
$query = "SELECT id, password FROM staff WHERE email = :user";
}
$stmt = $pdo->prepare($query);
$stmt->execute([
':user' => $user
]);
Thanks in advance!
There are two functions:
mysqli_real_escape_string which is supported in PHP 5 and 7 and must be used with mysqli: http://php.net/manual/en/mysqli.real-escape-string.php
And mysql_real_escape_string which was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0 and you can use withou a mysqli connection: http://php.net/manual/en/function.mysql-real-escape-string.php
In the comments of your question you posted a link that uses the mysql_real_escape_string but in your code you are using the mysqli_real_escape_string
So if you are using < PHP 7 or early you can use mysql_real_escape_string to improve your security without mysqli, like this:
$user = mysql_real_escape_string($_POST['user']);
but if you are using > PHP 7 then you must use mysqli, like in the example below:
<?php
//create a connection
$mysqli = new mysqli("localhost", "root", "", "school");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//mysqli_real_escape_string is the procedural version of the function below
$user = $mysqli->real_escape_string('1');
$pass = $mysqli->real_escape_string('student1');
//verify if is a student or teacher
$is_student = is_numeric($user);
if ($is_student == true) {
$query = "SELECT sid, name, password FROM students WHERE sid =? AND password =?";
}
else {
$query = "SELECT sid, name, password FROM staff WHERE email =? AND password =?";
}
if ($stmt = $mysqli->prepare($query)) {
if($is_student){
//i for integer and s for string
$stmt->bind_param("is", $user, $pass);
}else{
//s for string and s for string
$stmt->bind_param("ss", $user, $pass );
}
$stmt->execute();
$stmt->bind_result($sid, $name, $password);
$stmt->fetch();
printf("sid: %s; name: %s; password: %s\n", $sid, $name, $password);
$stmt->close();
}
Hope this helps.
After a long time avoiding Prepared Statements I want to leave my comfort zone and update all my sites to mysqli, but I'm having a really hard time to achieve things that seem simple before...
Connection
$conn = mysqli_connect($host, $user, $password, $database)or die(mysqli_error($conn));
All my query's were built this way:
$id = 1;
$result = mysqli_query($conn, "SELECT * FROM users WHERE id = '$id'");
$row = mysqli_fetch_array($result);
Then I could print all needed fields:
Name: $row['name'];
Email: $row['email'];
Address: $row['address'];
City: $row['city'];
...
I've tried several ways to prepare, execute, bind and fetch the results in a simple way, or similar to what I was used to, but none of them work for me.
My statement is that bad? I mean, if I sanitize all itens before any Query or Insert my statement will remain insecure?
Can anyone show me a example of how can I use prepared statement but still be able to print my results individually, like: $row['name], $row['address'], $row['city']...
JUST TO UPDATE A FEW THINGS
This code works properly, my connection is ok and the $id is declared above my query (I've edited my question). My question is how can I "transform" this code into a mySQLi Prepared Statement and still be able to print results individually like $row['name'], $row['address']...
<?php
$mysqli = new mysqli("localhost", "username", "password", "db_name");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$id =1;
if ($stmt = $mysqli->prepare("SELECT name, email from users where id=?")) {
/* bind parameters for markers */
$stmt->bind_param("d", $id);
/* execute query */
$stmt->execute();
$stmt->bind_result($name, $email);
/* fetch value */
$stmt->fetch();
printf("%s has email %s", $name, $email);
/* close statement */
$stmt->close();
}
?>
May it help
I am learning to put data in my database using php mysqli prepared statements. I have the data going into the data base by using this code.
$FirstName=ucwords($_POST['fname']);
$LastName=ucwords($_POST['lname'], "-'");
$Customer=$LastName." ".$FirstName;
$conn = new mysqli($host,$user,$password,$db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("INSERT INTO customers (FirstName, LastName, Customer) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $FirstName, $LastName, $Customer);
$stmt->execute();
$conn->close();
This is working very well. Especially with hyphenated names or names with an apostrophy such as Pete O'Brian.
Now then while trying to retrieve the information back out of the database I am using the following code.
$conn = new mysqli($host,$user,$password,$db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn -> prepare("SELECT Customer, Instrument1 FROM tblinvoice WHERE InvID = ?");
$stmt->bind_param("i", $tempid);
$stmt->execute();
$stmt -> bind_result($cust, $inst);
$stmt -> fetch();
$cust = mysqli_real_escape_string($conn, $cust);
$stmt -> close();
$conn -> close();
BUT the above output O\ for a last name of O'Brian. If I remove the mysqli_real_escape_string($conn, $cust) and just use the bound value of $cust I simply get O instead of O'Brian.
Can anyone tell me what I am not doing or what I am doing wrong here?
always use htmlspecialchars() in content from db that are going to show in html.
echo htmlspecialchars($yourresult['yourfield'], ENT_QUOTES);
We should always use htmlspecialchars when filling HTML form input fields values.
I cannot for the life of me get binding to work with PDO queries, they always return false.
On this example, it checks that the value of a field is between 2 other values.
This works:
$query = $db->query("SELECT * FROM table WHERE field1 > '$start' AND field1 < '$finish'");
This doesn't:
$query = $db->query("SELECT * FROM table WHERE field1 > :start AND field1 < :finish");
$query->bindParam(":start", $start);
$query->bindParam(":finish", $finish);
UPDATE: The above query now works thanks to the help. The following still doesn't.
I have been trawling through various PDO posts on here but I have not found a solution, and I don't know what else to try.
UPDATE2: Okay, it seems it is not finding $db and therefore not connecting and returning false. The $db connection line is in a connect.php file that is required on all main pages. The content on those pages is called by a function that then includes the relevant file/page. Because PDO does not work by itself in functions, is it losing the $db through the function to include the file containing the query? I may not have explained myself clearly enough.
Basically, example function in functions.php:
function getRegistration() {
include("registration.php");
}
main.php
require_once("connect.php");
require_once("functions.php");
getRegistration();
registration.php contains:
$sql = $db->prepare("INSERT INTO tempus_members(username, email, password, activation_code, registration_date, registered_ip, name) VALUES(:username, :email, :password, :activation_code, :registration_date, :registered_ip, :name)");
$sql->bindParam(":username", $username);
$sql->bindParam(":email", $email);
$sql->bindParam(":password", $hash);
$sql->bindParam(":activation_code", $activation_code);
$sql->bindParam(":registration_date", $registration_date);
$sql->bindParam(":registered_ip", $registered_ip);
$sql->bindParam(":name", $name);
$sql->execute();
Is it losing the $db variable through the function to include the page? If so, how do I carry $db through all functions?
Try:
$stmt = $db->prepare("SELECT * FROM table WHERE field1 > :start AND field1 < :finish");
$stmt->bindParam(":start", $start);
$stmt->bindParam(":finish", $finish);
$stmt->execute();
You were using PDO::query instead of PDO::prepare.
As for the other query, what errors are you getting back? Try the following code and see if any errors are spit out onto the page:
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try{
$sql = $db->prepare("INSERT INTO tempus_members(username, email, password, activation_code, registration_date, registered_ip, name) VALUES(:username, :email, :password, :activation_code, :registration_date, :registered_ip, :name)");
$sql->bindParam(":username", $username);
$sql->bindParam(":email", $email);
$sql->bindParam(":password", $hash);
$sql->bindParam(":activation_code", $activation_code);
$sql->bindParam(":registration_date", $registration_date);
$sql->bindParam(":registered_ip", $registered_ip);
$sql->bindParam(":name", $name);
$sql->execute();
}
catch(PDOException $e){
echo $e->getMessage();
}
I'm new to PHP and I'm trying to get a prepared statement to work. Its for my final year project at university and I remember reading that prepared statements are good practice and also good for SQL injections. However the following code gives me a Server 500 error.
<?php
$email = "blah#blah.co.uk";
$hash = "somerandomhashedpassword";
$db = new mysqli("localhost", "root", "1234", "UEAnetwork");
$sql = "INSERT INTO Students (Email, Password) VALUES (?,?)";
$stmt = $db->prepare($sql);
$stmt->bindValue(1, $email);
$stmt->bindValue(2, $hash);
if ($stmt->execute()) {
echo "You have registered!!!!!!!!!!!!!!!!!!!!!!!!!!!!";
}
?>
If I run the following then a row is inserted, so I'm pretty sure I'm connecting to the database properly.
<?php
$db = new mysqli("localhost", "root", "1234", "UEAnetwork");
$sql = "INSERT INTO Students (Email, Password) VALUES ('blah#blah.co.uk','somerandomhashedpassword')";
$stmt = $db->prepare($sql);
if ($stmt->execute()) {
echo "You have registered!!!!!!!!!!!!!!!!!!!!!!!!!!!!";
}
?>
Am I using bindValue incorrectly? I've seen it used this way in many tutorials online but I must be doing something wrong.
mysqli has a very different API than PDO. There is no mysql_stmt::bindValue. You want to use mysql_stmt::bind_param, but the syntax is quite different:
$stmt->bind_param('ss', $email, $hash);