PHP/MySQL error: Could not execute INSERT INTO with PDO - php

I'm a beginner to PHP/MySQL trying to insert data into a table via a form, but I keep getting this:
Connected successfully ERROR: Could not execute INSERT INTO foo (firstname, lastname, landline, mobile) VALUES ('', '', ', ').
My limited understanding tells me I'm connecting successfully but nothing's getting into the table. Checking the table confirms this.
I'm trying to send the data from a PHP 7.1 WHMCS server to a remote host running MySQL 5.1.73. I'm pulling a user ID from WHMCS and pre-populating the that field with the idea to send that along with the rest of the form data. I had that field set to "hidden" and "text," no luck.
I even copied/pasted the form to a separate html and tried running everything at the root. No luck.
I used this example as my guide.
form.tpl:
<form method="post" action="includes/action.php">
User ID:<input type ="text" name = "userid" value={$d} readonly> //pulls userID from WHMCS
First name:<input type="text" name="firstname">
Last name:<input type="text" name="lastname">
Landline:<input type="text" name="landline">
Mobile:<input type="text" name="mobile">
<input type="submit" value="Submit"></form>
dbconnect.php:
$servername = "fqdn.com";
$username = "few";
$password = "2many";
try {
$conn = new PDO("mysql:host=$servername;dbname=data_base", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
action.php:
//Open MySql Connection
include "dbconnect.php";
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO foo (userid, firstname, lastname, landline, mobile) VALUES (:userid, :firstname, :lastname, :landline, :mobile)");
$stmt->bindParam(':userid', $userid);
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':landline', $landline);
$stmt->bindParam(':mobile', $mobile);
// insert a row
$userid = $_POST["userid"];
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$landline = $_POST["landline"];
$mobile = $_POST["mobile"];
$stmt->execute();
echo "New records created successfully";
} catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
$conn = null;

Sorry for the delay. Here's the solution.
action.php:
public function insertToDb($data)
{
try{
$sql = "INSERT INTO table_name (column1, column2) VALUES ('" . $data['column1']."','" . $data['column2']."')";
$this->con->exec($sql);
if($this->con->lastInsertId() > 0){
return true;
} else {
return "Error: " . $sql . "<br>" . $conn->error;
}
} catch (\PDOException $e) {
return "Insert failed: " . $e->getMessage();
}
}
public function getSingleData($d,$c)
{
try{
$sql = "SELECT * FROM table_name WHERE d='".$d."' AND c='".$c."'";
$query = $this->con->prepare($sql);
$query->execute();
return $query->fetchAll(\PDO::FETCH_ASSOC);
} catch (\PDOException $e) {
return "Error: " . $e->getMessage();
}
}
Edit: #halfer thanks for pointing out the vulnerability.
public function insertToDb($data)
{
try{
$insertdata = [
'column1' => $data['column1'],
'column2' => $data['column2'],
'column3' => $data['column3'],
];
$sql = "INSERT INTO table_name (column1, column2,column3) VALUES (:column1,:column2,:column3)";
$stmt= $this->con->prepare($sql);
$stmt->execute($insertdata);
if($this->con->lastInsertId() > 0){
return true;
} else {
return "Error: " . $sql . "<br>" . $conn->error;
}
} catch (\PDOException $e) {
return "Insert failed: " . $e->getMessage();
}
}

in action.php you are using variables before you have set them.
// insert a row
$userid = $_POST["userid"];
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$landline = $_POST["landline"];
$mobile = $_POST["mobile"];
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO foo (id, firstname, lastname, landline, mobile) VALUES (:userid, :firstname, :lastname, :landline, :mobile)");
$stmt->bindParam(':userid', $userid);
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':landline', $landline);
$stmt->bindParam(':mobile', $mobile);
$stmt->execute();

Related

PDO fails when called inside a function

I'm trying to use a function to execute all my PDO queries. I am experiencing a 500 error when using the function. I am able to execute the code successfully if I don't use the function.
you'll notice that the only difference between the working and non-working code blocks below is the use of the function.
Why does the code fail when called inside a function?
WORKS:
try {
$conn = new PDO($dsn, $username, $password, $options);
}
catch (PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
$info = array();
$info['fname'] = $_POST['fname'];
$info['lname'] = $_POST['lname'];
$info['email'] = $_POST['email'];
$info['password'] = password_hash($_POST['password'], PASSWORD_DEFAULT);
$info['datecreated'] = date("Y-m-d H:i:s");
$sql = "INSERT INTO Users (fname, lname, email, password, datecreated)
VALUES (:fname, :lname, :email, :password, :datecreated)";
try {
$stmt=$conn->prepare($sql);
$stmt->execute($info);
}
catch (PDOException $e)
{
echo $sql . "PDO query failed: <br>" . $e->getMessage();
}
DOESN'T WORK
try {
$conn = new PDO($dsn, $username, $password, $options);
}
catch (PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
$info = array();
$info['fname'] = $_POST['fname'];
$info['lname'] = $_POST['lname'];
$info['email'] = $_POST['email'];
$info['password'] = password_hash($_POST['password'], PASSWORD_DEFAULT);
$info['datecreated'] = date("Y-m-d H:i:s");
$sql = "INSERT INTO Users (fname, lname, email, password, datecreated)
VALUES (:fname, :lname, :email, :password, :datecreated)";
function pdoquery ($sql, $info){
try {
$stmt=$conn->prepare($sql);
$stmt->execute($info);
}
catch (PDOException $e)
{
echo $sql . "PDO query failed: <br>" . $e->getMessage();
}
}
pdoquery($sql,$info);
Try following
$info = array();
$info['fname'] = $_POST['fname'];
$info['lname'] = $_POST['lname'];
$info['email'] = $_POST['email'];
$info['password'] = password_hash($_POST['password'], PASSWORD_DEFAULT);
$info['datecreated'] = date("Y-m-d H:i:s");
$sql = "INSERT INTO Users (fname, lname, email, password, datecreated)
VALUES (:fname, :lname, :email, :password, :datecreated)";
function pdoquery ($sql, $info, $conn){
$stmt=$conn->prepare($sql);
$stmt->execute($info);
return $stmt;
}
pdoquery($sql,$info, $conn);
In a nutshell, you forgot to pass $conn to your function.

Insert multiple rows using form and PDO

Hello guys i am stuck in PHP code to Insert multiple rows using form and PDO
Below my code please help me to fix it
I'll appreciate all comments and suggested solutions
and forgive my mistakes because I am new i PHP
HTML code
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Firstname: <input type="text" name="firstname[]"><br>
Lastname: <input type="text" name="lastname[]"><br>
Email: <input type="text" name="email[]"><br>
<hr>
Firstname: <input type="text" name="firstname[]"><br>
Lastname: <input type="text" name="lastname[]"><br>
Email: <input type="text" name="email[]"><br>
<input type="submit" name="submit" value="Submit">
</form>
PHP Code
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$firstname = input_checker($_POST["firstname"]);
$lastname = input_checker($_POST["lastname"]);
$email = input_checker($_POST["email"]);
foreach ($row as $rows) {
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO memo (firstname, lastname, email)
VALUES (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $rows);
$stmt->bindParam(':lastname', $rows);
$stmt->bindParam(':email', $rows);
$stmt->execute();
echo "New records created successfully";
}
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
function input_checker($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Indent please, it's hard to read.
It can't work.
DONT FOREACH THE QUERY. You'll send one query with bad datas as many times as you have elements in $rows array
What you're doing here is sending nothing cause $rows don't exist.
So here are the steps.
Do
$rows = array($firstname, $lastname, $email);
$stmt = $conn->prepare("INSERT INTO memo(ID, firstname, lastname, email)
VALUES (NULL, :firstname, :lastname, :email)");
foreach($rows as $key => $value){
$stmt->bindParam($key, $value);
}
$stmt -> execute();
OR you can try building the query this way :
DB_connect :
<?php
$db_username = "root";
$db_password = "";
$db_host = "localhost";
$db_name = "veterinaires";
/* PDO EN FR OU EN ARABE C ISSI */
$db_options = array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8");
try {
$db = new PDO("mysql:host={$db_host};dbname={$db_name};charset=utf8", $db_username, $db_password, $db_options);
} catch(PDOException $ex) {
die("Failed to connect to the database: " . $ex->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
?>
Query :
$query = "INSERT INTO patients
(ID,
pet_name,
breed,
colour,
sex,
date_of_birth,
microchip_tatoo,
comment,
owner_ID)
VALUES
(NULL,
:pet_name,
:breed,
:colour,
:sex,
:date_of_birth,
:microchip_tatoo,
:comment,
:owner_ID)";
$query_params = array(':pet_name' => $pet_name,
':breed' => $breed,
':colour' => $colour,
':sex' => $sex,
':date_of_birth' => $date_of_birth,
':microchip_tatoo' => $microchip_tatoo,
':comment' => $comment,
':owner_ID' => $_SESSION['ID']);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$check = true;
}catch(PDOException $ex){
$check = false;
die("Failed to run query: " . $ex->getMessage());
}
?>

Simple PHP Form SQL Insert

I need some help with a very basic issue that I cannot resolve.
A bit of background: I have a PHP form and I would like the information inside the table to insert into my SQL table. For some reason, when I hit submit nothing inserts into the table and I have no idea why. Please help!
This is the PHP Code:
<?php
try
{
$db = new PDO('mysql:host=' . $Database_Host . ';dbname=' . $Database_Database, $Database_Username, $Database_Password);
}catch(PDOException $e){
die("Failed to connect to database! Please check the database settings.");
}
if(isset($_POST['submit'])) {
$result = mysql_query('INSERT INTO requests (song,name,dedicated,time) VALUES ("' . mysql_real_escape_string($_POST['name']) . '", "' . mysql_real_escape_string($_POST['dedicated']) . '", "' . mysql_real_escape_string($_POST['song']) . '", UNIX_TIMESTAMP())');
if ($result) {
echo 'Song requested successfully!<br />';
}
}
?>
This is the HTML Code:
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">Request:<br /><br />
Song:<br />
<input type="text" name="song"><br />
Name:<br />
<input type="text" name="name"><br />
Comments:<br />
<input type="text" name="dedicated"><br />
<input type="submit" name="submit" value="Submit" >
</form>
What this is meant to do is insert the request form into the SQL table, however nothing is happening. Any help is appreciated.
Kind Regards,
Edward
You can't mix mysql and PDO like that. You should use a PDO prepared query for the insert.
Also, the order of the values in the VALUES list have to match the column list -- you had the values in the order name, dedicated, song, time instead of song, name, dedicated, time.
<?php
if (isset($_POST['submit'])) {
try
{
$db = new PDO('mysql:host=' . $Database_Host . ';dbname=' . $Database_Database, $Database_Username, $Database_Password);
}catch(PDOException $e){
die("Failed to connect to database! Please check the database settings.");
}
$stmt = $db->prepare('INSERT INTO requests (song,name,dedicated,time) VALUES (:song, :name, :dedicated, UNIX_TIMESTAMP())');
$result = $stmt->execute(array(':song' => $_POST['song'], ':name' => $_POST['name'], ':dedicated' => $_POST['dedicated']));
if ($stmt->rowCount == 1) {
echo "Song requested successfully";
} else {
echo "Song could not be requested";
}
}
You should study about pdo and mysql and then use them ...
just see this simple example with mysql :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
$stmt->execute();
$firstname = "Mary";
$lastname = "Moe";
$email = "mary#example.com";
$stmt->execute();
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie#example.com";
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
?>
and this one with pdo :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email)
VALUES (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
// insert a row
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
$stmt->execute();
// insert another row
$firstname = "Mary";
$lastname = "Moe";
$email = "mary#example.com";
$stmt->execute();
// insert another row
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie#example.com";
$stmt->execute();
echo "New records created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
I prefer using pdo
Source : http://www.w3schools.com/php/php_mysql_prepared_statements.asp
NOTE : use prepared statements to avoid sql injection .

MySQLi insert statement to executing

I am writing a simple code in PHP to test my MySql server by , inserting data to my database server
i am executing the file from the internet
URL of executing : Scores2.php?n=asdad&l=345&s=241
PHP Code:
<?php
$servername = "sql3.freesqldatabase.com";
$username = "MY USERNAME";
$password = "MY PASSWORD";
$dbname = "MY DBNAME";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name = (string)$_GET['n'];
$score = (int)$_GET['s'];
$level = (int)$_GET['l'];
$sql = "INSERT INTO HighScores (name, score, level)
VALUES ($name, $score, $level)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
When i execute the file , the browser shows this error :
Error: INSERT INTO HighScores (name, score, level) VALUES (asdad, 241, 345)
Unknown column 'asdad' in 'field list'
I checked the Control Panel in phpMyAdmin and executed the same statement but without variables , and it worked
Rows Types :
name : text
score : int(11)
level : int (11)
Learn how to prepare the query it's not that difficult.
You will avoid sql injection and missing quotes
Use num_rows to check if the record is inserted
Use $conn->error if the prepare() call return false.
$name = (string)$_GET['n'];
$score = (int)$_GET['s'];
$level = (int)$_GET['l'];
$sql = "INSERT INTO HighScores (name, score, level)
VALUES (?, ?, ?)";
if ($stmt = $conn ->prepare($sql)) {
$stmt->bind_param("s", $name);
$stmt->bind_param("i", $score);
$stmt->bind_param("i", $level);
$stmt->execute();
if($stmt->num_rows > 0){
echo "New record created successfully";
}else{
echo "no rows affected";
}
$stmt->close();
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn ->close();
$sql = "INSERT INTO HighScores (name, score, level)
VALUES ('$name', '$score', '$level')";
change query like this

Call to a member function execute() on a non-object in

I have the following error, and this is the exact same form processing file I use for registering a user, but I changed it for the appropriate table and columns. While the reg works fine every time.
Here is the code where the error is located:
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (:yas,:yasas,:yasasha)";
$q = $conn->prepare($sql);
$q->execute(array(':yas'=>$eventname,':yasas'=>$about,':yasasha'=>$website));
Here is the full code:
<?php
$servername = "localhost";
$username = "root";
$password = "Af2vaz93j68";
$dbname = "pdo_ret";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$eventname = $_POST['eventname'];
$about = $_POST['about'];
$website = $_POST['website'];
if($eventname == '') {
$errmsg_arr[] = 'You must enter your Email';
$errflag = true;
}
if($about == '') {
$errmsg_arr[] = 'You must enter your Password';
$errflag = true;
}
if($website == '') {
$errmsg_arr[] = 'You must enter First Name';
$errflag = true;
}
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (:yas,:yasas,:yasasha)";
$q = $conn->prepare($sql);
$q->execute(array(':yas'=>$eventname,':yasas'=>$about,':yasasha'=>$website));
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Youre confusing PDO and mysqli. mysqli does not support named parameters so you stmt is not compiling and Mysqli::prepare is returning false. Additionally mysqli does not support passing the param to be bound through mysqli_stmt::execute so even if you switch to positional placeholders your execute will fail.
This is what you would need for mysqli:
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (?,?,?)";
$stmt = $conn->prepare($sql);
// check to make sure the statement was prepared without error
if ($stmt) {
// the statement is good - proceed
$stmt->bind_param('sss', $eventname, $about, $website);
$stmt->execute();
}
Additionally this makes no sense at all:
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
This will just run the same query again either inserting a second row of the exact same data, or perhaps creating a duplicate key error depending upon your schema.
If you want to test that the previous query succeeded you would do something like:
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (?,?,?)";
$stmt = $conn->prepare($sql);
if ($stmt) {
$stmt->bind_param('sss', $eventname, $about, $website);
$success = $stmt->execute();
} else {
$success = false;
}
if ($success === true) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
If you want to use PDO (which i prefer and usually recommend) your code would look something like this:
$conn = PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (:yas,:yasas,:yasasha)";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':yas'=>$eventname,':yasas'=>$about,':yasasha'=>$website));
echo "New record created successfully";
} catch (PDOException $e) {
echo "Error: " . $sql . "<br>" . $e->getMessage();
}

Categories