How do I to make an insert from a form by PDO it gives me the following error:
Fatal error: Call to a member function bindParam() on string
Here is my code:
$name = $_POST['name'];
$name = $_POST['subname'];
$phone= $_POST['phone'];
$sql = "INSERT INTO customers(name,subname,phone)VALUES(:name,:subname,:phone)";
$sql->bindParam(':name', $name);
$sql->bindParam(':subname', $subname);
$sql->bindParam(':phone', $phone);
$sql->bindParam(':telefono', $telefono);
$sql->execute();
You have to work with your PDO statement, and first prepare your query:
$name = $_POST['name'];
$name = $_POST['subname'];
$phone= $_POST['phone'];
$sql = "INSERT INTO customers(name,subname,phone)VALUES(:name,:subname,:phone)";
$sth = $dbh->prepare($sql);
$sth->bindParam(':name', $name);
$sth->bindParam(':subname', $subname);
$sth->bindParam(':phone', $phone);
$sth->bindParam(':telefono', $telefono);
$sth->execute();
Related
I have been working on this process for the past two days and might be missing something very obvious, so I am hoping for some extra eyes to spot the issue.
My form is passing the fields and I am able to connect to my database and echo out both the $_POST data (var_dump($_POST)) and also echo out the variables successfully. I get my connection message at line 35, but the script does not proceed to the SQL INSERT section. Any suggestions would be greatly appreciated
<?php
session_start();
//Get user id for posting to record
$_SESSION['id'] = $id;
//Get posted data and sanitize
$custId = filter_var($_POST['cust_id'], FILTER_SANITIZE_STRING);
$name = filter_var($_POST['_name'], FILTER_SANITIZE_STRING);
$ordDate = filter_var($_POST['ordDate'], FILTER_SANITIZE_STRING);
$reqDate = filter_var($_POST['reqDate'], FILTER_SANITIZE_STRING);
$bAddr = filter_var($_POST['_baddr'], FILTER_SANITIZE_STRING);
$bCont = filter_var($_POST['_contact'], FILTER_SANITIZE_STRING);
$bEmail = filter_var($_POST['_email'], FILTER_SANITIZE_STRING);
$bFax = filter_var($_POST['_fax'], FILTER_SANITIZE_STRING);
$bMobile = filter_var($_POST['_mobile'], FILTER_SANITIZE_STRING);
$bPhone = filter_var($_POST['_phone'], FILTER_SANITIZE_STRING);
$dAddr = filter_var($_POST['_daddr'], FILTER_SANITIZE_STRING);
$dCont = filter_var($_POST['_dContact'], FILTER_SANITIZE_STRING);
$bEmail = filter_var($_POST['_dEmail'], FILTER_SANITIZE_STRING);
$bMobile = filter_var($_POST['_dMobile'], FILTER_SANITIZE_STRING);
$bPhone = filter_var($_POST['_dPhone'], FILTER_SANITIZE_STRING);
$notes = filter_var($_POST['_delNotes'], FILTER_SANITIZE_STRING);
$servername = "localhost";
$database = "edwardm3_generation";
$username = "edwardm3_gen";
$password = "*********";
$sql = "mysql:host=$servername;dbname=$database;";
$dsn_Options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
//
// Create a new connection to the MySQL database using PDO, $my_Db_Connection is an object
try {
$my_Db_Connection = new PDO($sql, $username, $password, $dsn_Options);
echo "Connected successfully";
} catch (PDOException $error) {
echo 'Connection error: ' . $error->getMessage();
}
$sql2 = "INSERT INTO orders (custId, orderDate, reqDate, bAddr, bCont, bFax, bMobile, bPhone, dAddr, dCont, dEmail, dMobile, dPhone, notes, orderedBy) VALUES (:custId, :ordDate, :reqDate, :bAddr, :bCont, :bFax, :bMobile, :bPhone, :dAddr, :dCont, :dEmail, :dMobile, :dPhone, :notes, :id)";
$stmt = $my_Db_Connection->prepare($sql2);
$stmt ->bindParam(':custId', $custId, PDO::PARAM_INT);
$stmt ->bindParam(':ordDate', $ordDate, PDO::PARAM_STR);
$stmt ->bindParam(':reqDate', $reqDate, PDO::PARAM_STR);
$stmt ->bindParam(':bAddr', $bAddr, PDO::PARAM_STR);
$stmt ->bindParam(':bCont', $bCont, PDO::PARAM_STR);
$stmt ->bindParam(':bFax', $bFax, PDO::PARAM_STR);
$stmt ->bindParam(':bMobile', $bMobile, PDO::PARAM_STR);
$stmt ->bindParam(':bPhone', $bPhone, PDO::PARAM_STR);
$stmt ->bindParam(':dAddr', $dAddr, PDO::PARAM_STR);
$stmt ->bindParam(':dCont', $dCont, PDO::PARAM_STR);
$stmt ->bindParam(':dEmail', $dEmail, PDO::PARAM_STR);
$stmt ->bindParam(':dMobile', $dMobile, PDO::PARAM_STR);
$stmt ->bindParam(':dPhone', $dPhone, PDO::PARAM_STR);
$stmt ->bindParam(':notes', $notes, PDO::PARAM_STR);
$stmt ->bindParam(':create', $create, PDO::PARAM_INT);
if ($stmt ->execute()) {
echo "New record created successfully";
} else {
echo "Unable to create record";
}
?>
I am trying to enter user's data into a database. I think the commas in the address are causing the error.
<?php
$full_name = $_POST["fullname"];
$email = $_POST["email"];
$password = $_POST["password"];
$full_address = $_POST["address"];
$city = $_POST["city"];
$age = $_POST["age"];
$contact_number = $_POST["number"];
$gender = $_POST["gender"];
$education = $_POST["education"];
?>
<?php
$servername = "hidden";
$username = "hidden";
$password = "hidden";
$dbname = "hidden";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO users (full_name, email, password,full_address,city,age,contact_number,gender,education)
VALUES ($full_name, $email, $password,$full_address,$city,$age,$contact_number,$gender,$education)";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
As others have noted, your code is vulnerable to SQL injections. You should consider using parameterized queries:
$sql = "INSERT INTO users (full_name, email, password, full_address, city, age, contact_number, gender, education)
VALUES (?,?,?,?,?,?,?,?,?)";
$stmt = mysqli_prepare($conn, $sql);
// Bind parameters
$stmt->bind_param("s", $full_name);
$stmt->bind_param("s", $email);
$stmt->bind_param("s", $password);
$stmt->bind_param("s", $full_address);
$stmt->bind_param("s", $city);
$stmt->bind_param("s", $age);
$stmt->bind_param("s", $contact_number);
$stmt->bind_param("s", $gender);
$stmt->bind_param("s", $education);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
For more information refer to the PHP manual on MySQLi prepared statements.
You need to quote string in your SQL statement;
$sql = "INSERT INTO users (full_name, email, password,full_address,city,age,contact_number,gender,education)
VALUES ('$full_name', '$email', '$password','$full_address','$city',$age,'$contact_number','$gender','$education')";
Notice the single quotes around all the variables that contain strings. I might be a bit off because I don't know the values or table structure.
But the just quote all values that are going in to a Date or Text field.
To avoid additional problems and security risks you should be using mysqli_real_escape_string (at a minimum).
In all your assignment statements wrap the values in mysqli_real_escape_string
$full_name = mysqli_real_escape_string($conn, $_POST["fullname"]);
$email = mysqli_real_escape_string($conn, $_POST["email"]);
...
Note this requires setting up your DB connection before the variable assignments, so you'll have to reorganize your code a bit.
rink.attendant.6's answer is the proper way to adapt your code.
I did some research around and I found two ways to prepared my statements from PDO object. But it seems like both are not working at all. I am missing something?
Named placeholders
$email = 'my_email';
$code = 'my_private_code';
$pdo = new PDO('mysql:host=personal_info;dbname=personal_info', 'personal_info', 'personal_info');
$sql = "UPDATE `promo` SET code = :code WHERE email = :email";
$st = $pdo->prepare($sql);
$st->execute(array(
':code' => $code,
':email' => $email
));
Unamed placeholders
$pdo = new PDO('mysql:host=personal_info;dbname=personal_info', 'personal_info', 'personal_info');
$st = $pdo->prepare("INSERT INTO promo (`email`, `code`) VALUES (?, ?)");
$st->bindParam(1, $email);
$st->bindParam(2, $code);
$email = 'my_email#hotmail.com';
$code = 'my_private_code';
$st->execute();
The query runs in mysql, there is no catch when you submit but the data doesn't update. Is there any advice on why this doesn't work or even how to debug this?
<?php
if( $_SERVER['REQUEST_METHOD'] == "POST" )
{
// var_dump($_POST["first_name"]);
try
{
// this needs to be a lot more secure!
// read PDO manual
$id = $_GET['id'];
// $description = $_POST["description"];
$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$description = $_POST["description"];
$sql = $db->prepare("UPDATE `exhibitors` SET first_name = '$first_name' WHERE id = '52'");
$update = $db->query($sql);
}
catch ( Exception $e )
{
echo " Data could not be updated from the database.";
}
}
and the connection:
<?php
try
{
$db = new PDO("mysql:host=localhost;dbname=openstudios;port=8889","root","root");
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
// var_dump($db);
}
catch ( Exception $e )
{
echo "Could not connect to the database.";
exit;
}
You are not using prepare() (or query()) correctly here. prepare() is used to create a "prepared statement" that gets ran with execute() and query() is used to run an SQL query string.
DO NOT concatenate your $_POST values into your query string, that's how you open yourself up to SQL injections. You are ignoring the whole point of using prepared statements.
This is for MySQLi:
$id = $_GET['id'];
// $description = $_POST["description"];
$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$description = $_POST["description"];
$sql = $db->prepare("UPDATE `exhibitors` SET first_name = ? WHERE id = ?");
$sql->bind_param('sd', $first_name, $id);
$sql->execute();
See the docs: http://php.net/manual/en/mysqli.prepare.php
If you are using PDO, the syntax is a bit different
$id = $_GET['id'];
// $description = $_POST["description"];
$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$description = $_POST["description"];
$sql = $db->prepare("UPDATE `exhibitors` SET first_name = :first_name WHERE id = :id");
$sql->execute(array(
'first_name' => $first_name,
'id' => $id
));
For prepared statements you should be using something like this
$sql = $db->prepare('UPDATE exhibitors SET first_name = :first_name WHERE id = :id');
$sql->execute(array('first_name' => $first_name,'id' => 52));
In case you want to use query statement only, (which one should not, receptive to SQL injections)
$db->query("UPDATE exhibitors SET first_name = '$first_name' WHERE id = 52");
I have the following working MySQL insert:
$tableSelect = $_POST["tableSelect"];
$companyName = $_POST["companyName"];
$telephone = $_POST["telephone"];
$fax = $_POST["fax"];
$email = $_POST["email"];
$address = $_POST["address"];
$postcode = $_POST["postcode"];
$category = $_POST["category"];
$contact = $_POST["contact"];
$contactTel = $_POST["contactTel"];
$contactEmail = $_POST["contactEmail"];
$sql = "INSERT INTO $tableSelect (companyName,telephone,fax,email,address,postcode,category,contact,contactTel,
contactEmail) VALUES ('$companyName','$telephone','$fax','$email','$address','$postcode','$category',
'$contact','$contactTel','$contactEmail');";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
However, I've tried to change this into a prepared statement to protect myself from injection, like so:
$stmt = $con->prepare("INSERT INTO suppliers (companyName,telephone,fax,email,address,postcode,
category,contact,contactTel,contactEmail) VALUES(:companyName, :telephone, :fax, :email, :address,
:postcode, :category, :contact, :contactTel, :contactEmail);");
if ($stmt !== FALSE) {
$stmt->bindParam(':companyName',$companyName);
$stmt->bindParam(':telephone',$telephone);
$stmt->bindParam(':fax',$fax);
$stmt->bindParam(':email',$email);
$stmt->bindParam(':address',$address);
$stmt->bindParam(':postcode',$postcode);
$stmt->bindParam(':category',$category);
$stmt->bindParam(':contact',$contact);
$stmt->bindParam(':contactTel',$contactTel);
$stmt->bindParam(':contactEmail',$contactEmail);
$companyName = $_POST["companyName"];
$telephone = $_POST["telephone"];
$fax = $_POST["fax"];
$email = $_POST["email"];
$address = $_POST["address"];
$postcode = $_POST["postcode"];
$category = $_POST["category"];
$contact = $_POST["contact"];
$contactTel = $_POST["contactTel"];
$contactEmail = $_POST["contactEmail"];
$stmt->execute();
}
else {
echo "Could not connect";
}
Every time I run it, $stmt returns false. It's the first time I've used prepared statements and I'm fairly new to MySQL so some pointers would be greatly appreciated.
The syntax for mysqli is wrong. You have tried using PDO. For mysqli
$stmt = $con->prepare("INSERT INTO suppliers (companyName,telephone,fax,email,address,postcode,category,contact,contactTel,contactEmail) VALUES(?,?,?,?,?,?,?,?,?,?)");
if($stmt){
$stmt->bind_param('ssssssssss',$companyName,$telephone,$fax,$email,$address,$postcode,$category,$contact,$contactTel,$contactEmail);
//s for string, i for integer, d for double, b for blob
$stmt->execute();
}else{
echo($con->error); //TO display Error
}
Though your question is a sure offtopic, here are some pointers
Assuming you are using PDO for the second example (for some reason you didn't indicate it in your question)
you have to tell PDO to throw exceptions
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
it will let you to at least have an error message to think of.
a table name should never be supplied by client side.
adjust your bound variables to make them fit the query
Instead of that long and windy code just remove unnecessary members from $_POST array and pass it to execute
something like this
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "INSERT INTO suppliers
(companyName,telephone,fax,email,address,postcode,
category,contact,contactTel,contactEmail)
VALUES
(:companyName, :telephone, :fax, :email, :address,
:postcode, :category, :contact, :contactTel, :contactEmail)";
$stmt = $con->prepare($sql);
unset ($_POST['submit']);
// make sure you unset all the useless members
$stmt->execute($_POST);