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();
Related
I've got a website that is pulling data from my MSSQL Server. I am using functions to build tables for reports. Here's what I've got:
function BeginTable($rowCount,$headings,$searchValue,$ReportName,$OneButton,$NewSearch)
{
try{
$StateSelectSQL = "select distinct State from pmdb.MaterialTracking where State is not null";
var_dump($StateSelectSQL);echo " What!<br>";
$getSelect = $conn->query($StateSelectSQL);
var_dump($getSelect);echo " When!<br>";
$StateSelectNames = $getSelect->fetchALL(PDO::FETCH_ASSOC);
var_dump($StateSelectNames);echo " Where!<br>";
}
catch(Exception $e)
{
echo "Something went wrong";
die(print_r($e->getMessage()));
}
I tried this too:
try{
$StateSelectSQL = "select distinct State from pmdb.MaterialTracking where State is not null";
var_dump($StateSelectSQL);echo " What!<br>";
$getSelect = $conn->prepare($StateSelectSQL);
$getSelect->execute();
//$getSelect = $conn->query($StateSelectSQL);
//var_dump($getSelect);echo " When!<br>";
$StateSelectNames = $getSelect->fetchALL(PDO::FETCH_ASSOC);
var_dump($StateSelectNames);echo " Where!<br>";
}
catch(Exception $e)
{
echo "Something went wrong<br>";
die( print_r( $e->getMessage()));
}
The second and third var_dump's never show anything and the rest of the code (not shown here) doesn't get run. If I comment out the $getSelect and $StateSelectNames lines (with the var_dump's under them) then everything else works.
Here is my DBConn.php file that is included above the Function:
$conn = new PDO("sqlsrv:server=$servername;database=$dbname", $username,$password);
//set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::SQLSRV_ATTR_QUERY_TIMEOUT, 10);
What is wrong with the line $getSelect = $conn->query($StateSelectSQL); I can't figure it out. I tried using it later in my foreach like this:
foreach($conn->query($StateSelectSQL) as $StateName)
But that doesn't work either. It again stops at this line and doesn't go any further. The only thing I can think of is that my SQL is messed up, but when I run it in SSMS it works fine!
What's going on?
Try preparing and executing your SQL before using fetchAll. Also consider enabling exception mode if you haven't already and wrapping your statement in a try catch - this should flag any issues (e.g. your applications database user not having permission to access the schema, or syntax error etc)
Exceptions:
See this stack overflow post for info about how to enable
And for your code:
try {
$sql = "
SELECT DISTINCT State
FROM pmdb.MaterialTracking
WHERE State IS NOT NULL
";
$sth = $conn->prepare($sql);
$sth->execute();
$rowset = $sth->fetchAll(PDO::FETCH_ASSOC);
print_r($rowset);
} catch PDOException($err) {
echo "Something went wrong".
echo $err;
}
I have figured it out after pulling my hair out all day! I had to include my DBConn.php inside the function. After this it worked. I don't know why that mattered since it is included at the beginning of the file. If there is anyone who can explain why that is i'd be grateful!
It now looks like this:
function BeginTable($rowCount,$headings,$searchValue,$ReportName,$OneButton,$NewSearch)
{
try{
include("DBConn.php");
$SelectSQL = "select distinct State from pmdb.MaterialTracking where State is not null order by State";
$getSelect = $conn->prepare($SelectSQL);
$getSelect->execute();
$StateSelectNames = $getSelect->fetchALL(PDO::FETCH_ASSOC);
}
catch(Exception $e)
{
echo "Something went wrong<br>";
die( print_r( $e->getMessage()));
}
I am trying to connect to MYSQL using php, but when I use the following command:
$link=mysql_connect("localhost","root","password");
and echo $link, it gives me Resource id #98. What does this mean? Am I not connected?
Okay, I guess it sounds like the connection is okay. Now, with the following code, I am not seeing any changes in the mysql database. Why could that be?
<?php
$conn=new mysqli("localhost","root","password","database");
$sql="INSERT INTO chat_active (user, time)
VALUES('John', '1234')";
?>
What makes you think you are not connected?
According to the docs, mysql_connect()
[r]eturns a MySQL link identifier on success or FALSE on failure.
Since it did not return FALSE, but rather a resource identifier, that means the connection was successful.
Also note that the mysql extension is deprecated since PHP 5.5.0 as MortimerCat pointed out. Instead you should look into the MySQLi or the PDO extension.
"Now, with the following code, I am not seeing any changes in the mysql database. Why could that be?"
As per your edit which you are now using mysqli_ to connect with, and that you're saying that you're not seeing any changes in your database, is because:
You're not passing the DB connection to your query and it is required when using mysqli_.
Rewrite, with a few more goodies:
<?php
$conn=new mysqli("localhost","root","password","database");
// Check if you've any errors when trying to access DB
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
$sql="INSERT INTO chat_active (user, time) VALUES ('John', '1234')";
$result = $conn->query($sql);
// Check if you've any errors when trying to enter data in DB
if (!$result)
{
throw new Exception($conn->error);
}
else{
echo "Success";
}
Read the manual http://php.net/manual/en/mysqli.query.php
Once you've grasped that, get to know mysqli with prepared statements, or PDO with prepared statements, they're much safer.
References:
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/language.exceptions.php
Footnotes:
Your column names user, time suggests that you're trying to enter a string and what appears to be and to be intended as "time" and that the user column is set to varchar.
Make sure that you haven't setup your time column other than a datetime-related type, otherwise MySQL may complain about that.
MySQL stores dates as YYYY-mm-dd as an example.
Visit https://dev.mysql.com/doc/refman/5.0/en/datetime.html in regards to different date/time functions you can use.
MySQL references:
https://dev.mysql.com/doc/refman/5.0/en/char.html
https://dev.mysql.com/doc/refman/5.0/en/data-types.html
https://dev.mysql.com/doc/refman/5.0/en/datetime.html
You yould use mysqli or PDO.
Here's a connection example with PDO:
<?php
$dbuser = 'user';
$dbpasswd = 'passwd';
$dbname = 'dbname';
try {
$gbd = new PDO("mysql:host=localhost;dbname=$dbname;charset=utf8", $dbuser, $dbpasswd);
$gbd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
}
PDO CRUD examples:
//INSERT
try {
$sentence = $gbd->prepare("INSERT INTO table (param1, param2) VALUES (:param1, :param2)");
$sentence->bindParam(':param1', $param1);
$sentence->bindParam(':param2', $param2);
$sentence->execute();
}
catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}
//SELECT
try {
$sentence = $gbd->prepare("SELECT param1,param2 FROM table WHERE param1 = :param1 AND param2 = :param2)");
$sentence->bindParam(':param1', $param1);
$sentence->bindParam(':param2', $param2);
$sentence->execute();
while ($row = $sentence->fetch(PDO::FETCH_ASSOC)){ //Also available FETCH_NUM,FETCH_BOTH AND OTHERS
$result['param1'] = $row['param1'];
$result['param2'] = $row['param2'];
}
}
catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}
//UPDATE
try {
$sentence = $gbd->prepare("UPDATE table SET param1 = :param1, param2 = :param2)");
$sentence->bindParam(':param1', $param1);
$sentence->bindParam(':param2', $param2);
$sentence->execute();
}
catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}
//DELETE
try {
$sentence = $gbd->prepare("DELETE table WHERE param1 = :param1 AND param2 = :param2)");
$sentence->bindParam(':param1', $param1);
$sentence->bindParam(':param2', $param2);
$sentence->execute();
}
catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}
And here's PDO manual
http://php.net/manual/en/book.pdo.php
u are not executing that query.u are only declaring that query.
for execution do--
$conn->query($qry);
it will,execute ur query.
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
}
?>
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);
Can anyone spot where I might be going wrong with the following code?
<?php
//MySQL Database Connect
require 'config.php';
$unitFrom = "kilogram";
$unitTo = "gram";
$units = "9000";
try{
require 'config.php';
$stmt = $dbh->prepare('CALL sp_get_conversion(:in_unit_from, :in_unit_to, :in_amount, #out_amount)');
$stmt->bindParam(':in_unit_from',$unitFrom,PDO::PARAM_STR,4000);
$stmt->bindParam(':in_unit_to',$unitTo,PDO::PARAM_STR,4000);
$stmt->bindParam(':in_amount',$units,PDO::PARAM_STR,4000);
$stmt->execute();
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
$conversion = $dbh->query( "SELECT #out_amount" )->fetchColumn();
echo $conversion;
}
?>
When I run the stored procedure in phpmyadmin it works fine but nothing is echoed out when I try the code above.
Thanks
The following should be in the try block:
$conversion = $dbh->query( "SELECT #out_amount" )->fetchColumn();
echo $conversion;
You currently have it in the catch block so it will get executed only if there is an exception is generated.
Try handling your error as dictated here. It's how I've always worked with PDO issues.