Im a very novice programmer, i work with PHP and a have a doubt/problem with fetch_assoc().
I have this method that return the result of the database consult:
public function getUsuarios() {
try {
$resultado = $this->conexion->query("SELECT * FROM login_usuarios");
} catch(Exception $e) {
throw new Exception("Error al obtener los usuarios de la base de datos. Código de error: ".mysqli_errno);
} finally {
if($this->conexion != null) {
$this->conexion->close();
}
}
return $resultado;
}
This script iterate and show the data of the database consult's result:
<table>
<tr>
<td>Código</td>
<td>Nombres</td>
<td>Apellidos</td>
</tr>
<?php while ($fila = mysqli_fetch_array($usuarios)) { ?>
<tr>
<td><?php print($fila['codUsuario']); ?></td>
<td><?php print($fila['nombres']); ?></td>
<td><?php print($fila['apellidos']); ?></td>
</tr>
<?php
}
$usuarios->free();
?>
</table>
With this way, all worked fine (but i don't understand what xD, i've see this way in a forum).
But, i've see other way in many sites. With this way the script stand like this:
// first convert the result to a fetch_assoc
$usuarios = (new Consultas)->getUsuarios()->fetch_assoc();
<table>
<tr>
<td>Código</td>
<td>Nombres</td>
<td>Apellidos</td>
</tr>
<?php foreach ($usuarios as $fila) { ?>
<tr>
<td><?php print($fila["codUsuario"]); ?></td>
<td><?php print($fila["nombres"]); ?></td>
<td><?php print($fila["apellidos"]); ?></td>
</tr>
<?php
}
$usuarios->free();
?>-->
</table>
But with this way i have a Illegal string offset mysql. This looks like the foreach iterate on each column and not on each row.
Why the first way works and the second way don't?, How works mysqli_fetch_array($result) and fetch_assoc()?
Thanks for help.
Construction finally closes connection before your call fetch_assoc().
Try to comment $this->conexion->close();.
Your code iterates through row. mysqli_result::fetch_assoc return only one row. Please, read the documentation.
Related
This question already has answers here:
Checking if mysqli_query returned any values?
(2 answers)
Closed 3 months ago.
I'm using while loop to fetch data from the database I want to display like nothing found the result is null or empty. I've tried using if/else with like: if (empty($jobs)) echo 'nothing found'; that doesn't work. if(!mysqli_fetch_assoc($jobs)) works but if don't show the jobs if available.
Loop
<?php while ($job = mysqli_fetch_assoc($jobs)) { ?>
<tr class="custom-table-body-titles">
<td><?php echo h($job['updated_at']); ?></td>
<td>
<?php echo h($job['title']); ?>
</td>
<td>0/<?php echo h($job['required_freelancers']); ?></td>
<td><?php echo h($job['delivery_time']); ?> Days</td>
<td>$<?php echo h($job['budget']); ?></td>
<td>
Apply
</td>
</tr>
<?php } ?>
You have to do a validation to check if any results were found before even starting the loop. Assuming $jobs is an instance of mysqli_result returned by mysqli_query().
if (mysqli_num_rows($jobs) > 0)
{
// your while loop
}
else
{
echo "no jobs found";
}
You should keep PHP and HTML separate as much as you can.
You can fetch all results into an array before and then foreach on that array.
$jobs = $jobs->fetch_all(MYSQLI_ASSOC);
if($jobs) {
foreach ($jobs as $job) {
}
} else {
}
A good question which is sadly most of time is answered incorrectly.
It's a very bad practice to mix the database-related code and HTML code. There should never be a while loop like this.
Instead, the data should be fetched into array,
$jobs = [];
while ($row = mysqli_fetch_assoc($result)) {
$jobs[] = $row;
}
which is then used to output the data. And once you have this array, you can use it to tell whether the query returned any data or not:
<?php if ($jobs) { ?>
<?php foreach ($jobs as $job) { ?>
<tr class="custom-table-body-titles">
<td><?php echo h($job['updated_at']); ?></td>
<td>
<?php echo h($job['title']); ?>
</td>
<td>0/<?php echo h($job['required_freelancers']); ?></td>
<td><?php echo h($job['delivery_time']); ?> Days</td>
<td>$<?php echo h($job['budget']); ?></td>
<td>
Apply
</td>
</tr>
<?php } ?>
<?php } else {?>
no data
<?php } ?>
This query giving same result 3 times. i couldn't identify the error. I am using codeigniter. The query in the function in model is
Model
public function combinedFunctionTest($userID){
$this->db->from('test_report');
$this->db->join('assign_tble','test_report.scode=assign_tble.scode','LEFT');
$this->db->join('course_details','test_report.ccode=course_details.ccode','LEFT');
$this->db->where('test_report.scode',$userID);
$query=$this->db->get();
return $query->result();
}
Controller
public function results()
{
$this->load->model('AllCourses_m');
$data['records']=$this->AllCourses_m-> combinedFunctionTest('2420DC');
$this->load->view('courses/TestResult',$data);
}
View
<?php
foreach ($records as $rec) {
?>
<tr>
<td>
<?php echo $rec->ccode; ?>
</td>
<td><?php echo $rec->cname; ?></td>
<td><?php echo $rec->adate; ?></td>
<td><?php echo $rec->at_date; ?></td>
<td>
<?php echo $rec->score; ?>
</td>
</tr>
<?php
}
?>
Why this is resulting three times repetition for the same. anybody can help me?
Hello i'm stil learning, using Codeigniter can someone tell me, or give example code?
what i need is in Round Id we have 111 i want give it link and search database with value 111 how to do that? here the code i tried but still not right
<div class="row" id="ajaxdata">
<table border="1">
<tr>
<th>Round Id</th>
<th>Player Id</th>
<th>Bet Place</th>
<th>Total Bet</th>
<th>Win</th>
<th>Lose</th>
</tr>
<?php foreach ($tbl_bet_spot as $data) {?>
<tr>
<td><?php echo $data->round_id;?>
<td><?php echo $data->id;?></td>
<td><?php echo $data->bet;?></td>
<td><?php echo $data->total_bet;?></td>
<td><?php echo $data->win;?></td>
<td><?php echo $data->lose;?></td>
</tr>
<?php } ?>
</table>
</table>
</div>
controller
public function detail_round_id(){
$select = $_GET['select'];
$data['tbl_bet_spot'] = $this->login_model->selectRoundId_by_round($select)->result();
print_r ($data);
}
i just try with my code and it work now, but it's static in here
<td><?php echo $data->round_id;?>
how i can send this value <?php echo $data->round_id;?> properly into controller? thanks a lot.
Use this code
<td><?php echo $data->round_id;?></td>
controller
public function detail_round_id(){
$select = $this->uri->segment(3);
$data['tbl_bet_spot'] = $this->login_model->selectRoundId_by_round($select)->result();
print_r ($data);
}
Try this may help you,
In view make link like this,
<td><?php echo $data->round_id;?>
And in controller add parameter like this,
public function detail_round_id($id){
$data['tbl_bet_spot'] = $this->login_model->selectRoundId_by_round($id)->result();
print_r ($data);
}
view page you pass value like this
<?php echo $data->round_id;?>
In controller get value like this
$select=$this->uri->segment(4);
hope this will help
Trying to list the data from mysql to a html table using php in main html file. I've been through all of the other questions on here and I'm sure I have mostly the same methods and code as them.
For some reason (which I suspect has something to do with mysql and not the code) the only result is a blank table with one row and five columns. Each time I try to implement the other codes they just seem to print text onto the site.
I'm very confused as I think I've done the right thing. I've even been able to list the data from mysql through php echo so I know it's there and that I can access it. Really would appreciate some help on this. Thank you.
<table border="1">
<tbody>
<?php
$connect = mysqli_connect("localhost", "daemon", "xampp", "test");
if (!$connect) {
die(mysqli_error());
}
$results = mysqli_query("SELECT title,url,details,file,submission_date FROM input");
while($row = mysqli_fetch_array($results)) {
?>
<td><?php echo $row['title']?></td>
<td><?php echo $row['url']?></td>
<td><?php echo $row['details']?></td>
<td><?php echo $row['file']?></td>
<td><?php echo $row['submission_date']?></td>
<?php
}
?>
</tbody>
</table>
You say this code is in your mail html file? And it is printing out onto the screen? Try changing your file to .php not .html! Php code won't run in a .html file, and will likely output your code directly onto the page.
Mysqli_query expect connection link as first parameter.
$results = mysqli_query($connect, "SELECT title,url,details,file,submission_date FROM input");
Just a quick not so related improvement. You can avoid inserting most of the php opening and closing clauses:
...
while($row = mysqli_fetch_array($results)){
echo "<td>".$row['title']."/td>";
echo "<td>".$row['url']"</td>";
...
}
?>
Use <tr> because table must have atleast one row(<tr>) and one column(<td>)
<table border="1">
<tbody>
<tr>
<?php
$connect = mysqli_connect("localhost", "daemon", "xampp", "test");
if (!$connect) {
die(mysqli_error());
}
$results = mysqli_query("SELECT title,url,details,file,submission_date FROM input");
while($row = mysqli_fetch_array($results)) {
?>
<td><?php echo $row['title']?></td>
<td><?php echo $row['url']?></td>
<td><?php echo $row['details']?></td>
<td><?php echo $row['file']?></td>
<td><?php echo $row['submission_date']?></td>
<?php
}
?>
</tr>
</tbody>
<table border="1">
<tbody>
<?php
$connect = mysqli_connect("localhost", "daemon", "xampp", "test");
if (!$connect) {
die(mysqli_error());
}
$results = mysqli_query($connect, "SELECT title,url,details,file,submission_date FROM input");
if (!$results) {
mysqli_error($results);
die();
}
while ($row = mysqli_fetch_array($results)) {
?>
<tr>
<td><?php echo $row['title'] ?></td>
<td><?php echo $row['url'] ?></td>
<td><?php echo $row['details'] ?></td>
<td><?php echo $row['file'] ?></td>
<td><?php echo $row['submission_date'] ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
I have an activity table that contain the list of activity student had joined before. So if the student is new student, there will have been no activity for that student.
<table align="center" width="1000" border="1" >
<h3>Activity List</h3>
</br>
<tr align="center" style="font-weight:bold" >
<td>ID</td>
<td>Activity</td>
<td>Sem</td>
<td>Session</td>
<td>Achievement</td>
<td>Level</td>
</tr>
<?php do { ?>
<tr align="center">
<td><?php echo $row_Recordset1['student_id']; ?></td>
<td><?php echo $row_Recordset1['activity']; ?></td>
<td><?php echo $row_Recordset1['sem']; ?></td>
<td><?php echo $row_Recordset1['session']; ?></td>
<td><?php echo $row_Recordset1['achievement']; ?></td>
<td><?php echo $row_Recordset1['level']; ?></td>
</tr>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
</table>
How can I make this table only show on screen if it is not empty. Btw, im using session to display the exist record.
The best way to do this would be to get your array via mysql(i)_fetch_array() of the query you have build and then to chec to see if the query has rows like:
$qry = "SELECT `this` FROM `table`"
while ($result = mysql_fetch_array($qry)) {
if (mysql_num_rows($result) > 0) {
echo "We have rows!";
}
else {
echo "Looks like we haven't got anything here!";
}
}
I hope this helps.
Might also help to look here: PHP mysql_num_rows method.
<?php if(!empty($activity))
{
your msg ..
}
else
{
}
?>
where empty() will check a given variable is empty or not
Well that's what the if statement is used for:
if(!count($activities)) {
echo "This student has no activities yet.";
} else {
//display activities
....
}