mysql_connect to PDO connection - php

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
}

Related

How to use new format

I have the following query, but this one is old. There should be a new way of writing the following code. Can anyone tell me how i should write this:
$get_test = mysql_query("select test from test_table where id = '1'");
$test = mysql_result($get_test, 0);
Ik would like to write it in: MYSQLI instead of mysql.
Maybe this is what you are looking for:
Mysqli:
<?php
$strSQL = "select test from test_table where id = '1'";
$query = mysqli_query($con, $strSQL);
while($result = mysqli_fetch_array($query))
{
echo $result["test"]."
";
}
?>
PDO:
<?php
$id = 1;
try {
#connection
$conn = new PDO('mysql:host=localhost;dbname=myDB', $db_username, $db_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data = $conn->prepare('SELECT test FROM test_table WHERE id = :id');
$data->execute(array('id' => $id));
while($rows = $data->fetch()) {
print_r($rows);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}?>
You should use PDO:
$db = new PDO("...");
$statement = $db->prepare("select test from test_table where id = :id");
$statement->execute(array(':id' => "test"));
$row = $statement->fetch();

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

nested if loop partially working

What I am trying to do is simply display the row values. Now suppose if the field 'head_office' dont have the value 'H.O' then I want to display the values of the last row. I tried but cant find any solution. Here is my code: (I have only blocked the php part)
<?php
$mysql_host = 'localhost';
$mysql_user = 'root';
$mysql_password = '123';
$mysql_database = 'sdbms';
$setup_page = './myinstitute.php';
$db = mysql_connect($mysql_host, $mysql_user, $mysql_password);
mysql_select_db($mysql_database, $db);
if(isset($_REQUEST['id'])){
$id=$_REQUEST['id'];
$sql = "SELECT * FROM institute WHERE id =$id";
$result = mysql_query($sql, $db);
$row = mysql_fetch_array($result);
}
else if(!isset($_REQUEST['id'])){
$sql = 'SELECT * FROM institute WHERE head_office ="H.O"';
$result = mysql_query($sql, $db);
$row = mysql_fetch_array($result);
}
else{
$sql="SELECT * FROM institute";
$result = mysql_query($sql, $db);
$n = mysql_num_rows($result); //counting number of rows
if($n==0){
header('Location: '.$setup_page);
}
else{
$sql = 'SELECT * FROM institute ORDER BY id DESC LIMIT 1';
$result = mysql_query($sql, $db);
$row = mysql_fetch_array($result);
}
}
?>
<?php
$mysql_host = 'localhost';
$mysql_user = 'root';
$mysql_password = '123';
$mysql_database = 'sdbms';
$setup_page = './myinstitute.php';
$db = mysql_connect($mysql_host, $mysql_user, $mysql_password);
mysql_select_db($mysql_database, $db);
$row = array();
if(isset($_REQUEST['id'])) {
$id = (int) $_REQUEST['id'];
if(!empty($id)) {
$sql = "SELECT * FROM institute WHERE id =$id";
$result = mysql_query($sql, $db);
$row = mysql_fetch_array($result);
}
} else {
$sql = 'SELECT * FROM institute WHERE head_office = "H.O"';
$result = mysql_query($sql, $db);
$row = mysql_fetch_array($result);
}
if(!isset($_REQUEST['id']) && empty($row))
$sql = "SELECT * FROM institute";
$result = mysql_query($sql, $db);
$n = mysql_num_rows($result); //counting number of rows
if($n == 0) {
header('Location: ' . $setup_page);
} else {
$sql = 'SELECT * FROM institute ORDER BY id DESC LIMIT 1';
$result = mysql_query($sql, $db);
$row = mysql_fetch_array($result);
}
}
?>
As $_REQUEST['id'] can only have 2 status, isset and !isset, the else statement will never be used.
I don't understand very well how do you want to do, but it's illogic: the three step don't execute ever. Try it:
if(isset($_REQUEST['id'])){
$id=$_REQUEST['id'];
$sql = "SELECT * FROM institute WHERE id =$id";
$result = mysql_query($sql, $db);
$row = mysql_fetch_array($result);
}
else if(!isset($_REQUEST['id'])){
$sql = 'SELECT * FROM institute WHERE head_office ="H.O"';
$result = mysql_query($sql, $db);
$row = mysql_fetch_array($result);
}
if(count($row)<=0) {
$sql="SELECT * FROM institute";
$result = mysql_query($sql, $db);
$n = mysql_num_rows($result); //counting number of rows
if($n==0){
header('Location: '.$setup_page);
}
else{
$sql = 'SELECT * FROM institute ORDER BY id DESC LIMIT 1';
$result = mysql_query($sql, $db);
$row = mysql_fetch_array($result);
}
}
Enjoy your code.

to retrieve a mysql data in php and echo the retrieved data

<?php
$username = "root";
$password = "password";
$database = "xxxxxx";
$link = mysql_connect("localhost", $username, $password);
$query = "SELECT rollno FROM users where username = '".$_SESSION['MM_Username']."'";
mysql_select_db('xxxxxx', $link);
$result = mysql_query($query) or die(mysql_error($link));
$num = mysql_num_rows($result);
mysql_close();
$rows = array();
$result = mysql_query($query) or die(mysql_error());
$rows = array();
while($r = mysql_fetch_row($result))
{
$rows[] = $r[0];
}
print_r($rows);
?>
This is my code i want to display the roll number of the currently logged in user and
when i run this code i get no database selected.
First of all, you should code properly, means database connection and database selection should be on top:
<?php
$username = "root";
$password = "password";
$database = "xxxx";
$link = mysql_connect("localhost", $username, $password);
mysql_select_db('xxxx', $link);
$query = "SELECT rollno FROM users where username = '".$_SESSION['MM_Username']."'";
$result = mysql_query($query) or die(mysql_error($link));
$num = mysql_num_rows($result);
$rows = array();
$result = mysql_query($query) or die(mysql_error());
$rows = array();
while($r = mysql_fetch_row($result))
{
$rows[] = $r[0];
}
print_r($rows);
mysql_close();
?>
Also moved mysql_close(); on last
One other main point was, now mysql_ is deprecated, please use mysqli_
Remove this statement from line number 10
mysql_close();
just remove these two lines before while that will solve ur problem
$result = mysql_query($query) or die(mysql_error());
$rows = array();
Use this code and use mysql_close function in the last.
<?php
$username = "root";
$password = "password";
$database = "xxxxxx";
$link = mysql_connect("localhost", $username, $password);
$query = "SELECT rollno FROM users where username = '".$_SESSION['MM_Username']."'";
mysql_select_db($database, $link);
$result = mysql_query($query) or die(mysql_error($link));
$num = mysql_num_rows($result);
$rows = array();
$result = mysql_query($query) or die(mysql_error());
$rows = array();
while($r = mysql_fetch_row($result))
{
$rows[] = $r[0];
}
print_r($rows);
mysql_close();
?>
You have closed the connection from MySQL before the mysql_query mysql_close();
try this
<?php
$username = "root";
$password = "password";
$database = "dfsdftwsdgdfgdfsgsdf";
$link = mysql_connect("localhost", $username, $password);
$query = "SELECT rollno FROM users where username = '".$_SESSION['MM_Username']."'";
mysql_select_db('xxxxxxx', $link);
$result = mysql_query($query) or die(mysql_error($link));
$num = mysql_num_rows($result);
$rows = array();
$result = mysql_query($query) or die(mysql_error());
$rows = array();
while($r = mysql_fetch_row($result))
{
$rows[] = $r[0];
}
mysql_close();
print_r($rows);
?>
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
The order should be like this
mysql_select_db('meipolytechnic', $link);
$query = "SELECT rollno FROM users where username = '".$_SESSION['MM_Username']."'";
mysql_select_db('meipolytechnic', $link);

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

Categories