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.
Related
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());
}
?>
<?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 assign uuid() to the id field. It works perfectly. But I don't know how to echo the generated uuid back to the user. How can I do this?
My code:
<?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 (id,firstname, lastname, email)
VALUES (UUID(),: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();
echo "New records created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
You can't.
Your only choice is separating this into two queries.
SELECT UUID()
Retrieve created UUID into a php variable ($uuid)
Insert that variable into your prepared statement.
$stmt = $conn->prepare("INSERT INTO MyGuests (id,firstname, lastname, email)
VALUES (:uuid,:firstname, :lastname, :email)");
$stmt->bindParam(':uuid', $uuid);
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
$query = $this->link->prepare("INSERT INTO surveys (`username`,`inspected`,
`comments`,`ip_address`,`date`,`time`)
VALUES '(?,?,?,?,?,?)';);
$values = array ($username,$inspected,$comments,$ip_address,$date,$time);
var_dump($query);$rowCount = $query->rowCount();
$return $rowCount;
You can base yourself on the following which I've prepared for you.
Sidenote: I'm not entirely sure as to why you want to use rowCount() for, so I left it out for now.
If you're looking to check if a record exists using rowCount(), let me know.
The following method works to insert data into a database, which is based on a method I use.
<?php
$dbname = 'xxx';
$username = 'xxx';
$password = 'xxx';
try {
$pdo = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
exit( $e->getMessage() );
}
$sql = "INSERT INTO surveys (
username,
inspected,
comments,
ip_address,
date,
time
) VALUES (
:username,
:inspected,
:comments,
:ip_address,
:date,
:time)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $_POST['username'], PDO::PARAM_STR);
$stmt->bindParam(':inspected', $_POST['inspected'], PDO::PARAM_STR);
$stmt->bindParam(':comments', $_POST['comments'], PDO::PARAM_STR);
$stmt->bindParam(':ip_address', $_POST['ip_address'], PDO::PARAM_STR);
$stmt->bindParam(':date', $_POST['date'], PDO::PARAM_STR);
$stmt->bindParam(':time', $_POST['time'], PDO::PARAM_STR);
// $stmt->execute();
$stmt->execute(array(':username' => $_POST['username'],':inspected' => $_POST['inspected'],':comments' => $_POST['comments'],
':ip_address' => $_POST['ip_address'],':date' => $_POST['date'],':time' => $_POST['time']));
if($stmt != false) {
echo "success!";
} else {
echo "an error occured saving your data!";
}
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");