Retrieving and displaying data from MySql in PhP - php

I have ran into a problem that says:
Catchable fatal error: Object of class PDOStatement could not be converted to string in F:\University\xampp\htdocs\database.php on line 36
Connection to a database is successful it is just that I cannot retrieve a data from my database and display it on the page.
Here's my database:
http://screenshot.sh/m1Ol9a8Fp2j3a
And here is my code
<?php
$conn = new PDO(
'mysql:host=localhost;dbname=u1358595',
'root'
);
try{
$conn = new PDO('mysql:host=localhost;dbname=u1358595', 'root');
echo "Connected successfully";
}
catch (PDOException $exception)
{
echo "Oh no, there was a problem" . $exception->getMessage();
}
$query = "SELECT * FROM hotel";
$results = $conn->query($query, PDO::FETCH_OBJ);
$hotel = $results->fetch();
echo "<p>".$results."</p>";
$conn=NULL;
?>

You are trying to echo a PDO Object which doesn't work. You are passing the data to $hotel and to show the data you will use hotel.
<?php
$conn = new PDO(
'mysql:host=localhost;dbname=u1358595',
'root'
);
try{
$conn = new PDO('mysql:host=localhost;dbname=u1358595', 'root');
echo "Connected successfully";
}
catch (PDOException $exception)
{
echo "Oh no, there was a problem" . $exception->getMessage();
}
$query = "SELECT * FROM hotel";
$results = $conn->query($query);
$hotel = $results->fetch();
echo '<pre>';
var_dump($hotel);
echo '</pre>';
$conn=NULL;
?>

Related

PHP executes sql inside a false condition of IF statement with $_POST

Please help with this difficult to understand bug: php always execute sql update inside IF with $_POST in condition.
When condition is false: the code i) not executes the echo command, but ii) it still executes the sql command
if ($_POST["scanned_set"] != "saved") {
try {
$conn = new PDO("mysql:host=$servername;dbname=abc", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
// Update
$sql = "UPDATE `id_scan` SET `scan_count` = 10 WHERE `id_scan`.`id` = 1";
// use exec() because no results are returned
$conn->exec($sql);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$conn = null;
}
and the strange thing is that, if I try the iF condition with "IF (1 ==2)" then code works well. In other words, it does not execute the sql.
The full code
<html>
<body>
<?php
$servername = "localhost";
$username = "reviinve_vchain";
$password = "";
var_dump($_POST["scanned_set"]);
try {
$conn = new PDO("mysql:host=$servername;dbname=reviinve_vchain", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
// Retrieve data from db
$sql = "SELECT * FROM `id_scan` WHERE `id` = 1";
foreach ($conn->query($sql) as $row) {
echo "print scan number after retrieving statement ".$row['scan_count'] . "\t";
// print $row['color'] . "\t";
$count_update = $row['scan_count'] + 1;
}
}
catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
$conn = null;
if ($_POST["scanned_set"] != "saved") {
try {
$conn = new PDO("mysql:host=$servername;dbname=reviinve_vchain", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
// Update count number to db
echo 'new count number' . $count_update;
$sql = "UPDATE `id_scan` SET `scan_count` = $count_update WHERE `id_scan`.`id` = 1";
// use exec() because no results are returned
$conn->exec($sql);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$conn = null;
}
?>
</body>
</html>
Try scrubbing your request variable first:
$do_update = !(trim(strtolower($_REQUEST["scanned_set"])) == "saved")
if ($do_update) {
try {
$conn = new PDO("mysql:host=$servername;dbname=abc", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
// Update
$sql = "UPDATE `id_scan` SET `scan_count` = 10 WHERE `id_scan`.`id` = 1";
// use exec() because no results are returned
$conn->exec($sql);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$conn = null;
}

sent last id inserted variable to another page in php [duplicate]

This question already has answers here:
How to get last inserted inserted row id from PDO
(2 answers)
Closed 5 years ago.
in this code i have to insert some value in DB, then i have to take last id inserted in DB and sent it to another page to show the value of that id row. here is my code for insert data in DB :
try {
$con = new PDO("mysql:host=localhost;dbname=resume", "root", "");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql_basic = "INSERT INTO user_basic_info (first_name,last_name,address,profile_pic,resume_file)
VALUES ('$FirstName','$LastName','$Address','$pic_destination','$resume_destination')";
$con->exec($sql_basic);
$last_id = $con->$lastInsertId();
} catch (PDOException $e) {
echo $sql_basic . "<br>" . $e->getMessage() . "<br>";
}
$con = null;
header('Location: DB-Read.php?id=' . $last_id);
in another php page i have to take $last_id and use it. here is my code:
try {
$user_id = $id;
$conn = new PDO("mysql:host=localhost;dbname=resume", "root", "");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT first_name FROM user_basic_info where user_id = ".$user_id);
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
echo "this is username: " . $result;
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
header('Location: show-edit.php?id=' . $last_id);
first of all $lastInsertId() not working !!
after that, is my way true to take $last_id from first page ?
lastInsertId is a method of the PDO object. You need to call $conn->lastInsertId();.
Your given syntax $conn->$lastInsertId(); is valid, however, it does not do, what you are expecting. It considers $lastInsertId to be a variable containing the method name to be called. The following example would work as well:
$method_name = 'lastInsertId';
$conn->$method_name();
Be aware that your solution enables anyone to fetch any row of your table. Consider using sessions.
TRY THIS:
use session:
try {
$con = new PDO("mysql:host=localhost;dbname=resume", "root", "");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql_basic = "INSERT INTO user_basic_info (first_name,last_name,address,profile_pic,resume_file)
VALUES ('$FirstName','$LastName','$Address','$pic_destination','$resume_destination')";
$con->exec($sql_basic);
$_SESSION['id'] = $con->lastInsertId(); //it's a method
} catch (PDOException $e) {
echo $sql_basic . "<br>" . $e->getMessage() . "<br>";
$con = null;
header('Location: DB-Read.php?id=' . $last_id);
Now use this code
try {
$user_id = $_SESSION['id'];
$conn = new PDO("mysql:host=localhost;dbname=resume", "root", "");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT first_name FROM user_basic_info where user_id = ".$user_id);
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
echo "this is username: " . $result;
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
header('Location: show-edit.php?id=' . $last_id);

PDO MSSQL error query on null

I am trying to select rows from my database table, and I am getting an error stating that
Fatal error: Call to a member function query() on null in..
Our connection to the database shows successful. Below is my php code:
<?php
require_once("dbconn.php");
$db = getConnection();
$input_pid = "870104-07-5448";
$sql = "SELECT * FROM Pat WHERE PID ='$input_pid'";
$stmt = $db->query($sql);
$row = $stmt->fetchObject();
echo $row->PID;
echo $row->Name;
?>
This is the dbconn.php code:
function getConnection(){
try {
$hostname = "busctrlctr-pc";
$dbname = "DispenserSystem";
$username = "sa";
$password = "123456";
$db = new PDO ("sqlsrv:Server=$hostname;Database=$dbname", $username, $password);
echo 'We are succesful to connect the database !!'.'<br>'; // successful word
} catch (PDOException $e){
echo "connection failed problem is >> ". $e -> getMessage()."\n";
exit;
}
}
Can i know why I am getting this error. Thank you.
You never return $db in your funtion getConnection();
change the funtion to:
function getConnection(){
try {
$hostname = "busctrlctr-pc";
$dbname = "DispenserSystem";
$username = "sa";
$password = "123456";
$db = new PDO ("sqlsrv:Server=$hostname;Database=$dbname", $username, $password);
echo 'We are succesful to connect the database !!'.'<br>'; // successful word
return $db;
} catch (PDOException $e){
echo "connection failed problem is >> ". $e -> getMessage()."\n";
exit;
}
}

Changing from mysqli to PDO did not work?

I previously used mysqli and now i would like to use PDO instead but I did not echo any result from my database. I have read so many articles about PDO tutorial but they teach different things. I tried to pick piece by piece and came up with this code, but i did not echo any result from my database or throw any error.
try{
$stmt = $conn->query("SELECT * FROM memberpost ORDER BY poststart DESC LIMIT $start_from,$num_rec_per_page");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$row = $stmt->fetch();
if(count($row)>0){
while($row = $stmt->fetch()) {
echo $row['title']."<br>";
}
}
else{
echo "NO result found";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
Here is my database connect code:
try {
$conn = new PDO('mysql:host=localhost;dbname=mydatabase;charset=utf8', $username, $password); //new PDO
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
Edit your database connection code to this:
<?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();
}
?>
And try this code in your .php file :
$sth = $conn->prepare(SELECT * FROM memberpost)
$sth->execute();
$red = $sth->fetchAll();
print_r($red);
I found this on the internet, it might help:
// defining query
$sql = 'SELECT name, surname, zip FROM table';
// showing results
foreach($db->query($sql) as $row){
echo $row['name']. '<br>';
echo $row['surname']. '<br>';
echo $row['zip']. '<br>';
}
Source (ita): http://www.mrwebmaster.it/php/guida-utilizzo-pdo_7594_4.html

Want to delete a row from a table using php pdo

I want to delete a row from a table using php pdo.I am using the following code,
$dsn = 'mysql:host=127.0.0.1;dbname=as1';
$user = 'root';
$password = '';
try {
// Connect and create the PDO object
$pdo = new PDO($dsn, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo 'Database connection failed - ';
echo $e->getMessage();
exit;
}
$sql1="DELETE FROM photo WHERE id=?";
$q1=array($result);
try {
$stmt1 = $pdo->prepare($sql1);
$stmt1->execute($q1);
$stmt1->setFetchMode(PDO::FETCH_BOTH);
$result1= $stmt1->fetchColumn();
}
catch (PDOException $e) {
die("Failed to run query: " . $e->getMessage());
}
But my datas in a table are not deleting ...It shows failed to run query..
You did not provide a value for ?
$stmt1->execute($q); // Where is $q defined?
Should be something like
$q=array(1);
$stmt1->execute($q);

Categories