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

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?

Related

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?

Recycling variable names for mysqli results?

Is there a benefit or drawback to using the same variable to store the results of consequetive mysql queries, like this example?
$res = mysqli_query($conn, "UPDATE Research SET Progress=Progress+1 WHERE ID=1");
$res = mysqli_query($conn,"SELECT Progress FROM Research WHERE ID=1");
$res = mysqli_fetch_assoc($res);
I do it all the time. I copy and past those lines routinely. the only drawback is if you need an additional query while looping through the results of the first, in which case, things will get ugly. In those cases, you will need a unique name for the second query.

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.

PDO query result includes "PDO Object()"

I'm new to PDO, so I suspect the cause of my problem is something I've overlooked somewhere. What's happening is this: when I run a query on a PDO like
$sql = "select * from some table";
$result = $pdo->query($sql);
$result always looks like this:
PDO Object()
{[field1:value], [field2:value]}
So what's going on? Why is the phrase "PDO Object()" always at the start of the result set? None of the examples I've seen show this, and many Google searches have been fruitless. Any help would be greatly appreciated.
As Michael Berkowski explained you need to fetch. Also since you're just learning use prepared statements (more secure). Here's how you do it.
$sql = "SELECT * FROM some_table WHERE field = :someVar";
$statement = $pdo->prepare($sql);
$statement->execute(array(':someVar'=>"expectedFieldValue"));
$result = $statement->fetchAll();

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

Categories