Connect the database - php

I try to do the booking form and in the PHP I type the $stmt->bind_param part come out syntax error. However, I don't know where I did wrong. Here is my phpMyAdmin setting phpmyadmin table structure:
. Below is my code:
$conn = mysqli_connect($servername, $username, $password,$database);
// Check connection
if($conn->connect_error){
die("Connection Failed : ". $conn->connect_error);
} else {
$stmt = $conn->prepare("insert into event_and_inquiry_form (Name,Mail,Phone_Number,Date,Propose,Person,Theme,Event_Package,Remarks)VALUES (Name, Mail, Phone_Number,Date,Propose,Person,Theme,Event_Package,Remarks);
$stmt->bind_param("sssisisss", $Name,$Mail,$Phone_Number,$Date,$Propose,$Person,$Theme,$Event_Package,$Remarks);
$execval = $stmt->execute();
echo $execval;
$stmt
$stmt->close();
$conn->close();
}

You do happen to have a few issues.
When you prepare your mysqli statement the values to be inserted are to be held by a question mark ?. I believe you can hold them with :name :secondname as well but that's a story for another question.
You have not closed your quotes or bracket on the prepare function.
You have a random $stmt variable at the end of your script.
I corrected your code with what I noticed and posted it below:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect($servername, $username, $password,$database);
$stmt = $conn->prepare("INSERT INTO `event_and_inquiry_form`
(`Name`,`Mail`,`Phone_Number`,`Date`,`Propose`,`Person`,`Theme`,`Event_Package`,`Remarks`)
VALUES
( ? , ? , ? , ? , ? , ? , ? , ? , ?)");
$stmt->bind_param("sssisisss", $Name,$Mail,$Phone_Number,$Date,$Propose,$Person,$Theme,$Event_Package,$Remarks);
$execval = $stmt->execute();
$stmt->close();
$conn->close();

It seems you're getting confused between mysqli and PDO - although there are syntax issues either way!
mysqli
With mysqli the short answer is that you need to replace all of the variables in VALUES( ... ) with ?.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // Enable error reporting
$mysqli = new mysqli($servername, $username, $password, $database); // Create connection to database
$sql = "
INSERT INTO event_and_inquiry_form
(Name,Mail,Phone_Number,Date,Propose,Person,Theme,Event_Package,Remarks)
VALUES (?,?,?,?,?,?,?,?,?)
";
$query = $mysqli->prepare($sql);
$query->bind_param("sssisisss", $Name, $Mail, $Phone_Number, $Date, $Propose, $Person, $Theme, $Event_Package, $Remarks);
$query->execute();
PDO
You can do it the same way in PDO.
Of course the connection method is different and we'll pass an array of the values to the execute function instead.
// Connect to the database
$pdo = new pdo(
"mysql:host={$servername};dbname={$database}",
$username,
$password,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => FALSE
]
);
$sql = "
INSERT INTO event_and_inquiry_form
(Name,Mail,Phone_Number,Date,Propose,Person,Theme,Event_Package,Remarks)
VALUES (?,?,?,?,?,?,?,?,?)";
$query = $pdo->prepare($sql);
$query->execute([$Name, $Mail, $Phone_Number, $Date, $Propose, $Person, $Theme, $Event_Package, $Remarks]);
Finally, in some cases you may prefer to name your placeholders. In this case the name will be :some_name and the array will need to be associative ["some_name"=> "Some value"].
// Connect to the database
$pdo = new pdo(
"mysql:host={$servername};dbname={$database}",
$username,
$password,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => FALSE
]
);
$sql = "
INSERT INTO event_and_inquiry_form
(Name,Mail,Phone_Number,Date,Propose,Person,Theme,Event_Package,Remarks)
VALUES
(:name, :mail, :phone_number, :date, :propose, :person, :theme, :event_package, :remarks)";
$query = $pdo->prepare($sql);
$query->execute([
"name" => $Name
"mail" => $Mail
"phone_number" => $Phone_Number
"date" => $Date
"propose" => $Propose
"person" => $Person
"theme" => $Theme
"event_package" => $Event_Package
"remarks" => $Remarks
]);

Related

Binding parameters in mysql

I'm trying to learn about binding parameters in MySQL. I tried this test but I'm getting the error "Call to a member function bind_param() on a non-object".
Am I doing something wrong?
Here is the updated code:
$sql = "INSERT INTO users (field1, field2, field3) VALUES (?, ?, ?)";
connect();
$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $value1, $value2, $value3);
$value1 = "test1";
$value2 = "test2";
$value3 = "test3";
$stmt->execute();
Here is the connect() function:
function connect(){
global $conn;
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
}
To bind params in a prepared query in PDO, pass an array containing your params to the execute function :
$result = $conn->prepare($sql);
$result->execute(array($value1, $value2, $value3));
UPDATE
For the mysqli version :
connect();
$result = $conn->prepare($sql);
$result->bind_param('sss', $value1, $value2, $value3);
$result->execute();
See http://php.net/manual/en/mysqli-stmt.bind-param.php

PDO parameterized query code review, how safe am i?

I'm a PHP newbie that just starts to code. Before coding any further, I need to know if I already on the right path on making a secure web. So please review my code samples below.
PHP Version 5.4.34
Database Server version: 5.5.40-cll - MySQL Community Server (GPL)
on connection.php
//should I use utf8mb4 and set server connection collation to utf8mb4_general_ci?
//also on html, is including <meta charset="utf-8"> necessary?
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // enabled by default?
select query
$query = "SELECT * FROM tbname WHERE username = :username";
$params = array(':username' => $_POST['username']);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($params);
}
catch(PDOException $ex)
{
die();
}
insert query
$query = "INSERT INTO log (
username,
email,
ip,
time
) VALUES (
:username,
:email,
:lastip,
:lastlog
)";
$params = array(
':username' => $_POST['username'],
':email' => $_POST['email'],
':lastip' => $_SERVER['REMOTE_ADDR'],
':lastlog' => time()
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($params);
}
catch(PDOException $ex)
{
die();
}
update query
$params = array(
':username' => $_SESSION['userdata']['username'],
':email' => $_POST['email'],
':age' => $_POST['age'],
':gender' => $_POST['gender']
);
$query = "UPDATE users SET
email = :email,
age = :age,
gender = :gender
where username = :username";
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($params);
}
catch(PDOException $ex)
{
die();
}
How safe am i from SQL injection? Safe enough from 2nd order attack?
Totally safe. The PDO Statement prepares the query to avoid SQL injections. Even if they try, the prepare() function make the necessary changes before send to the database.

PHP PDO Simple insert does not work

I am converting all of my query's to PDO, and i'm new to it.
It's properly a very stupid question but why does the following code not work?
try {
$conn = new PDO('mysql:host=localhost;dbname=ddd', $user, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$id = $_SESSION['id'];
$name = $_POST['name'];
$stmt = $pdo->prepare('INSERT INTO projects
(group_id, project_name)
VALUES (:id, :name)');
$stmt->execute(array(
':id'=>$id,
':name'=>$name
));
Thanks.
Your connection variable is $conn and you are preparing your PDO Statement using $pdo->prepare.
Change to $conn->prepare()
$stmt = $conn->prepare('INSERT INTO projects
(group_id, project_name)
VALUES (:id, :name)');
You're initializing a variable for your database connection called $conn yet later call $pdo that's not mentioned anywhere. That's the first thing I'd start with.

Issue inserting data using mysqli in MySQL

I try to use mysqli in order to insert data in my database. But does not work. Where may be the error?
$myDb = new mysqli($hostname, $username, $password, $database);
if($myDb->connect_errno > 0){
die('Unable to connect to database [' . $myDb->connect_error . ']');
}
$statment = $myDb->prepare("INSERT INTO user(name,surname,age)
VALUES (?,?,?)");
$statement->bind_param('s', $_POST['name']);
$statement->bind_param('s', $_POST['surname']);
$statement->bind_param('i', 25);
$statement->execute();
$statement->free_result();
EDIT:
I obtain this error:
Binding parameters failed: (0) Execute failed: (2031) No data supplied for parameters in prepared statement
You've got the error here:
$statement->bind_param('i', 25);
25 is not a variable. You can only use variables when binding parameters. You can't use constants nor fixed strings or numbers when binding.
Besides, it never worked for me to split the parameters when binding. I got an error. I need to do so:
$myDb = new mysqli($hostname, $username, $password, $database);
if($myDb->connect_errno > 0){
die('Unable to connect to database [' . $myDb->connect_error . ']');
}
$statement = $myDb->prepare("INSERT INTO user (name,surname,age) VALUES (?,?,25)");
$statement->bind_param('ss', $_POST['name'], $_POST['surname']);
$statement->execute();
$statement->free_result();
$statement->close();
I solved the problem using a correct bind of parameter. Here the correct code:
$myDb = new mysqli($hostname, $username, $password, $database);
if($myDb->connect_errno > 0){
die('Unable to connect to database [' . $myDb->connect_error . ']');
}
$statment = $myDb->prepare("INSERT INTO user(name,surname,age)
VALUES (?,?,?)");
$statement->bind_param('s', $name);
$statement->bind_param('s', $surname);
$statement->bind_param('i', $age);
$name = $_POST['name'];
$surname = $_POST['surname'];
$age = 25;
$statement->execute();
$statement->free_result();

What is wrong with my PDO prepared statement? [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 4 months ago.
Obviously, I am preparing the statement wrong, but I am not certain what I am doing wrong.
These 2 code segments are identical, except for the second line.
This fails:
$dbh = new PDO('mysql:host=localhost;dbname=' . $DB_Database, $DB_UserName, $DB_Password);
$sth = $dbh->prepare("SELECT * FROM `PNB`.`Users` WHERE `Users`.`EMail` = :email OR `Users`.`Temp_EMail` = :temp_email");
$sth->execute(array(':email' => $email, ':temp_email' => $email));
$sth->setFetchMode(PDO::FETCH_ASSOC);
$res = $sth->fetch();
$dbh = null;
This hard-coded test works:
$dbh = new PDO('mysql:host=localhost;dbname=' . $DB_Database, $DB_UserName, $DB_Password);
$sth = $dbh->prepare("SELECT * FROM `PNB`.`Users` WHERE `Users`.`EMail` = 'me#example.com' OR `Users`.`Temp_EMail` = 'me#example.com'");
$sth->execute(array(':email' => $email, ':temp_email' => $email));
$sth->setFetchMode(PDO::FETCH_ASSOC);
$res = $sth->fetch();
$dbh = null;
What am I doing wrong?
Thanks!
UPDATE: Solved!
The exact issue is still unknown, but seems to be related to the 'excessive naming' suggested by user 'Your Common Sense' in the comments below.
This works just fine:
$dbh = new PDO('mysql:host=localhost;dbname=' . $DB_Database, $DB_UserName, $DB_Password);
$sth = $dbh->prepare("SELECT * FROM Users WHERE EMail=:email OR Temp_EMail=:temp_email");
$sth->execute(array(':email' => $email, ':temp_email' => $email));
Thanks to everyone. I learned lots AND resolved the issue.
Message to Your Common Sense; If you form your comment as an 'Answer', then I can accept it.
It's hard to answer on sight.
Your code seems okay to me. So, debugging seems the only way.
What am I doing wrong?
Always ask this question from your PDO.
Every time you're connecting to PDO, do it this way (also make sure you can see errors, either on-screen or logged):
error_reporting(E_ALL);
$opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$dsn = 'mysql:host=localhost;dbname=' . $DB_Database;
$dbh = new PDO($dsn, $DB_UserName, $DB_Password, $opt);
if there is an error - you'll be notified.
If there isn't - check typo-like problems.
Just a quick try - Do you get it right with these two lines ?
$sth = $dbh->prepare("SELECT * FROM `PNB`.`Users` WHERE `Users`.`EMail` = :email OR `Users`.`Temp_EMail` = :temp_email");
$sth->execute(array(':email' => 'me#example.com', ':temp_email' => 'me#example.com'));
in other words... Did you set your $email variable ?
try this
$dbh = new PDO('mysql:host=localhost;dbname=' . $DB_Database, $DB_UserName, $DB_Password);
$sth = $dbh->prepare("SELECT * FROM `PNB`.`Users` WHERE `Users`.`EMail` = :email OR `Users`.`Temp_EMail` = :temp_email");
$sth->bindParam(':email', $email, PDO::PARAM_STR);
$sth->bindParam(':temp_email', $email, PDO::PARAM_STR);
$sth->execute();
$res = $sth->fetch(PDO::FETCH_ASSOC);
$dbh = null;

Categories