I'm new to php I have created a php form that will insert data into the database my database name is Emp and the table name is info. I'm inserting using PDO. I have written a code to do this and it is getting executed without catching any errors, but the database is still empty. I have posted my code below please tell me what I'm doing wrong.
<?php
try{
echo $_POST['name'].", ".$_POST['age'].", ".$_POST['email'].", ".$_POST['name'].", ".$_POST['country'].", ". $_POST['city'] ;
$user="root";
$pass="root123";
$con=new PDO('mysql:host=localhost;dbname=Emp', $user, $pass);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$con->beginTransaction();
//echo "INSERT INTO info(Empid,Ename,Age,Email,Country,City,Salary) VALUES('".$_POST['eid']."','".$_POST['name']."','".$_POST['age']."','".$_POST['email']."','".$_POST['country']."','".$_POST['city']."','".$_POST['salary']."')";
$num=$con->exec("INSERT INTO info(Empid,Ename,Age,Email,Country,City,Salary) VALUES('".$_POST['eid']."','".$_POST['name']."','".$_POST['age']."','".$_POST['email']."','".$_POST['country']."','".$_POST['city']."','".$_POST['salary']."')");
echo "<br>".$num." row added succesfully"; // this is displayed when I execute this but database is empty.
}
catch(Exception $e)
{
echo 'Exception -> ';
var_dump($e->getMessage());
}
?>
Since you have used beginTransaction(), you have to commit the changes. Add
$con->commit();
Reference: PHP Manual
Note: Even though you are using PDO, you are still interpolating HTTP Request values without sanitization, that could be bad
you either have to commit or rollback the transaction ..
changes made to the database via the PDO transactions are not committed until you end the transaction by calling PDO::commit() or Calling PDO::rollBack()
<?php
try{
echo $_POST['name'].", ".$_POST['age'].", ".$_POST['email'].", ".$_POST['name'].", ".$_POST['country'].", ". $_POST['city'] ;
...
$con->beginTransaction();
....
$con->commit();
}
catch(Exception $e)
{
echo 'Exception -> ';
var_dump($e->getMessage());
$con->rollBack();
}
?>
All you need to do is to commit and/or rollBack your code
<?php
try{
.
. code
.
$con->beginTransaction();
.
. code
.
$num=$con->exec("INSERT INTO info (Empid,Ename,Age,Email,Country,City,Salary) VALUES('".$_POST['eid']."','".$_POST['name']."','".$_POST['age']."','".$_POST['email']."','".$_POST['country']."','".$_POST['city']."','".$_POST['salary']."')");
$con->commit(); // This is missing
}
catch(Exception $e)
{
var_dump($e->getMessage());
$con->rollBack(); // And this is missing
}
?>
Related
I am using the below code to delete all rows from the mysql table but it does not take any effect. I am also not getting any errors - it just says record Record deleted successfully. I don't know if there is any backend safe mode enabled or I need to do additional commits but all the data is still in the database.
<?php
try {$pdo = new PDO("mysql:host=mysql;dbname=menu;charset=utf8mb4", "user",
"pass", array(PDO::ATTR_PERSISTENT => true));
} catch (\PDOException $e) {throw new \PDOException($e->getMessage(), (int)$e->getCode());};
$org = "1";
try {
$sql = "DELETE FROM menu where org=?";
$pdo->prepare($sql)->execute([$org]);
echo "Record deleted successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
?>
For some reason, this code always returns “Connected to Database” even when I try to test the, try catch block and break the connection. When I change the name of the database to test the exception, it just creates a new database.
Any ideas?
<?php
try{
$db = new PDO ("sqlite:".__DIR__."/database.db");
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch (Exception $e){
echo 'Caught exception: ', $e->getMessage();
exit;
}
echo "Connected to Database";
?>
I believe this is expected behavior with pdo_sqlite: if you provide a path to a database that doesn't exist, and PHP is able to write to files in the directory of that path, it will simply create the database under the filename you've provided.
If you want to test the case where the file isn't writable, you can change file permissions such that the user that PHP runs as doesn't have write access.
Because echo "Connected to Database"; is not within the try brackets, it will always echo that.
Try this.
<?php
try{
$db = new PDO ("sqlite:".__DIR__."/database.db");
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
echo "Connected to Database";
} catch (Exception $e){
echo 'Caught exception: ', $e->getMessage();
exit;
}
?>
I am converting an old php 5.6 code to 7.2 and learning how to use PDO.
I have reached a point where I got stuck and would like to learn from the community.
I created a test file structure:
db.php:
<?php
try {
$conn = new PDO($initlocation, $username, $pwdata);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "worked"; // THIS WORKS ON THE SCREEN
}
catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
?>
test.php:
<?php
include("db.php");
$user_query='SELECT * FROM `users` WHERE `email`="user1.a#gmail.com"';
echo $user_query; // I GET THE QUERY PRINTED ON THE SCREEN
echo is_object($conn); // THIS IS 1 WHICH IS GOD
echo "<br>";
echo is_object($res); // THIS IS 1 WHICH IS ODD
try{
$res = $conn->query($user_query);
}
catch (Exception $e){
echo "Query failed: " . $e->getMessage(); // NOTHING
}
echo "<br>";
echo is_object($res); // NOTHING
$data_exists = $res->fetch();
if ($data_exists==1) echo "yes"; // NOTHING
?>
I have left the testing method in the code as well and I am keen to find a better solution to find out why the query does not show anything.
The aim would be to find the email address in the DB and give me some feedback about it. Thank you in advance all the comments I will only learn form them.
Additional info:
When I run the SQL query in the DB directly it does give me the record that has the same email.
Try the following and use prepared statements like protection from SQL injections.
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$email]);
$user = $stmt->fetch();
I am starting to use PDO and I successfully connected to MySQL using PDO. However, when I try to SELECT stuff from my DB, nothing happens. Nothing is echoed. (even though I have records in that table, and the column username exists) No error in my PHP log.
I am using MAMP and all PDO components seem to be working in phpinfo() (since I was able to connect to db in the first place)
Please let me know what could have gone wrong. Thanks a lot
<?php
try
{
$connection = new PDO('mysql:host=localhost;dbname:my_db','my_username',
'xxxxxxx');
$stmt=$connection->prepare("SELECT * FROM users");
$stmt->execute();
while ($row=$stmt->fetch(PDO::FETCH_OBJ)){
echo $row->username;
}
}
catch(Exception $e)
{
echo "There was an error connecting to the database";
}
?>
You need to tell PDO that you want it to throw exceptions:
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Following your comment below, it is apparent that your DSN is incorrect. It should be:
$connection = new PDO('mysql:host=localhost;dbname=my_db','my_username','xxxxxxx');
Note that the syntax is dbname= rather than dbname: (which you had originally).
First, get your query out of your PDO connection segment...
<?php
try
{
$connection = new PDO('mysql:host=localhost;dbname:my_db','my_username',
'xxxxxxx');
}
catch(Exception $e)
{
echo "There was an error connecting to the database";
}
?>
Then, do it.
<?php
$SQL = 'SELECT * FROM users';
foreach($connection->query($SQL) as $row){
print $row['username'] . "\n".'<br />';
}
?>
Why not ask PHP?
catch(Exception $e)
{
die($e);
}
Looks like your either don't have data in that table or have an error:
Try to add this code after $stmt->execute();:
$arr = $sth->errorInfo();
print_r($arr);
I have a problem with my database! Here is my code:
<?php
$host = "/homes/49/jc192699/public_html/dbase";
$database = "EduPro.db";
$dbhandle = new PDO("sqlite:".$host.$database);
if (!$dbhandle){
echo "Error connecting to database.\n";
}
else{
echo "<br>";
echo "<br>";
echo "Database connection successful!";
}
mysql_select_db($database);
?>
The problem is that it's saying "Database connection successful!" No matter what I do, if I type the address in wrong, it still says successful, when I renamed the database to a database that doesn't exist, it still says successful. I can't see what the problem is here?
If anybody could help me out it would be GREATLY appreciated!
Thank you!
For starters, the PDO constructor throws an exception if there is an error. It does not return false. Check for errors using
try {
$dbhandle = new PDO("sqlite:".$host.$database);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Secondly, as you are using SQLite, provided your dbase directory is writeable by the script, your connection attempt will create an empty database.
Try this:
<?php
try {
/*** connect to SQLite database ***/
$dbh = new PDO("sqlite:/path/to/database.sdb");
}
catch(PDOException $e)
{
/*** real error message prints here ***/
echo $e->getMessage();
}
?>
This is directly taken from here:
http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html#4.2