bindValue is not working - php

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

Related

PHP Update Prepared Statement Issue

Here is the updated code for anyone looking to update their database. Thank you everyone for all your help.
<?php
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("UPDATE test SET title=:title WHERE id=:id");
$stmt->bindParam(':title', $title);
$stmt->bindParam(':id', $id);
// Update a row
$title = $_POST['title'];
$id = $_POST['id'];
$stmt->execute();
echo "Row updated";
echo "<br />";
echo "<strong>$title</strong> and <strong>$id</strong>";
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
You still have a bit of a mix of PDO and MySQLi although only in your call to bindParam now, which you are calling as if it was MySQLi::bind_param. Also in your last edit the query string got messed up with the addition of Values=? I'm not sure why you did that? Anyway, this should do what you want:
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("UPDATE test SET title=:title WHERE id=:id");
$stmt->bindParam(':title', $title);
$stmt->bindParam(':id', $id);
// Update a row
$title = $_POST['title'];
$stmt->execute();
echo "Row updated";
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
Use bind_param() :
<?php
$statement = $conn->prepare("UPDATE test SET title= ? WHERE id= ?");
$statement->bind_param('si', $title,$id);
$statement->execute();
if ($statement->affected_rows >0) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$statement->close();
?>
use this.hope it will help you.
<?php
$statement = $conn->prepare("UPDATE myTable SET name = ? WHERE id = ?");
$statement->bind_param("si", $_POST['title'],$id);
$statement->execute();
$statement->close();
?>

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";
}
}

php PDO prepare(" INSERT ..(variables ) VALUES(?,?,) produces an error need assistance

$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!";
}

Why isn't anything being inserted into my MySQL table?

I have some PDO that I'm trying to use to insert data into a MySQL table.
private function addResource() {
include('./dbconnect.php');
$pdo = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_password);
$stmt = $pdo->prepare('INSERT INTO Resources VALUES (?, $title, $url, $_SESSION[\'tblUserID\'');
$stmt->bindParam(1, $title);
$stmt->bindParam(2, $url);
$stmt->bindParam(3, $_SESSION['tblUserID']);
$stmt->execute();
if ($stmt->rowCount() != 1)
throw new Exception('Could not add resource');
$status = true;
}
Thing is, whenever I check the table, nothing is being inserted. How come?
EDIT: I have session_start() at the top of the page.
Because you're using PDO completely wrong. Placeholders do not use PHP variable syntax. The query string should be:
$stmt = $pdo->prepare('INSERT INTO .... VALUES (:id, :title, :url, :userid')
^^^^^^
$stmt->bindParam(':title', $title);
^^^^^^
Note the use of the :whatever format for placeholders.
As it is written now, your query is a flat-out syntax error, and vulnerable to SQL injection attacks
Try this:
private function addResource() {
include('./dbconnect.php');
try{
$pdo = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_password);
$stmt = $pdo->prepare('INSERT INTO Resources VALUES (:title, :url, :userid)';
$stmt->bindParam(':title', $title);
$stmt->bindParam(':url', $url);
$stmt->bindParam(':userid', $_SESSION['tblUserID']);
$stmt->execute();
if ($stmt->rowCount() != 1)
throw new Exception('Could not add resource');
$status = true;
}
}catch (Exception $e){
echo $e->getMessage();
exit;
}
}
Ref: http://php.net/manual/en/pdo.prepared-statements.php

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

Categories