Show message if inserted successfully PDO - php

I wrote some PHP code to insert the records in to MySQL database. I want to display a message indicating whether the records are successfully added to the database or not. I tried several times but I failed.
Code:
<?php
try {
$db_user = 'root';
$db_pass = 'cea123';
$db = new PDO( 'mysql:host=localhost;dbname=symposium', $db_user, $db_pass );
$form = $_POST;
$sql = "INSERT INTO app (
firstname, lastname, company, homepage, contactno, addressline1, addressline2, city,
postalcode, country, email, abstractdetails )
VALUES (
:firstname, :lastname, :company, :homepage, :contactno, :addressline1, :addressline2,
:city, :postalcode, :country, :email, :abstractdetails )";
$query = $db->prepare( $sql );
$query->execute( array( ':firstname'=>$firstname, ':lastname'=>$lastname, ':company'=>$company, ':homepage'=>$homepage, ':contactno'=>$contactno, ':addressline1'=>$addressline1, ':addressline2'=>$addressline2, ':city'=>$city, ':postalcode'=>$postalcode, ':country'=>$country, ':email'=>$email, ':abstractdetails'=>$abstractdetails ));
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>

You can check simply using rowCount function,
if($query->rowCount() > 0){
echo "Record Inserted Successfully !!";
}

In your current code you never print out a Text that show you that your Insert was succesfull.
catch(PDOException $e)
{
echo $e->getMessage();
}
will only show you the error, if one appeard.
To print a text that will show you that it was succesfull you have to insert at the end of the try block (before your catch block)
try {
[...]
if($query->rowCount() > 0){
echo "Record Inserted Successfully !!";
}
} catch(PDOException $e) {
[...]
}

Related

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

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();

Trying to insert data into database PHP PDO

I've tried everything and just cant seem to get this working.. it's probably a silly mistake I can't see but any help is appreciated.
As stated in the question I'm trying to insert records into a table via a form. I have a functions.php which includes my database.php with the pdo connection (all working fine) class with the following function in it:
function insertStaffUser($username, $password, $role) {
include('database.php');
try {
$query = "INSERT INTO users (userid, username, password, role) VALUES (default, :username, :password, :role)";
$stmt->$db->prepare($query);
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
$stmt->bindParam(':role', $role);
$result = $stmt->execute();
if($result) {
echo "INSERTED SUCCESSFULLY";
} else {
echo "error inserting";
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
And the following code is the one in my html class which is addUser.php with 3 text fields (new username, password and role).
<?php
if(isset($_POST['submit'])) {
$new_username = $_POST['username'];
$new_pass = $_POST['password'];
$new_role = $_POST['role'];
insertStaffUser($new_username, $new_pass, $new_role);
}
?>
Can anyone see what's wrong with this or what I'm doing wrong, thanks for the help!

PHP pdo insert query not working

<?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.

Performing insert/update query with PDO

I'm having problems with my code here. I have a form where a user fills out some information and submits it to be added to the database. The form can be used to submit a new row or to edit an existing one. However, neither queries appear to be working and I cannot see why. Can anyone see any errors in my code here?
Also, I am aware I shouldn't be echoing my PDO exception's but I have done this temporarily for debugging purposes. But nothing is echoed. There don't appear to be any errors.
try {
$db = new PDO('mysql:host=x.x.x.x;dbname=xxx', "xxx", "xxx");
} catch (PDOException $ex) {
echo $ex->getMessage();
}
if (isset($_POST['title'])) {
try {
$stmt = $db->prepare("SELECT * FROM xxxxx WHERE Title = :title;");
$stmt->bindParam(':title', $_POST['title']);
$stmt->execute();
$rows = $stmt->fetchAll();
} catch (PDOException $ex) {
echo $ex->getMessage();
}
if (count($rows) > 0){
$result = $rows[0];
if($result['Author'] == $_SESSION['user_name']) {
try {
$stmt = $db->prepare("UPDATE xxxxx SET Title = :title, `Short Desc` = :short, Description = :desc, Location = :loc, Genre = :genre, Date = :date, lat = :lat, lng = :lng WHERE ID = :id and Author = :user LIMIT 1;");
$stmt->bindParam(':title', $_POST['title']);
$stmt->bindParam(':short', $_POST['shortdesc']);
$stmt->bindParam(':desc', $_POST['description']);
$stmt->bindParam(':loc', $_POST['location']);
$stmt->bindParam(':genre', $_POST['genre']);
$stmt->bindParam(':date', $_POST['date']);
$stmt->bindParam(':lat', $_POST['lat']);
$stmt->bindParam(':lng', $_POST['lng']);
$stmt->bindParam(':user', $_SESSION['user_name']);
$stmt->execute();
$err = "Your ad was successfully updated.";
} catch (PDOException $ex) {
echo $ex->getMessage();
}
} else {
$err = "An ad already exists with that title.";
}
} else {
try {
$stmt = $db->prepare("INSERT INTO xxxxx (`Title`, `Short Desc`, `Description`, `Location`, `Genre`, `Date`, `Author`, `lat`, `lng`) VALUES (:title,:short,:desc,:loc,:genre,:date,:user,:lat,:lng)");
$stmt->bindParam(':title', $_POST['title']);
$stmt->bindParam(':short', $_POST['shortdesc']);
$stmt->bindParam(':desc', $_POST['description']);
$stmt->bindParam(':loc', $_POST['location']);
$stmt->bindParam(':genre', $_POST['genre']);
$stmt->bindParam(':date', $_POST['date']);
$stmt->bindParam(':lat', $_POST['lat']);
$stmt->bindParam(':lng', $_POST['lng']);
$stmt->bindParam(':user', $_SESSION['user_name']);
$stmt->execute();
$err = "Your ad was successfully added to our database.";
} catch (PDOException $ex) {
echo $ex->getMessage();
}
}
}

Data insert into mysql db table using PDO - Doesn't Insert 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");

Categories