mysql to pdo JSON for ios - php

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);

Related

Can't select data with PDO

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";
}
?>

android - php fetch mysql data by user id

This my PHP URL for fetching the data from MySQL. I need to make mysqli_fetch_array code saying if filled uid in the app-data table is the same with uid in users table fetch the data from all row in app-data to the uid like every user show his items from app-data table.
$host = "";
$user = "";
$pwd = "";
$db = "";
$con = mysqli_connect($host, $user, $pwd, $db);
if(mysqli_connect_errno($con)) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
$sql = "SELECT * FROM app_data ORDER By id";
$result = mysqli_query($con, $sql);
$rows = array();
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$rows[] = $row;
}
mysqli_close($con);
echo json_encode($rows);
I think this is the correct answer:
<?php
$host = "";
$user = "";
$pwd = "";
$db = "";
$con = mysqli_connect($host, $user, $pwd, $db);
if(mysqli_connect_errno($con)) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
$sql = "SELECT * FROM app_data WHERE u_id=".$_POST['posted_uid']." ORDER By id";
$result = mysqli_query($con, $sql);
$rows = array();
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$rows[] = $row;
}
mysqli_close($con);
echo json_encode($rows);
Little tip for the future:
Don't search exactly what you want, only search in parts.

php switching to mysqli: num_rows issue

I recently started updating some code to MySQL improved extension, and have been successful up until this point:
// old code - works
$result = mysql_query($sql);
if(mysql_num_rows($result) == 1){
$row = mysql_fetch_array($result);
echo $row['data'];
}
// new code - doesn't work
$result = $mysqli->query($sql) or trigger_error($mysqli->error." [$sql]");
if($result->num_rows == 1) {
$row = $result->fetch_array();
echo $row['data'];
}
As shown I am trying to use the object oriented style.
I get no mysqli error, and vardump says no data... but there definitely is data in the db table.
Try this:
<?php
// procedural style
$host = "host";
$user = "user";
$password = "password";
$database = "db";
$link = mysqli_connect($host, $user, $password, $database);
IF(!$link){
echo ('unable to connect to database');
}
ELSE {
$sql = "SELECT * FROM data_table LIMIT 1";
$result = mysqli_query($link,$sql);
if(mysqli_num_rows($result) == 1){
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
echo $row['data'];
}
}
mysqli_close($link);
// OOP style
$mysqli = new mysqli($host,$user, $password, $database);
$sql = "SELECT * FROM data_table LIMIT 1";
$result = $mysqli->query($sql) or trigger_error($mysqli->error." [$sql]"); /* I have added the suggestion from Your Common Sence */
if($result->num_rows == 1) {
$row = $result->fetch_array();
echo $row['data'];
}
$mysqli->close() ;
// In the OOP style if you want more than one row. Or if you query contains more rows.
$mysqli = new mysqli($host,$user, $password, $database);
$sql = "SELECT * FROM data_table";
$result = $mysqli->query($sql) or trigger_error($mysqli->error." [$sql]"); /* I have added the suggestion from Your Common Sence */
while($row = $result->fetch_array()) {
echo $row['data']."<br>";
}
$mysqli->close() ;
?>
As it was said, you're not checking for the errors.
Run all your queries this way
$result = $mysqli->query($sql) or trigger_error($mysqli->error." [$sql]");
if no errors displayed and var dumps are saying no data - then the answer is simple: your query returned no data. Check query and data in the table.
In PHP v 5.2 mysqli::num_rows is not set before fetching data rows from the query result:
$mysqli = new mysqli($host,$user, $password, $database);
if ($mysqli->connect_errno) {
trigger_error(sprintf(
'Cannot connect to database. Error %s (%s)',
$mysqli->connect_error,
$mysqli->connect_errno
));
}
$sql = "SELECT * FROM data_table";
$result = $mysqli->query($sql);
// a SELECT query will generate a mysqli_result
if ($result instanceof mysqli_result) {
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
$num_rows = $result->num_rows; // or just count($rows);
$result->close();
// do something with $rows and $num_rows
} else {
//$result will be a boolean
}
$mysqli->close() ;

mysql_connect to PDO connection

I've been trying to convert a mysql_connect connection into a PDO connection with no success, here is what I have:
$host = 'localhost';
$user = 'root';
$pwd = '';
$db = 'jdlferreira';
$connection = mysql_connect($host, $user, $pwd) or die("Could not connect");
mysql_select_db($db) or die("Could not select database");
$query = "SELECT COUNT(*) FROM blog";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_fetch_row($result);
$pages = new Paginator;
$pages->items_total = $num_rows[0];
$pages->mid_range = 9; // Number of pages to display. Must be odd and > 3
$pages->paginate();
$query = "SELECT id, title, resume, date
FROM blog
ORDER BY date DESC $pages->limit";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_row($result)) {
//do stuff
}
And what I tried to do with PDO:
include_once 'inc/db.inc.php';
$db = new PDO(DB_INFO, DB_USER, DB_PASS);
mysql_select_db("jdlferreira") or die("Could not select database");
$query = "SELECT COUNT(*) FROM blog";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_fetch_row($result);
$pages = new Paginator;
$pages->items_total = $num_rows[0];
$pages->mid_range = 9; // Number of pages to display. Must be odd and > 3
$pages->paginate();
$query = "SELECT id, title, resume, date
FROM blog
ORDER BY date DESC $pages->limit";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_row($result)) {
//do stuff
}
I'm getting a "Could not select database" error, I don't really care for the 'or die' cases, I would just like to make this connection functional on PDO, any help would be great.
You cant use PDO and then exepect to use mysql_* functions they arent related.
Theres no need to select a db like that with pdo because its included in the DSN which is the contructors first argument:
$db = new PDO('mysql:host=localhost;dbname=jdlferreira', DB_USER, DB_PASS);
Then you need to use the PDO interface to interact with the DB, not the mysql ones:
$stmt = $db->prepare("SELECT COUNT(*) FROM blog");
$stmt->execute();
$num_rows = $stmt->fetchColumn();
$stmt->closeCursor();
$pages = new Paginator;
$pages->items_total = $num_rows;
$pages->mid_range = 9; // Number of pages to display. Must be odd and > 3
$pages->paginate();
$query = "SELECT id, title, resume, date
FROM blog
ORDER BY date DESC $pages->limit";
$stmt = $db->prepare($query);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// do stuff
}

How to get rows of a specific type matching a specific value?

I want to get data from a table in my MySQL database.
$linkID = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $linkID) or die("Could not find database.");
$search='flu';
$query = mysql_query("SELECT * From ProviderDxCptCodes WHERE CodeType='CPT'");
$rows = array();
while($row = mysql_fetch_assoc($query)) {
$rows[] = $row;
}
echo json_encode($rows);
I want this query to show me all CPT codes matching the search string flu. How can I do that?
Do you mean something like that?
SELECT * From ProviderDxCptCodes WHERE CodeType='CPT' AND name LIKE '%flu%';
$linkID = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $linkID) or die("Could not find database.");
$flu = "CPT";
$query = mysql_query("SELECT * From ProviderDxCptCodes WHERE CodeType='%".mysql_real_escape_string($flu)."%'");
$rows = array();
while($row = mysql_fetch_assoc($query)) {
$rows[] = $row;
}
echo json_encode($rows);

Categories