PHP PDO Simple insert does not work - php

I am converting all of my query's to PDO, and i'm new to it.
It's properly a very stupid question but why does the following code not work?
try {
$conn = new PDO('mysql:host=localhost;dbname=ddd', $user, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$id = $_SESSION['id'];
$name = $_POST['name'];
$stmt = $pdo->prepare('INSERT INTO projects
(group_id, project_name)
VALUES (:id, :name)');
$stmt->execute(array(
':id'=>$id,
':name'=>$name
));
Thanks.

Your connection variable is $conn and you are preparing your PDO Statement using $pdo->prepare.
Change to $conn->prepare()
$stmt = $conn->prepare('INSERT INTO projects
(group_id, project_name)
VALUES (:id, :name)');

You're initializing a variable for your database connection called $conn yet later call $pdo that's not mentioned anywhere. That's the first thing I'd start with.

Related

PDO return success but no data is updated on database

when i try to update a row with PDO function it returned success and when i check database there was no data updated
so i followed this question PDOStatement::execute() returns true but the data is not updated which has answers already but didn't work here is what i did
Below is code i tried
<?php
$Fuid = '105199239598939142575';
sendOT($Fuid);
echo '<br>Below is var_dump() Rsult<br>';
check($Fuid);
function sendOT($Fuid) {
try {
$phone = '6381211774';
$otp = '1234';
$conn = new PDO("mysql:host=" . DBHOST . ";port=3306;dbname=" . DBNAME, DBUSER, DBPASS);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8");
$stmt2 = $conn->prepare("UPDATE members SET verification_code=:veri_code AND phone=:phone WHERE Fuid=:Fuid");
$stmt2->bindParam(':Fuid', $Fuid, PDO::PARAM_STR);
$stmt2->bindParam(':veri_code', $otp, PDO::PARAM_STR);
$stmt2->bindParam(':phone', $phone, PDO::PARAM_STR);
$stmt2->execute();
echo 'Updated succeeded';
} catch (Exception $e) {
echo $e;
}
}
function check($Fuid) {
$conn = new PDO("mysql:host=" . DBHOST . ";port=3306;dbname=" . DBNAME, DBUSER, DBPASS);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8");
$stmt2 = $conn->prepare("SELECT * FROM members WHERE Fuid=:Fuid");
$stmt2->bindParam(':Fuid', $Fuid, PDO::PARAM_STR);
$stmt2->execute();
$unr = $stmt2->fetch(PDO::FETCH_ASSOC);
var_dump($unr);
}
?>
Output
as per the answer in this question PDOStatement::execute() returns true but the data is not updated may be there is no row with WHERE so i tried with the same WHERE with SELECT query and it showed result.
WHY is my UPDATE query doesn't update in database?
After many tries i managed to update with this query.
$stmt2 = $conn->prepare("UPDATE members SET verification_code=:veri_code, phone=:phone WHERE Fuid=:Fuid");
it worked after removing AND from query using como , in update queries.

Error: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined NOOB

I am getting this error when i am trying to build announcement system and i am getting this error every time. This is one of my first PHP things i have done so if it is able can i get help in as simple as possible way
<?php
$servername = "1234";
$username = "asd";
$password = "123";
$dbname = "admini";
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 information (name, info)
VALUES (:name, :anouncement)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':info', $info);
$name = "sam";
$info = "i hope this works without errors";
$stmt->execute();
echo "New records created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
How I see you define params late meybe you should write like this
//first params define
$name = "sam";
$info = "i hope this works without errors";
$stmt = $conn->prepare("INSERT INTO information (name, info)
VALUES (:name, :anouncement)");
//then bind
$stmt->bindParam(':name', $name);
$stmt->bindParam(':anouncement', $info); //also change info into anouncement
Also change info into anouncement for second param

I am trying to add some data in database using PHP, but it does not work

This is my PHP code starting and used connection type is PDO.
//connection with server
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=gujaratoil", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
if(isset($_POST['submit']))
{
//at the beginning null value is set
$name = $emailaddress="";
$sql = "INSERT INTO
registration(name,emailaddress)VALUES('$_POST[name]','$_POST[emailaddre
ss]')";
}
?>
I have tried all the solutions available; what should I do to solve this issue? I am using a PDO connection.
When using PDO you should use prepared statements rather than directly embedding variables in the SQL.
The reason, I believe, given the code above why the insert was failing was / is due to the lack of quotes around field names within $_POST[] ~ ie $_POST[name] which is likely to be causing undeclared constant errors
$name=$_POST['name'];
$email=$_POSt['emailaddress'];
$sql='insert into `registration` ( `name`, `emailaddress` ) values ( :name, :email )';
$stmt=$conn->prepare( $sql );
if( $stmt ){
$stmt->bindParam(':name',$name);
$stmt->bindParam(':email',$email);
$stmt->execute();
}

Can't bind value to table in database php

I keep trying this code below but for some reason it will not put the value in the database. The table in the database is named 'all'. I get no errors when running the script either.
$user = '0';
$bet = '0';
try
{
$pdo = new PDO('mysql:host='. $host .';dbname='.$db_name_wd, $db_username, $db_password);
if($pdo){
echo 'works';
}
$query = $pdo->prepare('INSERT INTO all (w_id,w_amt) VALUES (?,?)');
if($query){
echo' works2 ';
}
$query->bindValue(1, $user);
$query->bindValue(2, $bet);
$query->execute();
//echo $user;
echo $user;
}
catch (PDOException $e)
{
exit('Error Connecting To DataBase');
}
add ` to your code, because all is a reserved word in mysql
$query = $pdo->prepare('INSERT INTO `all` (`w_id`,`w_amt`) VALUES (?,?)');
And on a side note, if you separated your PDO connection and query, you would have received an SQL syntax error.
Try having seperate functions for PDO connection and querying.

Can I include one pdo connection

Im a just moving to using PDO for my development and I see in most tutorials that the connection is opend for each db query like in Jeffery Ways example below
$id = 5;
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));
while($row = $stmt->fetch()) {
print_r($row);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
Can I still do a connection in an external file and include it at the top of my page like with previous procedural coding and then do my queries below in the page?
<?php include 'includes/db.php';?>
You probably misunderstood what he says. To open one connection and use it throughout the whole application is not that something you "can" but actually you should.
So - yes, you are doing it right.
Also note that this thing with
try {
...
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
that Jeffery taught you is wrong. Never use a try catch to echo an error message. PHP will handle it better
So, your code should be like this
include 'includes/db.php';
$stmt = $pdo->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));
while($row = $stmt->fetch()) {
print_r($row);
}
while db.php has to contain something like this
<?php
$dsn = "mysql:host=localhost;dbname=test;charset=utf8mb4";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn, $username, $password, $opt);
Also note that when using this PDO object, you have to be aware of the variable scope.
Further reading: https://phpdelusions.net/pdo
The short answer is yes,
if you are farmilier with OOPHP it might be worth creating a wrapper class to help with running queries but just creating the connection in a file and including it will get the job done
in the above example you can put
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
into your db.php and the run the queries
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));
wherever you need.
it may also be worth mentioning that you dont have to use prepared statements with PDO which can speed things up in coding however if you wish to do that i would highly recomend a database wrapper class
non prepared statement
<?php
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$query = "
SELECT
col_1,
col_2
FROM
table_1
WHERE
col_3 = " . $conn->quote($_POST['input']); //the quotr is important, it escapes dangerous characters to prevent SQL injection
//this will run the query for an insert this is all thats needed
$statement = $conn->query($query);
//fetch single col
$col = $statement->fetch(PDO::FETCH_ASSOC);
//fetch all collums
$cols = $statement->fetchAll(PDO::FETCH_ASSOC);
the advantage of this way is that you can build up the query SQL in a more simple to follow manner, i should not that i havent tested this code but in theory it should be fine as this is how i do database handling
Edit:
Your Common Sense brings up a good point about the echo 'ERROR: ' . $e->getMessage(); being a bad idea and this is a prime example of why you should NEVER blindly copy and paste code
Yes, example:
db.php
<?php
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
FROM:
http://www.php.net/manual/en/pdo.error-handling.php
Then just include db.php. I name my connection $PDO, seems more implicit, especially when you are building a prepared statement on that.

Categories