I'm coding in PHP. I have the following mySQL table:
CREATE TABLE `students` (
`ID` int(10) NOT NULL AUTO_INCREMENT,
`Name` varchar(255) DEFAULT NULL,
`Start` int(10) DEFAULT NULL,
`End` int(10) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB;
I'm trying to use the mysqli_query function in PHP to DESCRIBE the table.
Here's my code:
$link = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DATABASE);
$result = mysqli_query($link,"DESCRIBE students");
The documentation says For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object.
But from there I don't know how to print $result
so that it shows the query results. If possible I want to print $result so that it looks like:
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| ID | int(10) | NO | PRI | NULL | auto_increment |
| Name | varchar(255) | YES | | NULL | |
| Start | int(10) | YES | | NULL | |
| End | int(10) | YES | | NULL | |
+----------+--------------+------+-----+---------+----------------+
My other question is how to print the query SHOW CREATE TABLE students
.
$result = mysqli_query($link,"SHOW CREATE TABLE students");
Well I have to admit that
mysqli_query()
manual entry doesn't contain a clean example on how to fetch multiple rows. May be it's because the routine is so routine, known to PHP folks for decades:In case you want to print column titles, you have to select your data into nested array first and then use keys of the first row:
Some hosts may have no support for the
fetch_all()
function. In such a case, fill $data array usual way:Two important notes I have to add.
You have to make mysqli throw errors automatically instead of checking them for each mysqli statement manually. To do so, add this line before
mysqli_connect()
:Most important note: unlike
mysql_query()
,mysqli_query()
has very limited use. You may use this function only if no variables are going to be used in the query. If any PHP variable is going to be used, you should never usemysqli_query()
, but always stick to prepared statements, like this:It's a bit wordy, I have to admit. So, for the everyday use, instead of using
mysqli
functions as is, one have to adopt some sort of wrapper, which will hide all the repeated code inside. There are many wrappers, but surely I think my own is the best ^_^. It is called Safemysql and it will let you to write safe and concise code at once:But if you don't like to use third-party libraries, then stick to PDO.