Performing insert/update query with PDO - php

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

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

Can't figure out this bindParam issue

I'm trying to fetch some data from a MySql db using PDO but no matter what I do, I can't get anything when using a prepared statement... please tell me what I'm doing wrong.
The following code runs but returns nothing.
try {
$dbh = new PDO('mysql:host=localhost;dbname=banim', 'root', '');
$uName = "banim"; //$_POST['uName'];
$email = "Rabak#gmail.com"; //$_POST['email'];
$query = $dbh->prepare("SELECT * from users WHERE email = :email OR WHERE uName = :name");
$query->setFetchMode(PDO::FETCH_ASSOC);
$query->bindParam(":name", $uName);
$query->bindParam(":email", $email);
$query->execute();
foreach ($query as $row) {
print_r($query);
}
} catch (PDOException $e) {
echo "PDOException: " . $e->getMssage() . PHP_EOL;
}
What Alive To Die wrote was correct, and there was also an extra WHERE in the SQL string which also messed up the answer, this is the final code:
try {
$dbh = new PDO('mysql:host=localhost;dbname=banim', 'root', '');
$uName = "banim"; //$_POST['uName'];
$email = "Rabak#gmail.com"; //$_POST['email'];
$query = $dbh->prepare("SELECT * from users WHERE email = :email OR uName = :name");
$query->setFetchMode(PDO::FETCH_ASSOC);
$query->bindParam(":name", $uName);
$query->bindParam(":email", $email);
$query->execute();
while($row = $query->fetch()){
print_r($row);
}
} catch (PDOException $e) {
echo "PDOException: " . $e->getMssage() . PHP_EOL;
}

bindValue is not working

Using PDO with MariaDB server. I am having trouble understanding why this code does not work. Whenever I have :value for the values it gives me an error " Invalid parameter number: parameter was not defined"
$sql = "INSERT INTO table (USER, DOMAIN,FLG) VALUES (:username,:domain,:flag)";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':domain', $domain);
$stmt->bindValue(':flag', $flag);
$stmt->execute();
But then the code below does work.
$sql = "INSERT INTO table (USER, DOMAIN,FLG) VALUES (?,?,?)";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(1, $username);
$stmt->bindValue(2, $domain);
$stmt->bindValue(3, $flag);
$stmt->execute();
Below is the rest of the section for this code.
if(isset($_POST['addEditor'])){
$username = $_POST['formUsername'];
$domain = $_POST['formDomain'];
$flag = $_POST['formflg'];
$sql = "INSERT INTO table (USER, DOMAIN,FLG) VALUES (:username,:domain,:flag)";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':domain', $domain);
$stmt->bindValue(':flag', $flag);
$stmt->execute();
try{
$stmt->execute();
}
catch (Exception $e) {
die ('ERROR: ' . $e->getMessage());
}
That code worked for me have read something about PDO here
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$username='a';
$domain ='b';
$flag ='c';
$sql = "INSERT INTO `table` (`USER`, `DOMAIN`, `FLG`) VALUES (:username,:domain,:flag)";
$stmt = $dbh->prepare($sql);
$stmt->execute(
array(':username'=> $username,
':domain'=> $domain,
':flag'=> $flag)
);
I am having trouble understanding why this code does not work.
No wonder, as you're using wrong way to understand.
Get rid of all try and catch operators in your code, run it again and then read the full error message, that will make you understand which code does not work.
if($_POST)
{
$role ="student";
try{
$stmt = $db_con->prepare("INSERT INTO userinfo (role)
VALUES(:qrole)");
$stmt->bindParam(":qrole", $role);
if($stmt->execute())
{
echo "Successfully Added";
}
else{
echo "Query Problem";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
try this , if some errors occurred it will post it using catch

Inserting into DB sometimes doesn´t work (chat with PDO, AJAX, long polling)

I have chat that uses long polling to get messages from DB (there are no problems to load them). But i also have script that insert messages into DB and it sometimes doesnt work ... it just doesn´t insert the row but it says that it was inserted.
<?php
include_once "../conect.php";
$sprava = $_POST['sprava']; // received message
session_start();
echo $sprava;
$ja = $_SESSION['id'];
session_write_close();
$cas = time();
try {
$conn = new PDO($databaza, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT som FROM user WHERE id = :ja";
$stmt = $conn->prepare($query);
$stmt->bindValue(':ja', $ja, PDO::PARAM_STR);
if ($stmt->execute()) echo "works ";
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$on = $row["som"];
echo $on;
if ($on == "") return 0;
try {
$conn = new PDO($databaza, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "INSERT INTO chat (cas,text,od,pre) VALUES (:cas, :text, :od, :pre)";
$stmt = $conn->prepare($query);
$stmt->bindValue(':cas', $cas, PDO::PARAM_STR);
$stmt->bindValue(':text', $sprava, PDO::PARAM_STR);
$stmt->bindValue(':od', $ja, PDO::PARAM_STR);
$stmt->bindValue(':pre', $on, PDO::PARAM_STR);
$stmt->execute();
$affected_rows = $stmt->rowCount();
if ($affected_rows == 1) echo " works";
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();}
?>
i get no errors and outpus is still in form as it should be
for example
1 works 37 works
2 works 37 works
3 works 37 works
4 works 37 works
5 works 37 works
that first number is message I entered, the first "works" means that ID of user was loaded, the second nuber is loaded ID and the last "works" means that the message was inserted into DB but it sometimes wasn´t (just sometimes).
but in DB i have rows only with for example
1
2
4
and 3, 5 is missing
An INSTEAD OF INSERT trigger is doing this. Check your table's triggers.
You are returning 0 when $on is empty, when this happens , it won't insert the data
If you are going to SELECT an INSERT in the same script, then I suggest you to split that logic especially if the INSERT depend on what the SELECT returns.
Create 2 fucntions:
SELECT function
function select_som($conn, $ja){
try {
$query = "SELECT som FROM user WHERE id = :ja";
$stmt = $conn->prepare($query);
$stmt->bindValue(':ja', $ja, PDO::PARAM_STR);
$success = $stmt->execute();
if(!$success){
echo "SELECT failed";
}
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$on = $row["som"];
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
return $on;
}
INSERT function
function insert_data($conn, $cas, $sprava, $ja, $on){
try {
$query = "INSERT INTO chat (cas,text,od,pre) VALUES (:cas, :text, :od, :pre)";
$stmt = $conn->prepare($query);
$stmt->bindValue(':cas', $cas, PDO::PARAM_STR);
$stmt->bindValue(':text', $sprava, PDO::PARAM_STR);
$stmt->bindValue(':od', $ja, PDO::PARAM_STR);
$stmt->bindValue(':pre', $on, PDO::PARAM_STR);
$stmt->execute();
$affected_rows = $stmt->rowCount();
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
return $affected_rows;
}
Usage:
if(isset($_POST['sprava'])){
include_once "../conect.php";
//session
session_start();
$ja = $_SESSION['id'];
session_write_close();
//connection
$conn = new PDO($databaza, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//get "$on"
$on = select_som($conn, $ja);
//insert
if($on != ""){
$cas = time();
$sprava = $_POST['sprava'];
$success = insert_data($conn, $cas, $sprava, $ja, $on);
if($success==1){
echo "INSERT Successful";
}else{
echo "INSERT Failed!!";
}
}else{
echo "on is empty, cannot insert data";
}
}

Show message if inserted successfully PDO

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) {
[...]
}

Categories