Can't select data with PDO - php

I want to select data (at all) with PDO (always used mysqli) from an external database. It connects, and the query works on the server directly with mysql. With php, it doesn't. Here's my code:
<?php
$hostname = 'localhost';
$username = 'user';
$password = 'pass';
function testdb_connect ($hostname, $username, $password){
$dbh = new PDO("mysql:host=$hostname;dbname=database", $username, $password);
return $dbh;
}
try {
$dbh = testdb_connect ($hostname, $username, $password);
echo 'Connected to database';
} catch(PDOException $e) {
echo $e->getMessage();
}
$sql= "select * from table limit 10;";
echo "<br/>";
echo $sql;
$stmt = $pdo->prepare($sql);
$stmt->execute();
$row = $stmt->fetchObject();
echo $row->id;
It shows "connected to database", and the "echo $sql" part, but doesn't display any information.

Your first part of the question have been solved.
now this
I now want to print the 10 rows instead of just the first one. How do
I do it?
The are many ways you can do that, but you need to loop through your results and display the desired Rows
Option 1
$sql = $dbh->query("SELECT * from table limit 10")->fetchall(PDO::FETCH_ASSOC);
foreach($sql as $row){
// print_r($row); // see them all
echo $row['desiredRow']; //print them one by one
}
Option 2
$sql = $dbh->query("SELECT * from table limit 10");
while($row=$sql->fetch()){
// print_r($row);
echo $row['desiredRow'];
}
Option 3
<?php
$sql = "SELECT * from table limit 10";
$stmt = $dbh->prepare($sql);
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if(count($results) > 0){//check results
foreach($results as $row){
print_r($row);
}
}else{
echo "no results found";
}
?>

Related

need the result of mysqli query as a json array from this phpscript

this is my php script
$con = mysqli_connect(HOST,USER,PASS,DB);
if($_SERVER['REQUEST_METHOD']=='GET')
{
$qry_check="SELECT * FROM `tb_user`";
$stmt = $con->prepare($qry_check);
if ($stmt->execute()){
echo "Success";
}}
else
echo "Fail";
}
?>
when i run this query on my mysqli online server i get result which i have attached below i need this result as a json array when i call this json url, hanks in advance,enter image description here
enter image description here
try this
<?php
$con = mysqli_connect(HOST,USER,PASS,DB);
if($_SERVER['REQUEST_METHOD']=='GET')
{
$stmt = $con->prepare("SELECT * FROM tb_user");
if ($stmt->execute()) {
$users = array();
$user=$stmt->get_result();
while($row = $user->fetch_assoc()){
$users[]=$row;
}
$stmt->close();
echo json_encode($users);
}
}
?>
or use this code. Add your remaining columns in this code for full result
<?php
$con = mysqli_connect(HOST,USER,PASS,DB);
if($_SERVER['REQUEST_METHOD']=='GET')
{
$stmt = $con->prepare("SELECT user_id, category_id FROM tb_user");
if ($stmt->execute()) {
$users = array();
$stmt->bind_result($user_id, $category_id);
while ($stmt->fetch()) {
$user["user_id"] = $user_id;
$user["category_id"] = $category_id;
$users[] = $user;
}
$stmt->close();
echo json_encode($users);
}
}
?>
I already mention in comment that mysqli != PDO. But I thnk you don't get it.
You are initializing connection with mysqli then doing all process with PDO so you don't get result
<?php
$servername = HOST;
$username = USER;
$password = PASS;
$dbname = DB;
$con = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
if($_SERVER['REQUEST_METHOD']=='GET')
{
$stmt = $con->prepare("SELECT * FROM tb_user");
if ($stmt->execute())
{
$users = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$users[]=$row;
}
$stmt->close();
echo json_encode($users);
}
}
?>

Simple PHP MYSQL select statement doesn't return anything

Alright, so I have a simple database with one table, and I have a function which is supposed to get all the rows for that one table:
function get_days() {
global $db;
$query = 'SELECT * FROM days'
. 'ORDER BY idDays';
$statement = $db ->prepare($query);
$statement ->execute();
$the_days = $statement->fetchAll();
//$statement->closeCursor();
return $the_days;
//return $statement;
}
I've checked everything else, everything else functions just fine, including the part of my site where I input data into the table, that insert statement works just fine, so I've narrowed it down to this one select statement.
The problem is in you SQL syntax. You should do this:
function get_days() {
global $db;
$query = 'SELECT * FROM days '
. 'ORDER BY id';
$statement = $db ->prepare($query);
$statement ->execute();
$the_days = $statement->fetchAll();
//$statement->closeCursor();
return $the_days;
//return $statement;
}
The problem is the string concatenation of your query:
$query = 'SELECT * FROM days' . 'ORDER BY idDays';
This results in: SELECT * FROM daysORDER BY idDays
Include a space character instead:
$query = 'SELECT * FROM days' . ' ORDER BY idDays';
You can avoid problems like this with proper error handling:
try{
$statement->execute();
}
catch(PDOException $e){
exit($e->getMessage());
}
You might also want to remove the spaces in:
$db ->prepare($query);
$statement ->execute();
So they become:
$db->prepare($query);
$statement->execute();
This is simple way to select you can use a function for it.
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM days ORDER BY idDays";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//do anything
}
} else {
echo "0 results";
}

How do I reconnect my web pages on my website after updating to PHP 7 with a MySQL database 5.0.0?<?

I added the i updates to communicate with the database & now the page links don't work.
<?php
// Connect to database
$link=mysqli_connect('localhost', 'xxxxx', 'xxxxx');
mysqli_select_db($link, 'waddellc_PHRDB');
$sql = "SELECT * FROM quotes ORDER BY id";
$result = mysqli_query($link, $sql) or die(mysql_error());
$tenant_quotes = array();
$owner_quotes = array();
while($row = mysqli_fetch_array($result)) {
This should do the work, using PDO :
$servername = "localhost";
$username = "username";
$password = "password123";
$conn = null;
try {
$conn = new PDO("mysql:host=$servername;dbname=databaseName", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
if(!is_null($conn)){
$stmt = $conn->prepare("SELECT * FROM quotes ORDER BY id");
if ($stmt->execute()) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
}
I also think you need to update your database, it's quite old now.

How to get count using prepared statment in PHP?

$con = mysqli_connect("localhost","root","","uploads");
if($con)
{
$sql = "SELECT COUNT(id) FROM products";
$obj = mysqli_query($con,$sql);
if(is_object($obj))
{
$rows = mysqli_fetch_row($obj);
$totalrows = $rows[0];
enter code here
}else{
echo "not object";
}
}else
{
echo "db issue";
}
This code is perfectly fine but i want to perform same operation using prepared statment.i have tried but could't get the same result using prepared statment. what i have to do?
Check out the following solutions
//db configuration
$server = 'localhost';
$dataBase = 'uploads';
$UserName = 'root';
$Password = '';
PHP MySQLi Prepared Statement
$con = mysqli_connect($server, $userName, $password, $dataBase);
$sql = "SELECT COUNT(id) FROM products";
$stmt = mysqli_prepare($con, $sql);
if(mysqli_stmt_execute($stmt)) {
mysqli_stmt_bind_result($stmt, $totalRows);
mysqli_stmt_fetch($stmt);
echo $totalRows;
}
PHP MySQLi Object-oriented
$con = new mysqli($server, $userName, $password, $dataBase);
$stmt = $con->query("SELECT COUNT(id) FROM products");
if ($stmt->num_rows > 0) {
while($row = $stmt->fetch_row()) {
$totalRows = $row[0];
echo 'Total number of rows is '.$totalRows;
}
}
$stmt->close();
PHP MySQLi with Object-oriented Prepared Statement
$con = new mysqli($server, $userName, $password, $dataBase);
$stmt = $con->prepare("SELECT COUNT(id) FROM products");
$stmt->execute();
$stmt->bind_result($totalRows);
$stmt->fetch();
echo 'Total number of rows is '.$totalRows;
$stmt->close();
PHP PDO with Prepared Statement
try {
$con = new PDO("mysql:host=$server;dbname=$dataBase;", $userName, $password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $con->prepare("SELECT COUNT(id) FROM products");
$stmt->execute();
$totalRows = $stmt->fetchColumn();
echo 'Total number of rows is '.$totalRows;
} catch(PDOException $e){
echo $e->getMessage();
die();
}

mysql to pdo JSON for ios

I'm trying to convert this mysql code into PDO code, yet I can only return one of my rows in JSON whereas the mysql code allows me all the rows.
$connection = mysql_connect($host, $user, $pass);
//Check to see if we can connect to the server
if(!$connection)
{
die("Database server connection failed.");
}
else
{
//Attempt to select the database
$dbconnect = mysql_select_db($db, $connection);
//Check to see if we could select the database
if(!$dbconnect)
{
die("Unable to connect to the specified database!");
}
else
{
$query = "SELECT * FROM questions ORDER BY RAND() LIMIT 40";
$resultset = mysql_query($query, $connection);
$records = array();
//Loop through all our records and add them to our array
while($r = mysql_fetch_assoc($resultset))
{
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
}
}
And here is the PDO code I've got to so far
$db = new PDO('mysql:host=***;dbname=***', $user, $pass);
$query = "SELECT * FROM questions ORDER BY RAND() LIMIT 40";
$stmt = $db->prepare($query);
$stmt->execute();
$records = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$records = $row;
}
echo json_encode($records);
It looks like I have to fill some more of this post out with random gobldygook as it seems I haven't already gotten to the point.
forgot to push each row into records, therefore
$records[] = $row;
or use fetchAll()
$db = new PDO('mysql:host=***;dbname=***', $user, $pass);
$query = "SELECT * FROM questions ORDER BY RAND() LIMIT 40";
$stmt = $db->prepare($query);
$stmt->execute();
$records = $stmt->fetchAll(PDO::FETCH_ASSOC); // to get all records at once
echo json_encode($records);

Categories