Fetch data and display it in a table in with codeigniter - php

Could anyone help me fetch data from a database and view it in a table? I am new to codeigniter framework.

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
}

Related

Generate buttons with php that delete or edit a row in a table in db

I need to call database and a specific table, then display table values in rows and at the end of them have buttons 'edit' and 'delete' that allow me to edit that line or delete it completely.
At the moment I only manage to display the table and generate the buttons, but not 'tie' the buttons to that row.
I need to generate the buttons when displaying the table, and then 'tie' the buttons to corresponding row.
Edit:
if(!empty($_POST) && isset($_POST['show'])) {
$sel = "SELECT id, vardas, pavarde, amzius, miestas FROM zmogaus_info";
$res = mysqli_query($conn, $sel);
if(mysqli_num_rows($res)>0){
while($row = mysqli_fetch_assoc($res)){
echo "Id: ".$row["id"]." ".$row["vardas"]." ".$row["pavarde"]." ".$row["amzius"]."m."."<input type='submit' name='".$row['id']."' value='Delete'>"."<br>";
}
}
}
if(!empty($_POST) && isset($_POST[$row['id']])){
$sql = "DELETE FROM zmogaus_info WHERE id=".$row['id'];
mysqli_query($conn, $sql);
}
I think the problem might be with the way I use $row['id'] and i might need to make it into a global variable?
If you are able to var_dump($result) and there is data there from DB, then there is no need for a while loop.
Also research PDO, much safer method of data transfer to and from DB.
$sel = "SELECT id, vardas, pavarde, amzius, miestas FROM zmogaus_info";
$result = $mysqli -> query($sel);
// Define the associative array as $row
$row = $result -> fetch_assoc();
echo "Id: ".$row["id"]." ".$row["vardas"]." ".$row["pavarde"]." ".$row["amzius"]."m."."<input type='submit' name='".$row['id']."' value='Delete'>"."<br>";

Use PHP loop to fetch tables data from the table which contain names of database tables

I have table named category which contain names of other tables in the same database. I want to fetch table names from category table and then fetch data from each table from db. So far I have this code below:
$db = new mysqli('localhost', 'root', '', 'db_cat');
if($db){
// $q = "SELECT TABLE";
// $echo = $db->query($q);
// echo $echo;
// $result = $db->query("SHOW TABLES");
$qCat="SELECT * FROM product_category";
$cat_query= $db->query($qCat) or die(mysql_error());
while ($fetch= $cat_query->fetch_object())
{
$cat_id=$fetch->id;
$category=$fetch->category;
$p_cat=str_replace(" ","_",strtolower($category).'_categories');
//if(strlen($category)>22){$fine_product_name= substr($service, 0,19).'...';}else{ $fine_product_name=$category;}
$result = $db->query("SHOW TABLES");
while($row = $result->fetch_array()){
$tables[] = $row[0];
}
}
The second query must be different.
$result = $db->query("SELECT * FROM $category");
while($row = $result->fetch_array()){
$tables[] = $row[0];
}
print_r($tables);
First of all your design to connect to a database is not that good, Please check the below code for a proper way of connecting to it.
<?php
$con=mysqli_connect("localhost","root","","db_cat");
//servername,username,password,dbname
if (mysqli_connect_errno())
{
echo "Failed to connect to MySql: ".mysqli_connect_error();
}
?>
Here is a sample code of getting data from a table ( where this table name is in another table).
$get_table_name ="SELECT TableName FROM table_name";
$get_name=mysqli_query($con,$get_table_name);
$count=0;
while($row_name=mysqli_fetch_array($get_name)){
$count++;
$tbName=$row_name['TableName'];
$_SESSION['table_name'][count]=$tbName;
}
This will show you how to fetch data from one table. You can use a For loop to get all the tables
$table=$_SESSION['table_name'][1];
$get_table ="SELECT * FROM $table";
.... // Normal way of fetching data
You can try to adjust your code according to this and improve it.
For further reference please refer http://php.net/manual/en/book.mysqli.php

Insert into a db data coming from a loop (while)

hi have a code like this
for ($i=0; $i<=count($query)+1 ; $i++)
{
$sql ="SELECT * FROM $tabella[$i] WHERE id='1'";
$result=mysql_query($sql);
$numrows=mysql_num_rows($result);
while($row = mysql_fetch_array($result))
{
$name=$row['name'];
$surname=$row['surname'];
INSERT INTO student (name,surname) Values ($name,$surname)
}
}
It insert the data only from the first table he found so only one name and one surname and not all the $name and $surname with id=1
How can I resolve it
Here is the edit to your script and possible problems I fouund:
for ($i=0; $i<=count($query)+1 ; $i++) //Why is there a +1?
{
$sql ="SELECT * FROM $tabella[$i] WHERE id='1'"; //Your issue could be here, tabella[$1]
$result=mysql_query($sql); //may not be totally there
$numrows=mysql_num_rows($result); //Try to echo your SELECT $sql query
//to check
//Why do you have $numrows? I dont see
//that being used anywhere
while($row = mysql_fetch_array($result))
{
$name=$row['name'];
$surname=$row['surname'];
INSERT INTO student (name,surname) Values ($name,$surname) //Your INSERT statement
//looks ok
//Try to use single/or double
//quotes around the values
//I like having `name`,
//`surname` around fields
}
}
Check with comments. It's recommended you use Prepared/or PDO but in most cases
websites that use straight mysql functions are older or have already been coded so there
aren't any changes of being redone; its a lot of work. This makes sense when you're starting fresh. Hope it helps.

Mysqli query multiple tables

I'm trying to make a query that then displays certain results based on previous queries
The idea is that when someone logs into the page, it gets the session username and and saves it to a variable, from there the first query selects a row based on the session username, gets that value and does the same in the second query but on a different table this time getting the row based on the result from query 1 and query 3 is same as two and then its meant to echo it out
here's the code
$con = mysqli_connect("localhost","root","","boats4u");
$search = $_SESSION['myusername'];
if(mysqli_connect_errno())
{
echo "Failed to connect to database". mysqli_connect_error();
}
$pre_res = mysqli_query($con,"SELECT ownerNo FROM boatowner WHERE email ='$search'");
$pre_res = $pre_res -> fetch_assoc();
$result = mysqli_query($con,"SELECT boatNo FROM boatforrent WHERE ownerNo ='$pre_res'");
$result = $result -> fetch_assoc();
$result2 = mysqli_query($con,"SELECT * FROM boatviewing WHERE boatNo = '$result'");
echo "<table border='1'>
<tr>
<th>Client No</th>
<th>Boat No</th>
<th>View Date</th>
<th>Comments</th>
</tr>";
while ($row = mysqli_fetch_array($result2))
{
echo "<tr>";
echo "<td>". $row['clientNo']."</td>";
echo "<td>". $row['boatNo']."</td>";
echo "<td>". $row['viewDate']."</td>";
echo "<td>". $row['comment']."</td>";
}
echo "</table>";
?>
this is what displays
Notice: Array to string conversion in
E:\Download\Xampp\htdocs\owner.php on line 29
If I remove the first query then it no errors but obviously the search doesn't work then
any help appreciated
You should do one query and also parametize the search parameter. Something along the lines like:
$stmt = $con->prepare('
SELECT boatviewing.*
FROM boatowner owner
LEFT JOIN boatforrent ON boatforrent.ownerNo = owner.ownerNo
LEFT JOIN boatviewing ON boatviewing.boatNo = boatforrent.boatNo
WHERE owner.email = ?
');
$stmt->bind_param("s", $search);
$stmt->execute();
$result = $stmt->get_result();
Such code is normally more robust against SQL injection and it's also easier in case you change your database layout.
Next to that you actually run one query instead of three which allows the database to optimize data-retrieval and keeps roundtrips between the PHP script and the database server low.

Multiple SELECT Statements and INSERTS in 1 file

I'm working with a file and I'm attempting to do multiple select statements one after another and insert some values. So far the insert and the select I've got working together but when attempting to get the last SELECT to work I get no value. Checking the SQL query in workbench and everything works fine. Here's the code:
$id = "SELECT idaccount FROM `animator`.`account` WHERE email = '$Email'";
$result = mysqli_query($dbc, $id) or die("Error: ".mysqli_error($dbc));
while($row = mysqli_fetch_array($result))
{
echo $row[0];
$insert_into_user = "INSERT INTO `animator`.`user` (idaccount) VALUES ('$row[0]')";
}
$select_userid = "SELECT iduser FROM `animator`.`user` WHERE iduser = '$row[0]'";
$results = mysqli_query($dbc, $select_userid) or die("Error: ".mysqli_error($dbc));
while($rows = mysqli_fetch_array($results))
{
echo $rows[0];
}
I do not want to use $mysqli->multi_query because of previous problems I ran into. Any suggestions? And yes I know the naming conventions are close naming... They will be changed shortly.
Your code makes no sense. You repeatedly build/re-build the $insert_int-User query, and then NEVER actually execute the query. The $select_userid query will use only the LAST retrieved $row[0] value from the first query. Since that last "row" will be a boolean FALSE to signify that no more data is available $row[0] will actually be trying to de-reference that boolean FALSE as an array.
Since you're effectively only doing 2 select queries (or at least trying to), why not re-write as a single two-value joined query?
SELECT iduser, idaccount
FROM account
LEFT JOIN user ON user.iduser=account.idaccount
WHERE email='$Email';
I'm not sure what you're trying to do in your code exactly but that a look at this...
// create select statement to get all accounts where email=$Email from animator.account
$id_query = "SELECT idaccount FROM animator.account WHERE email = '$Email'";
echo $id_query."\n";
// run select statement for email=$mail
$select_results = mysqli_query($dbc, $id_query) or die("Error: ".mysqli_error($dbc));
// if we got some rows back from the database...
if ($select_results!==false)
{
$row_count = 0;
// loop through all results
while($row = mysqli_fetch_array($result))
{
$idaccount = $row[0];
echo "\n\n-- Row #$row_count --------------------------------------------\n";
echo $idaccount."\n";
// create insert statement for this idaccount
$insert_into_user = "INSERT INTO animator.user (idaccount) VALUES ('$idaccount')";
echo $insert_into_user."\n";
// run insert statement for this idaccount
$insert_results = mysqli_query($dbc, $insert_into_user) or die("Error: ".mysqli_error($dbc));
// if our insert statement worked...
if ($insert_results!==false)
{
// Returns the auto generated id used in the last query
$last_inisert_id = mysqli_insert_id($dbc);
echo $last_inisert_id."\n";
}
else
{
echo "insert statement did not work.\n";
}
$row_count++;
}
}
// we didn't get any rows back from the DB for email=$Email
else
{
echo "select query returned no results...? \n";
}

Categories