Hi I'm very new to PHP because I just started learning this 2 days ago!
I'm trying to display my second table properly in my index.html file but I get this error: Invalid argument supplied for foreach() Take a look
Any help would be much appreciated
Class
public class Category {
public int Id{get;set;}
public string Name {get;set;}
}
public class Product{
public int Id{get;set;}
public int CategoryId{get;set;}
public String Brand {get;set;}
public String Name {get;set;}
public decimal Price{get;set;
}
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<h3>PHP CRUD Grid</h3>
</div>
<div class="row">
<p>
Create
</p>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Id</th>
<th>CategoryId</th>
<th>Brand</th>
<th>Name</th>
<th>Barcode</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php
include_once 'database.php';
$pdo = Database::connect();
$sql = 'SELECT * FROM product ORDER BY id DESC';
foreach ($pdo->query($sql) as $row) {
echo '<tr>';
echo '<td>'. $row['id'] . '</td>';
echo '<td>'. $row['category_id'] . '</td>';
echo '<td>'. $row['brand'] . '</td>';
echo '<td>'. $row['name'] . '</td>';
echo '<td>'. $row['barcode'] . '</td>';
echo '<td>'. $row['price'] . '</td>';
echo '<td width=250>';
echo '<a class="btn" href="read.php?id='.$row['id'].'">Read</a>';
echo ' ';
echo '<a class="btn btn-success" href="update.php?id='.$row['id'].'">Update</a>';
echo ' ';
echo '<a class="btn btn-danger" href="delete.php?id='.$row['id'].'">Delete</a>';
echo '</td>';
echo '</tr>';
}
?>
</tbody>
</table>
<div class="container">
<div class="row">
<h3>PHP CRUD Grid</h3>
</div>
<div class="row">
<p>
Create
</p>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>CategoryId</th>
<th>Category Name</th>
</tr>
</thead>
include_once 'database.php';
<?php
$sql2 = 'SELECT * FROM category ORDER BY id DESC';
foreach ($pdo->query($sql2) as $row) {
echo '<tr>';
echo '<td>'. $row['id'] . '</td>';
echo '<td>'. $row['category_name'] . '</td>';
echo '<td width=250>';
echo '<a class="btn" href="readCategory.php?id='.$row['id'].'">Read</a>';
echo ' ';
echo '<a class="btn btn-success" href="updateCategory.php?id='.$row['id'].'">Update</a>';
echo ' ';
echo '<a class="btn btn-danger" href="deleteCategory.php?id='.$row['id'].'">Delete</a>';
echo '</td>';
echo '</tr>';
}
Database::disconnect();
?>
</tbody>
</table>
</div>
</div>
</body>
</html>
Remove the second:
include 'database.php';
or use:
include_once 'database.php';
to prevent double loading of your database file.
You might want to consider not disconnecting and connecting again
You have 6 th elements in the header and 7 td elements in your rows. Try to add a th in the header row.
This implies that the SQL query is failing (PDO returns false if the query fails). The manpage says
If you do not fetch all of the data in a result set before issuing your next call to PDO::query(), your call may fail. Call PDOStatement::closeCursor() to release the database resources associated with the PDOStatement object before issuing your next call to PDO::query().
Edit:
Doesn't look like this is the issue - try adding
echo '<pre>'.print_r($pdo->errorInfo(), true).'</pre>';
after the for each loop, this should output the PDO error details.
Related
I have a page which displays data from SQL in a table and on that table one cell is hyperlinked and I want a modal (using bootstrap) to open and fetch data using the ID (the hyperlink value) and populate with data on the body in modal from SQL. I have tried different approaches but none is working well. The modal opens up but its not prominent as if its opening in background. Please help me with this.
Used Links in HEAD:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script>
PHP Code
<?php
while ($ticketdata = mysqli_fetch_array($ticketresults))
{
// Print out the contents of the entry
echo '<tbody>';
echo '<th scope="row"><a href="#" data-toggle="modal" data-target="#ticketModal'.$ticketdata['ticketnumber'].'">';
echo $ticketdata['ticketnumber'];
echo '</a>';
echo '</th>';
echo '<td>' . $ticketdata['policynumber'] . '</td>';
echo '<td>' . $ticketdata['registration_number'] . '</td>';
echo '<td>' . $ticketdata['insuredname'] . '</td>';
echo '<td>' . $ticketdata['contactnumber'] . '</td>';
echo '<td>' . $ticketdata['casestatus'] . '</td>';
echo '<td>';
echo '<form method="post">';
echo '<input type="hidden" name="ticketnumber" value="'. $ticketdata['ticketnumber']. '">';
echo '<input type="submit" class="btn btn-danger btn-sm" name="deletedata" value="Delete">';
echo '</form>';
echo '</td>';
echo '</tbody>';
}
?>
How do I pass the ID to the modal and where should I initialize the modal passing the ID (hyperlink) to populate the modal with data using the ID with PHP script?
<table>
<?php
while($ticketdata = mysqli_fetch_array($ticketresults)){
<tr>
<td><a href="#" id="<?php echo $ticketdata['ticketnumber']; ?>" class="view_data" /><?php echo $ticketdata['ticketnumber']; ?></a></td>
<td><?php echo $ticketdata['name']; ?></td>
<td><?php echo $ticketdata['policynumber']; ?></td>
<td><?php echo $ticketdata['registration_number']; ?></td>
<td><?php echo $ticketdata['insuredname']; ?></td>
<td><?php echo $ticketdata['contactnumber']; ?></td>
<td><?php echo $ticketdata['casestatus']; ?></td>
<td>DELETE</td>
</tr>
<?php } ?>
</table>
</body>
</html>
<div id="dataModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Policy Details</h4>
</div>
<div class="modal-body" id="detail">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Ajax Code:-
<script>
$(document).ready(function(){
$('.view_data').click(function(){
var ticket_id = $(this).attr("id");
$.ajax({
url:"select.php",
method:"post",
data:{ticket_id:ticket_id},
success:function(data){
$('#detail').html(data);
$('#dataModal').modal("show");
}
});
});
});
</script>
select.php:-
<?php
if(isset($_POST["ticket_id"]))
{
$output = '';
$connect = mysqli_connect("localhost", "root", "", "testing");
$query = "SELECT * FROM table_name WHERE id = '".$_POST["ticket_id"]."'";
$result = mysqli_query($connect, $query);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td width="30%"><label>S. No</label></td>
<td width="70%">'.$row["ticketnumber"].'</td>
</tr>
<tr>
<td width="30%"><label>Ticket Name</label></td>
<td width="70%">'.$row["name"].' Year</td>
</tr>
';
}
$output .= "</table></div>";
echo $output;
}
?>
I am working on posting a CRUD Application to where the user logs in first. The application is made with 2 MySQL tables; one for logging in and the other for the CRUD values. This example hasn’t worked on my local environment using both XAMP/PC and MAMP/MAC.
When I uploaded it to my host it does work, however the CRUD values don’t populate when it the for each loop is specified. I concatenated the mysql_error(); to explain why this is not working on my host.
On line 34 in logincrud/main.php:
The code from the table in main.php:
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Number</th>
<th>Explanation</th>
<th>Date Accured</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
include 'database.php';
$pdo = Database::connect();
$sql = 'SELECT * FROM saftey ORDER BY id DESC';
foreach (($sql) as $row) {
echo '<tr>';
echo '<td>'. $row['ins_n'] . '</td>';
echo '<td>'. $row['explanation'] . '</td>';
echo '<td>'. $row['date'] . '</td>';
echo '<td width=250>';
echo '<a class="btn" href="read.php?id='.$row['id'].'">Read</a>';
echo ' ';
echo '<a class="btn btn-success" href="update.php?id='.$row['id'].'">Update</a>';
echo ' ';
echo '<a class="btn btn-danger" href="delete.php?id='.$row['id'].'">Delete</a>';
echo '</td>';
echo '</tr>';
}
Database::disconnect();
?>
</tbody>
</table>
The Add, Update, and Delete works on the host as I can see the records from the safety table on myphpadmin. The login/logoff is from a completely different table. Again, the local environment works with no issues.
I opened a help ticket with my host provider, but all I received is they do not troubleshoot Applications.
I have been looking for solutions for a few weeks and all I couldn’t find a solution. In the Chrome browser the console states the error: hp:1 Failed to load resource: the server responded with a status of 500 ()" Server issue? Aware of SQL Injection problems.
I uploaded a GITHUB project if it helps.
Thank you in advance.
I solved the problem why it was not working on my live site. Looking at this Stackoverflow article
The way the PHP Data Object has the forward arrow executes the code. The way this foreach works caused the value return false; in other words not in an array.
I reorganized the PHP Data Object into a variable known as $records.
foreach (($sql) as $row) {
to
$records = $pdo->query($sql);
foreach ($records as $row) {
changed the echo to print
}
Works now. Weird how echo is different than print in this situation.
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Number</th>
<th>Explanation</th>
<th>Date Accured</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
include 'database.php';
$pdo = Database::connect();
$sql = 'SELECT * FROM safety ORDER BY id DESC';
$records = $pdo->query($sql);
foreach ($records as $row) {
print '<tr>';
print '<td>'. $row['ins_n'] . '</td>';
print '<td>'. $row['explanation'] . '</td>';
print '<td>'. $row['date'] . '</td>';
print '<td width=250>';
print '<a class="btn" href="read.php?id='.$row['id'].'">Read</a>';
print ' ';
print '<a class="btn btn-success" href="update.php?id='.$row['id'].'">Update</a>';
print ' ';
print '<a class="btn btn-danger" href="delete.php?id='.$row['id'].'">Delete</a>';
print '</td>';
print '</tr>';
}
Database::disconnect();
Here's the thing, I need to update a selected row from a table, so I'm putting a form for each row of it (Every single row has an update button) and when I click update, it doesn't submit, actually, doesn't do anything.
Here's my code, I'll be grateful with the solution.
<div class="table-responsive">
<table class="table table-condensed">
<thead class="">
<tr>
<th>ID</th>
<th>Project</th>
<th>Type</th>
<th>Kick-Off Date</th>
<th>Deadline Date</th>
<th>Current Ninja</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$q = $_GET['q'];
$sql="SELECT pr.project_name, pr.project_type, pr.project_start_date, pr.project_end_date, us.nombre, st.id_status, pr.id_project FROM NT_Projects as pr LEFT JOIN Project_Status as st on st.id_status = pr.id_status LEFT JOIN NT_Clients as cl on cl.id_client = pr.id_client LEFT JOIN usuarios as us on us.username = pr.username WHERE cl.id_client = $q";
$result = mysql_query($sql) or die(mysql_error());
$upt = 1;
while($row = mysql_fetch_array($result)) {
echo '
<div id="update-project">
<form method="post" action="sistema/_actions/updateProject.php" id="res-update-proj-'.$upt.'">';
$kickoff = date('m/d/Y', strtotime($row[2]));
$deadline = date('m/d/Y', strtotime($row[3]));
echo '<tr>';
echo '<td width="95px">
<input class="form-control" name="id_Proj" type="text" value="'.$row[6].'" readonly>
</td>';
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $kickoff . "</td>";
echo "<td>" . $deadline . "</td>";
echo "<td>" . $row[4] . "</td>";
echo '<td width="225px">';
echo '<select class="form-control" name="proj_Status">';
$qStatus = "SELECT * FROM Project_Status;";
$exStatus = mysql_query($qStatus);
while($rStatus = mysql_fetch_array($exStatus))
{
if($row[5] == $rStatus[0])
echo '<option value="'.$rStatus[0].'" selected>'.$rStatus[1].'</option>';
else
echo '<option value="'.$rStatus[0].'">'.$rStatus[1].'</option>';
}
echo '</select>
</td>
<td class="text-center">
<button type="submit" class="btn btn-sm btn-primary btn-UProj" value="res-update-proj-'.$upt.'">Update</button>
<div id="res-update-proj-'.$upt.'" style="width: 100%; margin:0px; padding:0px;"></div>
</td>
</tr>
</form>
</div>';
$upt = $upt + 1;
}
?>
</tbody>
</table>
</div>
That code is being called from another HTML with ajax
You cannot mix table tags with divs and forms according to the web standards. If you do, browser's HTML-parser will mix your tags in unpredictable way.
The only solution I know is to utilize CSS:
<div style="display: table">
<form style="display: table-row">
<div> style="display: table-cell"></div>
</form>
</div>
I have a bootstrap table where I get the values from my database using select:
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>Studentnamn</th>
<th>Student ID</th>
<th>Registrerade kurser</th>
<th>Betyg</th>
</tr>
</thead>
<tbody>
<?php include 'studentDB.php'; ?>
</tbody>
</table>
I want to make my table collapse and then display an inputform where the values on onclicked row can be updated. I have used following code:
$sql = "SELECT student.studName, grades.studId, grades.courseId, grades.grade FROM student
INNER JOIN grades ON student.studId=grades.studId";
try {
foreach ($pdo->query($sql) as $row) {
echo '<tr data-toggle="collapse" data-target="#collapseUpdate">';
echo '<td>' . $row['studName'] . '</td>';
echo '<td>' . $row['studId'] . '</td>';
echo '<td>' . $row['courseId'] . '</td>';
echo '<td>' . $row['grade'] . '</td>';
echo '</tr>';
echo '<tr>';
echo '<td colspan="6" class="hiddenRow" id="collapseRow"><div class="accordian-body collapse" id="collapseUpdate">
<div class="card card-block">
<form class="form-horizontal" action="update.php" method="post" id="newGrade">
<div class="control-group">
<label class="control-label">Nytt betyg:</label>
<div class="controls">
<p><input id="cbetyg" name="grade" type="text"></p>
<input type="hidden" name="studId" value="'. $row['studId'] .'">
<input type="hidden" name="courseId" value="'. $row['courseId'] .'">
</div>
</div>
<div class="form-actions">
<input type="submit" name="submit" value="Ändra">
</div>
</form>
My problem here is now that, only the first row collapses and can use update. When I click on the other rows, the first row collapses... Can somebody tell me what I can do? And also, will my update still work for each individual row if I make the collapse work for all the rows?
My table looks like this (click here)
Thanks!
You are using the same collapseUpdate target in any field. Try modify these lines:
instead
echo '<tr data-toggle="collapse" data-target="#collapseUpdate">';
use
echo '<tr data-toggle="collapse" data-target="#collapseUpdate'.$row['studId'].'">';
and instead
echo '<td colspan="6" class="hiddenRow" id="collapseRow"><div class="accordian-body collapse" id="collapseUpdate">
use
echo '<td colspan="6" class="hiddenRow" id="collapseRow"><div class="accordian-body collapse" id="collapseUpdate'.$row['studId'].'">
I suspect that studId is unique in this table.
I am trying to send the id from one page to other and i have achieved that but how do i make sure that when the show is pressed of a particular column only that id is sent.Here is my code.
This is index.php.It displays the rows and a show button against each row.
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<h3>Restaurant Categories</h3>
</div>
<div class="row">
<p> Create </p>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<?php
include 'database.php';
$pdo = Database::connect();
$sql = 'SELECT * FROM Categories';
$result = $pdo->query($sql);
foreach ($pdo->query($sql) as $row) {
echo '<tr>';
echo '<td>'. $row['C_id'] . '</td>';
echo '<td>'. $row['C_name'] . '</td>';
echo '<td>'. $row['C_description'] . '</td>';
echo '<td><a class="btn" href="show_items.php">Shitems</a> </td>';
$_SESSION["id"] = $row['C_id']; <-----I am saving the id here.But it only saves the latest id
echo $_SESSION["id"];
echo '</tr>';
}
Database::disconnect();
?>
</tbody>
</table>
</div>
</div> <!-- /container -->
</body>
</html>
Just embed the ID in the url as a query string:
echo '<td><a class="btn" href="show_items.php?id=' . $row['C_id'] . '">Shitems</a> </td>';
^^^^^^^^^^^^^^^^^^^^
Simple using _GET...
<a class="btn" href="show_items.php">
<a class="btn" href="show_items.php?id=<?=$row['C_id']?>">
Then you can access it via... _GET['id']
First you need from form around button. But you can make this with ajax(if you don't redirect the page) or link