Issue migrating mysql to mysqli - php

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.

Related

PHP: how to switch from raw SQL query to laravel raw query?

When switching to Laravel, SQL queries are changed.
From this:
$sql = "SELECT * FROM table";
$result = mysqli_query($db, $sql);
to:
$sql = 'SELECT * FROM table';
$result = DB::select($sql);
(I want to use SQL raw queries in LARAVEL to make rewriting the code easier https://laravel.com/docs/7.x/database#running-queries)
Sorry if this question is obvious, but I'm a beginner and don't understand the other answers I've found. Now what to add to the new code, so the old $result and new $result behave the same?
Because new $result is an array, right? I need to have the new $result behave like the old $result to change the code easily.
Optional: do you know which topics I need to learn to understand this better myself?

PDO Query Not Showing Data

I want to migrate a site from some poorly written MySQLi to clean PDO.
I have looked at three similar questions and their answers, and this is a straightforward question, but none of them are giving me results. Here's my code:
$state = "Alaska";
//trying to implement PDO here
$sql = "SELECT * FROM sales WHERE state = ? ORDER BY type";
$result = $conn->prepare($sql);
$result->execute(array($state));
/*
this was the old, successfully working way before
$sql = "SELECT * FROM sales WHERE state = '$state' ORDER BY type";
$result = $conn->query($sql);
*/
Previous questions on this site show me answers that look like my PDO implementation, yet mine doesn't work. I have made sure the PDO class exists and that the extension is loaded.
If you see the error, let me know!
The difference between the two, aside from difference in libraries, is that one is using a direct query() (the mysqli_*), while the other is using a prepared statement. Those are handled a bit different, regardless which API is running.
When using MySQLi, doing
$result = $conn->query($sql);
would have $result be a mysqli-result object, which holds the data. You can use mysqli_result::fetch_assoc() on that to fetch the data. However, when you're using PDO::prepare(), your $result variable will be a PDOStatement - which is a bit different. You'll need to run a fetch() method on it first, and then you can use the return-value of it, as such
$state = "Alaska";
$sql = "SELECT * FROM sales WHERE state = ? ORDER BY type";
$stmt = $conn->prepare($sql);
$stmt->execute(array($state));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
Note that I've changed the names of your variables. Now $result is an array (if there are any results fetched), which you can use as you normally do when fetching associative-arrays. If there are no results, PDOStatement::fetch() will return a boolean false.
var_dump($result['state']);
You can loop the fetch() method as
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
if you expect more than one row. Use $result as you would without looping, as shown above.
Note that this assumes a valid PDO-connection. Beware that you cannot interchange any MySQL libraries, mysql_, mysqli_* and PDO are all different animals in the zoo.
PHP.net on PDOStatement::fetch()
Can I mix MySQL APIs in PHP?

MySQL query with/without table specific reference

In Joomla 2.5.14, when I create a query to MySQL using PHP, like:
$query = "SELECT id FROM xmb9d_content WHERE state=1" ;
It all works fine, but if I don't want a specific reference to the database prefix (xmb9d_) and use:
$query = "SELECT id FROM #__content WHERE state=1" ;
The query isn't executed. Is this the right way of building the query or what is wrong with this code?
You need to use the database prefix and also stick to Joomla 2.5 coding standards. There shouldn't be any problems with the prefix, providing your query is correct.
This is how it should look:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('id')
->from('#__content')
->where('state = 1');
$db->setQuery($query);
$results = $db->loadObjectList();
xmb9d_content is the name of the table by replacing it with #__content you are attempting to run the query on a table that doesn't exist (i assume) so it wont work.
What is the issue with the prefix? I don't understand how it could cause you an problems

How to select from mysql db php

Are these 2 equivalent, if not how can I make them. I'm using php/Mysql (I'll use mysqli later)
mysql_select_db("db_App", $link);
$result = mysql_query("SELECT * FROM AppOne");
OR
$result = mysql_query("SELECT * FROM db_App.AppOne"); // how can I get this to work like above?
You'll always have to select a database. From then on, specifying the database in the query is useless. It's better not to specify it there anyway, as that'd make you run into troubles if your database changes at some point.
if you skip the $link in mysql_select_db("db_App", $link);
they should do the same.

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 😀

Categories