Could anyone help me fetch data from a database and view it in a table? I am new to codeigniter framework.
-
you can do this from function mysql_queryFady Saad– Fady Saad2017-04-19 01:28:30 +00:00Commented Apr 19, 2017 at 1:28
-
stackoverflow.com/questions/17986379/…Peter– Peter2017-04-19 01:31:12 +00:00Commented Apr 19, 2017 at 1:31
-
Here's the documentation, give some time to research. codeigniter.com/user_guide/database/index.htmlJeffrey Hitosis– Jeffrey Hitosis2017-04-19 02:42:20 +00:00Commented Apr 19, 2017 at 2:42
1 Answer
here is a short Code for fetching Data from an SQL-Table
First you create a Connection:
// Create connection
$db = mysqli_connect($host,$username,$password,$database)
or die('Error connecting to MySQL server.');
The Values:
$host = your host-ip or URL or localhost
$username = Your Database Username
$password = your Database Password
$database = your database's Name
Then you need to request(query) something from a Table in that Database For Example like this:
$sql = "SELECT * FROM $table ORDER BY id DESC";
$res = mysqli_query($db, $sql) or die("Fehler:$sql");
while($row = mysqli_fetch_assoc($res))
{
}
Now this Code will get all the Data out of a Table and orders it by the ID Descending. In that code $table stands for your Table-Name and $db is your Database Name, as PHP7 needs it by every Query.
The Results eg. ALL Data in the Table, ordered by ID is now stored in the single Variable $res. If you want you can use code to check 'if ($res = true)' in order to make sure that you actually get a result from the query and catch an exception.
The 'Method mysqli_fetch_assoc()' will now give you all the Data nice and easy. All you have to do is use this While Loop like this:
while($row = mysqli_fetch_assoc($res))
{
$username = $row['username'];
$date= $row['date'];
}
Meaning, that every While Cycle goes through one Row of results in the order you chose to query it at. And $row acts as an Array where the Idice, ([] text in these brackets) corresponds to the given Clumn Name in your Table
Hope i could help you out :) And please in the future state your question a little more clear and detailed and show that you have actually worked on your Problem before asking
Spytrycer
Edit
I overread the table part :)
In order to view it in a Table you should do something like this:
echo"<table border = '1'>";
echo"<tr>";
//Do <td> and </td> for as many Columns as you have and write them between the td's
echo"<td>";
echo"Column Name";
echo"</td>";
//Then comes the Data part
$sql = "SELECT * FROM $table ORDER BY id DESC";
$res = mysqli_query($db, $sql) or die("Fehler:$sql");
while($row = mysqli_fetch_assoc($res))
{
//open new Row
echo"<tr>";
//Do this td, data, /td loop for as many Columns you have in your
Database. For a Database with id, username and Password for example:
echo"<td>";
echo"$row['id']";
echo"</td>";
echo"<td>";
echo"$row['username']";
echo"</td>";
echo"<td>";
echo"$row['password']";
echo"</td>";
echo"</tr>";
//Close row
}