How to output the MySQL EXPLAIN data in php? - php

I wonder if there is a way to output the EXPLAIN data from an MYSQL statement to PHP.
For studying I need to write a small application in PHP that outputs data via a SELECT query from a MYSQL DB. I have to output the EXPLAIN data, like searched rows etc., from this query as well. If I just set EXPLAIN in front of the SELECT, I get an Error.
Unfortunately I couldn't find a satisfying answer on the internet.
Due to I'm new to PHP, I would appreciate if someone can give me an example or smth like this.
Thank you guys!

You should be able to grab it using standard array tools. By using $result->fetch_array(MYSQLI_NUM); we can just grab the first return without a column name
$sql = 'EXPLAIN SELECT * FROM table WHERE condition = "condition"';
$result = $mysqli->query($sql);
$row = $result->fetch_array(MYSQLI_NUM);
echo $row[0];

Related

How to get the column names of a result returned by select query

I am building a reporting tool where an user can enter a SQL query and the tool will return the results in a CSV file. In addition to just writing to a CSV file, I also need to perform some additional logic here. So SELECT INTO OUTFILE will not work for me.
I know that executing arbitrary user provided SQL queries is bad, but this tool is going to be used only internally, so security shouldn't be a concern. Also I am limiting it to only select queries.
Now when I export the data in CSV format, I also want to output the column names of the query as the first row in the CSV file.
So my question is, is there a way to fetch the column names of a SQL query in PHP using PDO?
Mysql client tools like Sequel Pro are able to display the column names while displaying query results. So I am assuming that it should be possible, but I am not able to find it.
Here I am not writing full PDO connection code. You can use below code/logic to get the return column name.
$stmt = $conn->query("SELECT COUNT(*), first_column, second_column FROM table_name");
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$columns = array_keys($row);
print_r($columns); // array(0 => COUNT(*), 1 => first_column, 2 => second_column)
The keys of the row result are the column names. You can display them like so:
$conn = mysqli_connect(YOUR_CONNECTION_INFO);
$result = mysqli_query($conn, YOUR_QUERY);
$row = mysqli_fetch_assoc($result);
foreach ($row as $key=>$value) {
echo $key;
}
You said security wasn't an issue since the code would only be used internally, but what happens if you create a new database user with limited rights and connect to the database using that user.
That way you can set up the rights as you want from your database and won't have to worry about users dropping tables.

Search database table using rawQuery

I' am using MySQLI Wrapper as stated in the docs about running rawQuery. Since it doesn't have any function to search database I had write my own. Below is the code that am using.
$songs = $db->ObjectBuilder()->rawQuery('SELECT * FROM songs WHERE song_name LIKE ?', array('%test%'));
The query returns empty results, yes there are data in the database which should match the search keyword. Any idea what am I doing wrong in the Query?
I don't know the structure and content of songs but your code seems to be correct. You can try if problem persists when array('%test%') is inserted into query by inserting this manually. Try to execute this:
$db->ObjectBuilder()->rawQuery("SELECT * FROM songs WHERE song_name LIKE '%test%'");
If this query returns empty results then I would suspect that something wrong is either in your query or in the database. Otherwise, there is something wrong with rewriting parameters by rawQuery function.

Alternative to mssql_guid_string in PHP?

I found a couple of results similar to what I'm about to ask but unfortunately none of them provided a solution or direction to the problem I'm facing.
I'm reviewing a large SQL Server 2008 database and I'm running some blanket queries such as running a SELECT TOP(5) on every table to get an idea of the contents.
I've encountered some Binary(16) objects in the results in PHP and of course PHP isn't able to print a readable version of the id easily. I don't have the option of adding the MSSQL extension to make use of the mssql_guid_string function and I can't perform the convert in SQL as the select needs to be as generic as possible to work for every table. I'm doing a foreach on a list of tables to return the data and print it.
So my question is: Does anyone know of an alternative to mssql_guid_string in PHP??
The pseudo of what I'm trying to do would be;
1. SELECT TOP(5) * FROM table1
2. WHILE $row = sqlsrv_fetch_array{...
3. foreach $row as $col print $col
The id's in SQL look something like this -> 0xB0826E8A84CA6C418254E28BC0F749CF
When printed in PHP they look like this -> X÷Eòv˜H½XšÔÛé«Ù
Any help/thoughts would be greatly appreciated.
Steve
From the PHP side you can dump to hexadecimal and add a prefix:
echo '0x' . strtoupper(bin2hex($col));
From SQL Server you can probably cast to string (no idea about that).

MySQL database manipulation with PHP

Spent the last few days researching this, but I think I'm just not getting it... I can usually do what I need to with PHP but am new to MySQL
I set up a MySQL database to hold some photos. The photo's are in separate galleries (gallery is denoted by a gallery field). The photo's are also indexed by an id number.
When displaying the photos (it all works perfectly up to now...), I would like to be able to jump to the next or previous photo in the gallery, but can't just us the next or previous id, as it could be from a different group (found that out the hard way ;)
from my research, I feel like I need to use this:
$sql = "SELECT id FROM gphoto WHERE gallery='$g' ORDER BY id DESC";
$query = mysqli_query($db_conx, $sql);
But $query doesn't seem to give me what I expect. It feels like $query it should contain an array if all id's which contain gphoto, and I should be able to just find my current id number, then jump one up or down, but when I try to read $query I get:
Cannot use object of type mysqli_result as array
I'm obviously misunderstanding something
Some people have suggested:
$result = mysqli_fetch_assoc($query);
I had tried this after reading the online manual extensively, but for some reason it only lists one item... in this case the last record.
If I run it as ASC, it lists the first. Should it be listing all records like I expect, or is it a different command?
C)
+1 for Fabio's response.
A good advice is to use PDO interface for accessing databases in PHP. It's a meaningful interface to construct, execute and fetch the results of your queries without the knowledge of the used db driver.
http://php.net/manual/en/book.pdo.php
You need to fetch data from database after executing your query to handle mysqli object you have just created
$query = mysqli_query($db_conx, $sql);
$result = mysqli_fetch_assoc($query);
Now you have the array you were looking for in your variable $result
if ($result = mysqli_query($db_conx, $query)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
//mysqli_fetch_assoc fetches data by row
}
}
You are only getting 1 row, thats how mysqli_fetch_assoc works. If you want the entire result to be an array of the rows, use mysqli_fetch_all
I would recommend using PDO however like #ceadreak suggested.

MySQL - Simple search for ID and return name

G'day,
I'm not familiar with MySQL and this will probably be an easy question!
I am trying to mod a Joomla plugin and am working with this code that works well for a similar function:
$q="SELECT `".$naming."` AS naming FROM `#__users` WHERE `id`='".$jomsocial_event->creator."' ";
$db->setQuery($q);
$eventcreatorname = $db->loadResult();
$eventcreator = ''.addslashes($eventcreatorname).'';
What I need to do is lookup the field id in the table community_groups and return the matching field name. What I have is (note that $jomsocial_event->contentid contains the group ID):
$q="SELECT `".$naming."` AS naming FROM `#__community_groups` WHERE `id`='".$jomsocial_event->contentid."' ";
$db->setQuery($q);
$eventgroupname = $db->loadResult();
$eventgroup = ''.addslashes($eventcreatorname).'';
It returns nothing as the query is wrong; what should it be for my usage?
I'd work backwards from the database.
i.e. turn on SQL logging and look at what's actually arriving in the database. Tweak as necessary by playing with the resulting SQL until you get what you want (and expect) and then implement that in your code.
Take a look at your generated query in the debugging from Joomla.
Run it against mysql directly and see where it goes wrong.
Also, I'd use the JDatabaseQuery API because you are much less likely to get errors with quoting etc. It looks to me like you are treating id as a string not an integer.

Categories