PDO syntax whit querys - php

hi im starting to use PDO for sqlite and I want to know how to do something similar like:
$result = **sqlite_query**($conection,$consulta);
for example something similar to $conection = sqlite_open('../db/traductor.db');
would be--->$conection = new PDO('sqlite:../db/traductor.db');
hope you can understand my question, and thanks

As you've been pointed, the PHP PDO manual page will tell you where to look for, but I'll save you a couple of minutes.
In procedural MySQL, you would connect to your database with:
$link = mysql_connect("localhost", "user", "password");
mysql_select_db("database", $link);
And fire your queries like:
$query = mysql_query("SELECT * FROM `products` ORDER BY `product_id` ASC;", $link);
In PDO, it's a bit different:
$pdo = new PDO("mysql:host=localhost;dbname=database;charset=utf8", "user", "password");
And you fire your queries (in a direct fashion) like this:
$pdo->query("SELECT * FROM `products` ORDER BY `product_id` ASC;");
But the power of PDO lies within prepared statements
$statement = $pdo->prepare("SELECT * FROM `products` WHERE `price` > ? ORDER BY `product_id` ASC;");
$statement->execute([27.75]);
Take your time and read the PDO manual page and as many tutorials on the web as you can. It's more difficult to work with PDO in the beginning but, once you learn, you won't want to work with anything less (not to mention you can link with MySQL, SQL Server, Oracle, PostgreSQL, MongoDB and many other databases using the same structure, among other advantages).
Hope that helped ;)

Related

Issue migrating mysql to mysqli

I have a legacy php project that I need to convert from mysql to mysqli.
The conversion seems quite straight forward except for one part.
In mysql the following code seems to work well:
$query = "select c.id from contact c";
$queryResult = mysql_query($query);
$result = mysql_result($queryResult,0,"c.id");
I am translating the code to:
$connection = new mysqli(...)
$queryResult = $connection->query($query);
$queryResult->data_seek(0);
$result_row = $queryResult->fetch_assoc();
$result = $result_row["c.id"];
However it seems that in mysqli "c.id" is not valid. I need to use "id".
I been looking at mysql to mysqli conversion posts but I haven't seen any solution to this particular issue. I know I can update the query to use something like
"select c.id as cid from contacts"
However there are hundreds of queries that I need to manually convert so I was wondering if there is any easy way of getting the "c.id" part to work with mysqli.
Thanks.

The difference between PDO sql statements and regular sql?

I've learned PHP from a book and its told me to use PDO objects or sql statements (I'm not sure if that's the right terminology, I apologize if it's not).
When I look up sql stuff, a lot of the times I see stuff like this:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db('database_name')) {
die('Could not select database: ' . mysql_error());
}
$result = mysql_query('SELECT name FROM work.employee');
But in my code and in the book, I'm doing stuff like this:
global $db;
$query = "SELECT * FROM users WHERE username='$username'";
$results = $db->query($query);
$results = $results->fetch();
What's the difference between these two 'styles'?
First the function those are mysql_* (like mysql_query, mysql_connect etc) are deprecated and will not be supported in PHP future versions. So PDO or Mysqli are preferred way of communication with database.
The PDO 's prepared statements are used for avoiding SQL injection attacks. like in normal mysql_query you will use like this
$query = "SELECT * FROM users WHERE username='$username'";
$results = mysql_query($query);
but in PDO you have to use like this
$params = array(':username' => 'test', ':email' => $mail);
$pdo->prepare('
SELECT * FROM users
WHERE username = :username
AND email = :email');
$pdo->execute($params);
So PDO is recommended way. For more detail you can refer to
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
http://php.net/pdo
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
The first style was written long ago, or was written by people who stopped learning PHP before PHP5 came out. mysql_query is deprecated, and has been for a while now, and you should never be using it in a new project.
The second is using PDO, one of the newer database APIs. PDO supports a bunch of things that make working with SQL easier.
It's still pretty hideous as written, though. Most people would recommend using parameterized queries (a form of prepared statements) to separate the data from the SQL. This helps prevent "SQL injection", a process by which someone feeds you data that tricks your database into executing queries you never intended for it to.

How can I connect to two databases

i am trying to connect to two databases to create a search engine for a couple of my databases. Heres a test code. can someone tell me what i am doing wrong or if it is possible. thanks.
mysql_connect("localhost","user","pass");
mysql_select_db("db1");
mysql_select_db("db2");
$search=mysql_query("SELECT * from db1.repairs, db2.order from db1,db2");
while($row=mysql_fetch_array($search)){
echo $row['first_name']." ".$row['esn']." ".$row['order_type']."<br>";
}
You can query across databases if you specify the database name before the table name like this
SELECT a.col1, b.col2
FROM db1.table1 AS a
INNER JOIN db2.table2 AS b ON a.someIdFromA = b.someIdFromB
As Korcholis mentions the problem is in your select. Also you do not want to use the mysql_* functions if you can avoid it. PDO or MySqli are preferred.
Edit
At least this works using MySQL. I would bet it works for most other RDBMSes as well, but I don't have others handy to test and I can't say if this conforms to SQL standards or not. Comments anyone?
You can use
<?php
$db1 = mysql_connect("localhost","user","pass");
$db2 = mysql_connect("remote","user","pass");
mysql_select_db("db1", $db1);
mysql_select_db("db1", $db2);
$query1 = mysql_query("USE somedatabase", $db1);
$query2 = mysql_query("USE otherdatabase", $db2);
Or try with a class that handles these connections in a different instances
http://www.joni2back.com.ar/programacion/php-class-for-mysql-databases/
mysql_connect returns a $resource. You can connect twice and select a database with each one (in fact, you can select a database from the connect itself), and then use each connection.
However, your problem is that your SELECT is incorrect. You are trying to select fields from tables from databases, which is not correct. In fact, you cannot fetch two different databases in a so fancy way, because they are considered two sets of information independent and unrelated between them. That's why tables exist, to fit that problem.
This other answer, however, may have a solution.
Otherwise, you could connect to each database using two mysql_connect and two resources, fetch the values, and cross them yourself. Not the best option, I know, but an answer that could fit your needs.
PS: If you are beginning the project right now, switch to Mysqli or PDO. Mysql is deprecated.
Try to review this, and maybe you can't query a database with querying FROM:
<?php
$con1 = mysqli_connect("$hostname", "$user1", "$password1", "$db1");
if (mysqli_connect_errno($con1)) {
echo mysqli_connect_error();
}
$con2 = mysqli_connect("$hostname", "$user2", "$password2", "$db2");
if (mysqli_connect_errno($con2)) {
echo mysqli_connect_error();
}
$search1 = mysqli_query($con1, "SELECT * from $db1table");
$search2 = mysqli_query($con2, "SELECT * from $db2table");
/* Other PHP codes here */
mysqli_close($con1);
mysqli_close($con2);
?>
You can even improve this code, nor minimized it!

Switch between multiple database in PDO

I'm new to PDO. I would like to know if there is anything similar to mysql_select_db in PDO, so that i can switch between different databases during runtime without the need for creating a new object.
I know that I am a couple of months late but you should be able to switch between databases from within your query.
examples:
$sql = "SELECT * FROM dbname.tablename";
$sql = "SELECT * FROM anotherdbname.anothertablename"
So even if your original $pdo object was used 'blahblah' as the dbname, you should still be okay based on the select examples I provided.
It looks like PDO does not have database switching because not every database engine supports it.
AFAIK PostgreSQL does not have database switching, but offer schemas and u can switch between those.
However if you're using mysql check if this works for you:
$pdo = new PDO('mysql:dbname=db1;host=127.0.0.1','user','pass');
$sql = 'select count(*) from table_name';
$res = $pdo->query($sql);
print_r($res->fetchAll());
$pdo->exec('USE db2');
$res = $pdo->query($sql);
print_r($res->fetchAll());
You actually do not need to specify the database upon connection at all. As long as you specify the database in every query, as Laz stated, this will work:
$dbh = new PDO('mysql:host=127.0.0.1','USER','PASS');
$query = "SELECT * FROM database1.table1";
$query = "SELECT * FROM database2.table1";
There is not, you will need to create two PDO objects for the separate connections if you would like to use both at runtime.
Edit: Interesting point by #laz below (which I'm guessing is the cause of negative votes on my answer). I was thinking under the assumption that the databases were on separate servers tbh, in which case my answer stands.
you don't even need to specify the database in every query, just use msyql syntax
USE db_name
and then write your requests
you can make this :
$database1 = new PDO("mysql:host=localhost;dbname=db1;charset=utf8;",$username, $password);
$database2 = new PDO("mysql:host=localhost;dbname=db2;charset=utf8;",$username, $password);
simple 😀

PHP PDO: How to make num_rows, fetch_array, etc

I would like to know how to use the common mysql_* stuff. I don't take to make SO a mess and make a question for each one, so I just put up this question with a small list:
num_rows
fetch_array
set_charset
fetch_row
This is the functions you use to normal mysql_* queries, what are the PDO´s functions equals to these?
And how can you INSERT INTO, UPDATE and DELETE
The only thing I know and tested right now is connect to the db + selecting like this:
$conn = new PDO("mysql:host=$host;dbname=$db",$user,$pass);
$sql = "SELECT id FROM users";
$q = $conn->query($sql) or die("failed!");
What I expect for an answer is either links to each function and attributes
(num_rows, fetch_array, insert into, update, etc..) or direct answers to them.
$q = $conn->query($sql) or die("failed!");
Don't do that. Use:
$conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
Then you'll get an exception if something goes wrong with the query.
have a look at the documentation: http://php.net/manual/en/book.pdo.php
Its all in there

Categories