Converting MySql Insert To PDO - php

I am trying to convert this to PDO:
echo 'sup 1';
$sql = "INSERT INTO blogData(
title,
content,
category)
VALUES (
:title,
:content,
:category)";
echo 'sup 2';
$stmt = prepare($sql);
echo 'sup 3';
$stmt->bindParam(':title', $_POST['title'], PDO::PARAM_STR);
$stmt->bindParam(':content', $_POST['content'], PDO::PARAM_STR);
$stmt->bindParam(':category', 'City Secrets', PDO::PARAM_STR);
echo 'sup 4';
$stmt->execute();
echo 'sup 5';
header('location: http://www.backToThePageIPostedOn.com');
This is my current code but it is not entering to the DB:
$sql = "INSERT INTO blogData(
title,
content,
category)
VALUES (
:title,
:content,
:category)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':title', $_POST['title'], PDO::PARAM_STR);
$stmt->bindParam(':content', $_POST['content'], PDO::PARAM_STR);
$stmt->bindParam(':category', 'City Secrets', PDO::PARAM_STR);
$stmt->execute();
header('location: http://www.backToThePageIPostedOn.com');
Its stopping on the script page. This is my first time to use PDO so If someone could point out the error in my syntax I would appreciate it.
My code does not get past echo 'sup 2';
So I believe the error is in this line, $stmt = $pdo->prepare($sql);
I followed a tutorial to do this and I don't understand why they are adding the
$pdo in.
I was assuming thats supposed to be my connection but I have that set as
$con
When I change
$pdo to $con I still get the same cut off at echo 'sup 2';

Statement bindParam method accepts second parameter by reference. Only variables can be passed by reference.
The solution is to assign to variables the params you are going to bind:
$stmt = $pdo->prepare($sql);
$title = $_POST['title'];
$content = $_POST['content'];
$category = 'City Secrets';
$stmt->bindParam(':title', $title, PDO::PARAM_STR);
$stmt->bindParam(':content', $content, PDO::PARAM_STR);
$stmt->bindParam(':category', $category, PDO::PARAM_STR);
$stmt->execute();

This is the correct working code for the question above.
$stmt->bindParam
changed to
$stmt->bindValue
And added the connection.php file for DB connection.
<?php
require_once( 'connection.php' );
$sql = "INSERT INTO blogData(
title,
content,
category)
VALUES (
:title,
:content,
:category)";
$stmt = $con->prepare($sql);
$stmt->bindParam(':title', $_POST['title'], PDO::PARAM_STR);
$stmt->bindParam(':content', $_POST['content'], PDO::PARAM_STR);
$stmt->bindValue(':category', 'City Secrets', PDO::PARAM_STR);
$stmt->execute();
header('location: http://www.website.com');
?>

Related

Mysterious behaviour of php

Below code works as expected. It adds 3 entries to the table 'keywords'.
<?php
include "config.php";
try{
// $conn = new PDO(DBINFO,USER,PASS);
// $sql = "INSERT INTO projects (title,duration, startyear, description, tags,email) VALUES (:title,:duration, :startyear, :description, :tags,:email)";
// $stmt = $conn->prepare($sql);
// $stmt->bindParam(':title', $_POST['title'],PDO::PARAM_STR);
// $stmt->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
// $stmt->bindParam(':duration', $_POST['duration'], PDO::PARAM_STR);
// $stmt->bindParam(':startyear', $_POST['startyear'], PDO::PARAM_STR);
// $stmt->bindParam(':description', $_POST['description'], PDO::PARAM_STR);
// $stmt->bindParam(':tags', $_POST['tags'], PDO::PARAM_STR);
// $stmt->execute();
for($i=0; $i<3; $i++){
$conn2 = new PDO(DBINFO,USER,PASS);
$sql2 = "INSERT INTO keywords (keyword,confidence) VALUES (:keyword,:confidence)";
$stmt2 = $conn2->prepare($sql2);
$a = 'asdfds';
$stmt2->bindParam(':keyword', $a,PDO::PARAM_STR);
$stmt2->bindParam(':confidence', $a, PDO::PARAM_STR);
$stmt2->execute();
}
}
catch(PDOException $pe){
die("Could not connect to the database :".$pe->getMessage());
}
?>
However, when I run the below code (where I uncommented the first part), the entries get added 6 times to the 'keywords' table.
<?php
include "config.php";
try{
$conn = new PDO(DBINFO,USER,PASS);
$sql = "INSERT INTO projects (title,duration, startyear, description, tags,email) VALUES (:title,:duration, :startyear, :description, :tags,:email)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':title', $_POST['title'],PDO::PARAM_STR);
$stmt->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
$stmt->bindParam(':duration', $_POST['duration'], PDO::PARAM_STR);
$stmt->bindParam(':startyear', $_POST['startyear'], PDO::PARAM_STR);
$stmt->bindParam(':description', $_POST['description'], PDO::PARAM_STR);
$stmt->bindParam(':tags', $_POST['tags'], PDO::PARAM_STR);
$stmt->execute();
for($i=0; $i<3; $i++){
$conn2 = new PDO(DBINFO,USER,PASS);
$sql2 = "INSERT INTO keywords (keyword,confidence) VALUES (:keyword,:confidence)";
$stmt2 = $conn2->prepare($sql2);
$a = 'asdfds';
$stmt2->bindParam(':keyword', $a,PDO::PARAM_STR);
$stmt2->bindParam(':confidence', $a, PDO::PARAM_STR);
$stmt2->execute();
}
}
catch(PDOException $pe){
die("Could not connect to the database :".$pe->getMessage());
}
?>
I can't understand this. Any help?
Why do you create 4 different connections to the same server and schema in the first place?
The loop creates connections and closes them automatically when the references to statements and connections are overwritten.
But the original connection from before the loop will stay open and is reused for the statements. If you create a third connection without closing it before the loop you'll end up with 9 entries.
So delete the references to connection objects if they are no longer needed (this includes associated statements).
Or better yet reuse connections instead of creating a new connection for every statement.

PHP Session with MySQL Insert Into using bind_parm

I am simply trying to insert the variable from a session into a MySQL database and it causes it to fail. var_dump shows SESSIONS all there. No problem there. Why doesn't this work?
$job = $_SESSION['job'];
$user_id = '1';
$name = 'allie';
$stmt = $mysqli->prepare("INSERT INTO
requests(name,job_info,user_id)
VALUES (?,?,?)");
$stmt->bind_param('sss', $name, $job, $user_id);
$stmt->execute();
see pdo bind_param
your parameter is incorrect:
change this:
$stmt->bind_param('sss', $name, $job, $user_id);
with this:
$stmt->bind_param(1, $name, PDO::PARAM_STR);
$stmt->bind_param(2, $job, PDO::PARAM_STR);
$stmt->bind_param(3, intval($user_id), PDO::PARAM_INT);

Trying to change it so that the system gets the date. Not to get the date from the user

I have an issue I am trying to get the current date when user updates the form. What I am trying to do is instead of posting what the user types in for the date. I wanted the system to get the date. How do I make it so that the update_process.php page gets the current date. In the $_POST[date] bindparam section. I tried adding getdate() in there but that does not work. I am confused on how to do it.
<?php
$serverName = "localhost";
try {
$db= new PDO( "sqlsrv:server=$serverName ; Database=systems_requests", "test", "test");
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch(Exception $e) {
die( print_r( $e->getMessage() ) );
}
$sql = 'UPDATE requests SET id=:id, studentId= :studentId, name= :name, date= :date WHERE id= :id';
$stmt = $db->prepare($sql);
$stmt->bindParam(':id', $_POST['id'], PDO::PARAM_INT);
$stmt->bindParam(':studentId', $_POST['studentId'], PDO::PARAM_STR);
$stmt->bindParam(':name', $_POST['name'], PDO::PARAM_STR);
$stmt->bindParam(':date', $_POST['date'], PDO::PARAM_STR);
try {
$stmt->execute();
} catch(PDOException $exception) {
echo "Error: " . $exception->getMessage();
}
?>
also how would I change the count to reflect that to count how many Bob's signed up with todays date.
<?php
$stmt = $db->prepare("SELECT COUNT(*) AS rows_cnt FROM students WHERE name='Bob' AND date=getdate()");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['rows_cnt'];
}
?>
To fix my issue I had to remove set ID in order for the update to work.
$sql = 'UPDATE requests SET studentId= :studentId, name= :name, date=getdate() WHERE id= :id';
$stmt = $db->prepare($sql);
$stmt->bindParam(':id', $_POST['id'], PDO::PARAM_INT);
$stmt->bindParam(':studentId', $_POST['studentId'], PDO::PARAM_STR);
$stmt->bindParam(':name', $_POST['name'], PDO::PARAM_STR);
$stmt->execute();
$sql = 'UPDATE requests SET id=:id, studentId= :studentId, name= :name, date=getdate() WHERE id= :id';
$stmt = $db->prepare($sql);
$stmt->bindParam(':id', $_POST['id'], PDO::PARAM_INT);
$stmt->bindParam(':studentId', $_POST['studentId'], PDO::PARAM_STR);
$stmt->bindParam(':name', $_POST['name'], PDO::PARAM_STR);
$stmt->execute();
Like I said in the comments, I'm not sure what the role of $_POST['date'] is, so why are you using it? From your question, it seems like you just want the current date, not user input. In that case, you don't need to bind a parameter, you just put the date function in the query.

PDO prepared statement and bindValues from an array

I have the following block of code in a PDO statement:
$stmt = $db->prepare("INSERT INTO first_page_data (title, first_name, surname, phone, email, add1, add2, add3, add4, add5) VALUES(?,?,?,?,?,?,?,?,?,?)");
$stmt->bindValue(1, $_POST['title'], PDO::PARAM_STR);
$stmt->bindValue(2, $_POST['first_name'], PDO::PARAM_STR);
$stmt->bindValue(3, $_POST['surname'], PDO::PARAM_STR);
$stmt->bindValue(4, $_POST['phone'], PDO::PARAM_INT);
$stmt->bindValue(5, $_POST['email'], PDO::PARAM_STR);
$stmt->bindValue(6, $_POST['add1'], PDO::PARAM_STR);
$stmt->bindValue(7, $_POST['add2'], PDO::PARAM_STR);
$stmt->bindValue(8, $_POST['add3'], PDO::PARAM_STR);
$stmt->bindValue(9, $_POST['add4'], PDO::PARAM_STR);
$stmt->bindValue(10, $_POST['add5'], PDO::PARAM_STR);
$stmt->execute();
$_SESSION['buyer_email'] = $_POST['email'];
Can these parameters (title, first_name, etc) be put into the bindValues using an array and a for each loop? I can get the prepare statement working by just having an array containing the titles but cant seem to get the variable names inside the $_POST values. It would save quite a few lines of code, but I cant quite get there!
The following is the array im using in the prepared statement that I want to use in the bind value loop:
$first = array('title','first_name','surname','phone','email','add1','add2','add3','add4','add5');
Just simply loop over $first and call bindValue for each one.
foreach($first as $key=>$val){
$stmt->bindValue($key+1, $_POST[$val], PDO::PARAM_STR);
}
Or you can use it like this:
$stmt = $db->prepare("INSERT INTO first_page_data (title, first_name, surname, phone, email, add1, add2, add3, add4, add5) VALUES(?,?,?,?,?,?,?,?,?,?)");
$stmt->execute($array);
The array would be like:
$array = array($_POST['title'],$_POST['first_name']);
or if you have the correct order already just
$array = $_POST;

pdo statement failing to execute

i have a pdo block for inserting values into my table as follows
try{
$user = 'root';
$pass = null;
$pdo = new PDO('mysql:host=localhost; dbname=divebay', $user, $pass);
$name = $_POST['name'];
$desc = $_POST['description'];
$cond = $_POST['condGroup'];
$sprice = $_POST['sprice'];
$iprice = $_POST['iprice'];
$incprice = $_POST['incprice'];
$duration = $_POST['duration'];
$img = $_POST['img'];
$owner = $_SESSION['username'];
$valid = "set";
$stmt2 = $pdo->prepare("SELECT * FROM auction WHERE ID = :id");
$stmt2->bindParam(":id", $random, PDO::PARAM_INT);
while(isset($valid)){
$random = rand(100000,999999);
$stmt2->execute();
if(!$stmt2->fetch(PDO::FETCH_ASSOC)){
unset($valid);
}
}
$timestamp = time() + ($duration * 24 * 60 * 60);
$stmt = $pdo->prepare("INSERT INTO auction(ID, name, owner, holder, sprice, iprice, incprice, etime, img, condition, description)
VALUES (:id, :name, :owner, :holder, :sprice, :iprice, :incprice:, :etime, :img, :condition, :description");
$stmt->bindParam(':id', $random, PDO::PARAM_INT);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':owner', $owner, PDO::PARAM_STR);
$stmt->bindParam(':holder', $owner, PDO::PARAM_STR);
$stmt->bindParam(':iprice', $iprice, PDO::PARAM_STR);
$stmt->bindParam(':sprice', $sprice, PDO::PARAM_STR);
$stmt->bindParam(':incprice', $incprice, PDO::PARAM_STR);
$stmt->bindParam(':etime', $timestamp, PDO::PARAM_INT);
$stmt->bindParam(':img', $img, PDO::PARAM_STR);
$stmt->bindParam(':condition', $condition, PDO::PARAM_STR);
$stmt->bindParam(':description', $description, PDO::PARAM_STR);
if($stmt->execute()){
$worked ="yes";
}
}catch(PDOException $e){
echo $e->getMessage();
}
i cant tell why this statement wont execute, the $worked variable has not been set when it is the script is run. all database column names and datatypes have been checked correct as they are. ive never had a problem with a statement not executing until now. whats wrong? how do i go about debugging this?
If you setup the database connection with error mode exception PDO will throw an exception if something is wrong with your statement. I also see that you are using the MySQL driver for PDO. If you do this you should always disable emulated prepared statements. So I would write you connection as following (note that I have also set the encoding):
$pdo = new PDO('mysql:host=localhost; dbname=divebay;charset=utf8', $user, $pass);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Also see this post for more information about this.
Once you have done this you will see that your statement is wrong. You have one missing ) at the end of the statement:
$stmt = $pdo->prepare("INSERT INTO auction(ID, name, owner, holder, sprice, iprice, incprice, etime, img, condition, description)
VALUES (:id, :name, :owner, :holder, :sprice, :iprice, :incprice:, :etime, :img, :condition, :description)");
^
Modify this line:
$stmt = $pdo->prepare("INSERT INTO auction(ID, name, owner, holder, sprice, iprice, incprice, etime, img, condition, description)
VALUES (:id, :name, :owner, :holder, :sprice, :iprice, :incprice:, :etime, :img, :condition, :description");
To
$stmt = $pdo->prepare("INSERT INTO auction(ID, name, owner, holder, sprice, iprice, incprice, etime, img, condition, description)
VALUES (:id, :name, :owner, :holder, :sprice, :iprice, :incprice:, :etime, :img, :condition, :description)");
The difference is the ) at the end.
And tell me if it works now.

Categories