prathameshkakade Posted February 13, 2014 Share Posted February 13, 2014 Hello Everyone,I was learning connecting MySQLi with PHP.I wanted to display the names of all the databases on my server.I used the following code. <?php $server = 'localhost'; $user = 'root'; $pass = 'pass'; $mysqli = new mysqli($server,$user,$pass); if($mysqli->connect_error) die("Could not connect to server.<br/>"); $query = "SHOW DATABASES"; if($result = $mysqli->query($query)) { while($row = $result->fetch_row()) { printf("%s<br/>",$row[0]); } } ?> I am getting the desired result,but I didi not understand the functions fetch_row() and fetch_assoc properly. and why are we using the indice '0' in the line printf("%s<br/>",$row[0]); I tried using 1,but it gave me errors.I did not understand what was given on php.net manual. Someone please explain me in detail. Thank you. Quote Link to comment Share on other sites More sharing options...
Solution phpzer Posted February 13, 2014 Solution Share Posted February 13, 2014 Hello Everyone,I was learning connecting MySQLi with PHP.I wanted to display the names of all the databases on my server.I used the following code. <?php $server = 'localhost'; $user = 'root'; $pass = 'pass'; $mysqli = new mysqli($server,$user,$pass); if($mysqli->connect_error) die("Could not connect to server.<br/>"); $query = "SHOW DATABASES"; if($result = $mysqli->query($query)) { while($row = $result->fetch_row()) { printf("%s<br/>",$row[0]); } } ?> I am getting the desired result,but I didi not understand the functions fetch_row() and fetch_assoc properly. and why are we using the indice '0' in the line printf("%s<br/>",$row[0]); I tried using 1,but it gave me errors.I did not understand what was given on php.net manual. Someone please explain me in detail. Thank you. Hello, the function fetch_row() takes all the collumns in the database and puts them in an idexed array. In PHP arrays start with index 0, your query generates a mysql output like this (output might be different depending on your mysql version): +--------------------+ | Database | +--------------------+ | information_schema | | database_one | | database_two | +--------------------+ As you can see the only column in there is "Database", so column number one (index 0) is the only column you can access. If you try to access the value 1 you are asking PHP to do something it can't do so it's why it shows an error. The function fetch_assoc() returns an associative array, an associative array it's something like this: array( "key" => "value", "key2" => "value2", "key3" => "value3" // and so on ) Fetch_assoc is really useful when you don't know on what index the column are but you know the names of them. Hope I explained myself, if you didn't understand just say it, I will explain it differently. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.