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());
}
?>
Related
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();
<?php
// DATABASE-HOSTNAME-OR-IPADDRESS-GOES-HERE
// MYSQL-DBNAME-GOES-HERE
class LoginHandler {
public $dbHostname = 'localhost';
public $dbDatabaseName = 'employee101';
public $user = 'root';
public $password = 'root';
public function handleRequest($arg) {
$username = '123';
$password2 = '123';
$fname = 'John';
$lname = 'Doe';
$age = '18';
if ( ! $username ) {
$this->fail();
return;
}
try {
$dsn = "mysql:dbname={$this->dbDatabaseName};host={$this->dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$sql="SELECT * FROM `employee_data` WHERE `username`='$username'";
$stmt = $pdo->query($sql);
if ( $stmt === false ) {
echo "DB Critical Error";
return;
}
elseif ( $stmt->rowCount() > 0 ) {
echo "user already exists";
return;
}
else {
echo "User created";
$sql = "INSERT INTO employee_data (name, sumame, age, username, password)
VALUES ($fname, $lname, $age, $username, $password2)";
$dsn = "mysql:dbname={$this->dbDatabaseName};host={$this->dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$stmtz = $pdo->prepare($sql);
$stmtz->bindParam($fname, $_POST[$fname], PDO::PARAM_STR);
$stmtz->bindParam($lname, $_POST[$lname], PDO::PARAM_STR);
$stmtz->bindParam($age, $_POST[$age], PDO::PARAM_STR);
$stmtz->bindParam($username, $_POST[$username], PDO::PARAM_STR);
$stmtz->bindParam($password2, $_POST[$password2], PDO::PARAM_STR);
$resultzzx = $stmtz->execute();
return;
}
}
catch(PDOException $e) {
$this->log('Connection failed: ' . $e->getMessage());
echo "DB Critical Error";
}
}
function log($msg) {
file_put_contents("login.log", strftime('%Y-%m-%d %T ') . "$msg\n", FILE_APPEND);
}
}
$handler = new LoginHandler();
$handler->handleRequest($_POST);
?>
When attempting to use this script above, I get the echo that the user was created, but even when refreshing the table, the new entry doesn't show up.
Now, if i change the values line to be the following, it will work and show the new entry.
('John', 'Doe', '18', $username, $password2)";
What am i doing wrong? I need the first name, last name and age entries to not be concrete, as i will be obtaining them from a POST on my android device. The whole purpose of this script is to create the user and it's records if it doesn't already exist.
You have various mistakes.
1) You are not binding your parameters correctly. To bind them correctly, you place a :variablename in the position you want to include the variable. Usually the "variablename" should be the same as the one you are obtaining from the $_POST superglobal so that the code is cleaner and more readable.
2) You are not obtaining the values from the $_POST superglobal correctly. The key values you place inside are strings, and by placing an empty $fname variable, you are not going to obtain a correct result. It would only work if you had coding saying $fname = 'fname' somewhere up top hidden from us, however that code itself would be unadvised since it is unnecessary and only makes the source code larger.
$sql = "INSERT INTO employee_data (name, sumame, age, username, password)
VALUES (:fname, :lname, :age, :username, :password2)";
$dsn = "mysql:dbname={$this->dbDatabaseName};host=
{$this>dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$stmtz = $pdo->prepare($sql);
$stmtz->bindParam(':fname', $_POST['fname']);
$stmtz->bindParam(':lname', $_POST['lname']);
$stmtz->bindParam(':age', $_POST['age']);
$stmtz->bindParam(':username', $_POST['username']);
$stmtz->bindParam(':password2', $_POST['password2']);
I hope that helps.
$sql = "INSERT INTO employee_data (name, sumame, age, username, password) VALUES (:name, :sumame, :age, :username, :password)";
$dsn = "mysql:dbname={$this->dbDatabaseName};host={$this->dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$stmtz = $pdo->prepare($sql);
$stmtz->bindParam(':name', $fname);
$stmtz->bindParam(':sumame', $lname);
$stmtz->bindParam(':age', $age);
$stmtz->bindParam(':username', $username);
$stmtz->bindParam(':password', $password2);
$resultzzx = $stmtz->execute();
return;
After reviewing the link Fred posted in the comment above, i've modified it to work fine, thanks.
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 .
I need to rewrite my php code with mysql_* functions with PDO so I have:
<?php
$con = mysql_connect('localhost', 'gmaestro_agro', 'pass') or die('Error connecting to server');
mysql_select_db('gmaestro_agro', $con);
mysql_select_db('gmaestro_agro', $con);
$query = "INSERT INTO `stat` (`Name`, `Gender`, `Age`, `Donuts eaten`) VALUES (";
$query .= "'".mysql_real_escape_string($_POST['Name']) . "', ";
$query .= "'".mysql_real_escape_string($_POST['Gender']) . "', ";
$query .= "'".mysql_real_escape_string($_POST['Age']) . "', ";
$query .= "'".mysql_real_escape_string($_POST['Donuts_eaten']);
$query .= "')";
$result = mysql_query($query);
if($result != false) {
echo "success!";
} else {
echo "an error occured saving your data!";
}
?>
and I try to write this but with PDO function like this:
<?php
/* Your Database Name */
$dbname = 'gmaestro_agro';
/* Your Database User Name and Passowrd */
$username = 'gmaestro_agro';
$password = 'pass';
$stmt = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO stat(Name,
Gender,
Age,
Donuts eaten
) VALUES (
:Name,
:Gender,
:Age,
:Donuts_eaten)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':Name', $_POST['name'], PDO::PARAM_STR);
$stmt->bindParam(':Gender', $_POST['gender'], PDO::PARAM_STR);
$stmt->bindParam(':Age', $_POST['age'], PDO::PARAM_STR);
// use PARAM_STR although a number
$stmt->bindParam(':Donuts_eaten', $_POST['Donuts_eaten'], PDO::PARAM_STR);
$stmt->execute();
if($stmt != false) {
echo "success!";
} else {
echo "an error occured saving your data!";
}
?>
I dont get any error just nothing happend? Any idea how to solve my problem?
Edit (successful test code)
Table and data creation codes used for the successful insertion (test).
Column Donuts_eaten has been used with an underscore instead of a space.
You can base yourself on this:
Table creation codes in PHPmyadmin
Note: Change your_db_name to your Database name.
CREATE TABLE `your_db_name`.`stat` (
`Name` VARCHAR( 255 ) NOT NULL ,
`Gender` VARCHAR( 255 ) NOT NULL ,
`Age` INT NOT NULL ,
`Donuts_eaten` INT NOT NULL
) ENGINE = MYISAM
HTML form
Note: <input type="text" name="Donuts_eaten"> - Donuts_eaten is not the same as donuts_eaten notice the lowercase d
<form action="insert.php" method="post">
Name:
<input type="text" name="name">
<br>
Gender:
<input type="text" name="gender">
<br>
Age:
<input type="text" name="age">
<br>
Donuts eaten:
<input type="text" name="Donuts_eaten">
<br>
<input type="submit" name="submit" value="Submit">
</form>
PHP/SQL
<?php
/* Your Database Name */
$dbname = 'dbname'; // change this
/* Your Database User Name and Passowrd */
$username = 'username'; // change this
$password = 'password'; // change this
$pdo = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO stat (Name,
Gender,
Age,
Donuts_eaten
) VALUES (
:Name,
:Gender,
:Age,
:Donuts_eaten)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':Name', $_POST['name'], PDO::PARAM_STR);
$stmt->bindParam(':Gender', $_POST['gender'], PDO::PARAM_STR);
$stmt->bindParam(':Age', $_POST['age'], PDO::PARAM_STR);
// use PARAM_STR although a number
$stmt->bindParam(':Donuts_eaten', $_POST['Donuts_eaten'], PDO::PARAM_STR);
// old execute
// $stmt->execute();
$stmt->execute(array(':Name' => $_POST['name'],':Gender' => $_POST['gender'],':Age' => $_POST['age'],':Donuts_eaten' => $_POST['Donuts_eaten']));
if($stmt != false) {
echo "success!";
} else {
echo "an error occured saving your data!";
}
?>
Original answer
You need to wrap Donuts eaten in backticks (for your column name), due to the space.
$sql = "INSERT INTO stat(Name,
Gender,
Age,
`Donuts eaten`
) VALUES (
:Name,
:Gender,
:Age,
:Donuts_eaten)";
Using spaces in column names is discouraged. Use an underscore instead for your table's column.
Also, change:
$stmt = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
to:
$pdo = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
because you're using $pdo in $stmt = $pdo->prepare($sql);
You are mixing up your variables, $pdo is undefined / not your database connection.
You can probably solve it by using:
$pdo = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
instead of:
$stmt = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
And if a table or column name contains spaces, you need to quote them in backticks:
Gender,
Age,
`Donuts eaten`
) VALUES (
But with the first change, PDO should throw an exception to show you this problem.
I'm 'Connected to database'. There is no data in the table, and $result doesn't echo anything. Even though I'm 'Connected to database', the error is as follows:
SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected
I've read the relevant postings, with no luck.
<?php
include("/directory outside of html/db.php");
try {
$dbh = new PDO("mysql:host=$host;database=$database", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database';
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//try to insert data
$fname = 'BOB';
$lname = 'JONES';
$email = 'me#mymail.com';
$phone = '410-310-3456';
$resident = TRUE;
$age = '25=30';
$zip = '23456';
$result = FALSE;
$stmt = $dbh->prepare('INSERT INTO volunteers
(
lname,
fname,
email,
)
VALUES
(
:lname,
:fname,
:email,
)');
$result = $stmt->execute(array(
':lname' => $lname,
':fname' => $fname,
':email' => $email,
));
echo $result;
//catch any errors from try()
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Use dbname= instead of database= , like this:
$dbh = new PDO("mysql:host=$host;dbname=$database", $username, $password);
Alternatively, you can select later a different database with USE, like this:
$dbh->query("use newdatabase");