MySQL query with/without table specific reference - php

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

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?

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.

Change my code to only count rows with spesific value in a cell

How i can change my code to count only columns with a specific value in a column.
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select('COUNT(*)')
->from('#__zoo_item');
Is this making my code much more slow? Is there a better way to do it? It will help if i enable cache in this joomla module because the script runs in my homepage :O
There's nothing wrong with getting data from the database, based on a specific column value. This is what the where clause is for. Like so:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('COUNT(*)')
->from($db->quoteName('#__zoo_item'))
->where($db->quoteName('state') . ' = 1');
Also note I've used $db->quoteName() when defining column names which is used to escape them.
Hope this helps

Using PHP variables inside MYSQL stored queries

I searched before posting this but didn't find an answer to my question.
I have a table in a database which stores queries such as (with the php variable stored in the database):
select * from accounts where type = 'client'
select * from accounts where user_id = $userid
select * from accounts where name = '$name'
I assumed that when I pulled that particular query from the database that PHP would recognized the variable and replace it but it treats it as regular text.
Is there a way to have PHP replace the $__ with an actual variable that exists? I think maybe the eval() function perhaps??
What you might try is using it as a prepared statement. So instead, if your database stored queries looked like this:
select * from accounts where type = 'client'
select * from accounts where user_id = ?
select * from accounts where name = ?
and you use PDO prepared statements like this:
$pdo = new PDO($dsn, $user, $pass);
$statement = $pdo->prepare($secondOfTheAboveQueries);
$statement->execute(array($userId));
$account = $statement->fetch();
You could also use prepared queries with named variables like user_id = :userid instead of questions marks if you have to process a few statements at a time with various variables.
You may also want to consider stored procedures which work similarly. An explanation for both can be found here:
http://php.net/manual/en/pdo.prepared-statements.php
Assuming that you pull the query from a database:
$string = ''; // Assign the real userID
while ($fetch = mysql_fetch_array($query)) {
$newQuery = str_replace('$userid', $string, $fetch['your_row_name']);
}
I'm not sure if this will work, but this is what i would try first...
sprint seems to work well. instead of storing them as $variable, I can use %s, etc.

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