i have this code that will display the items perfectly but having a error pop up that i have to click "OK" too view the page
i have searched the web and from what i understand this has something to do with that the header table has more column than the data itself, i have tried to troubleshot this and got nowhere fast as i am a novice (noob) :/
if anyone can shed some light on this it would be great! :)
The Error
DataTables warning (table id = 'example'): Requested unknown parameter '0'
from the data source for row 0
My Code
<?php
//include database connection
include 'db_connect.php';
//query all records from the database
$query = "select * from repair_jobs";
//execute the query
$result = $mysqli->query( $query );
//get number of rows returned
$num_results = $result->num_rows;
//this will link us to our add.php to create new record
if( $num_results > 0){ //it means there's already a database record
//start table
//creating our table heading
echo "<table id='example' cellpadding='0' cellspacing='0' border='0' class='display' >";
echo "<thead><tr>";
echo "<th>Client</th>";
echo "<th>Type</th>";
echo "<th>Labour</th>";
echo "<th>ourcosts</th>";
echo "</thead></tr><tbody><tr class=\"gradeX\">";
//loop to show each records
while( $row = $result->fetch_assoc() ){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td>{$client}</td>";
echo "<td>{$type}</td>";
echo "<td>{$labour}</td>";
echo "<td>{$ourcosts}</td>";
echo "</td>";
echo "</tr>";
}
echo "</table>";//end table
}else{
//if database table is empty
echo "No records found.";
}
//disconnect from database
$result->free();
$mysqli->close();
?>
it displays ok but this error puzzling me.
Related
This question already has answers here:
Show values from a MySQL database table inside a HTML table on a webpage
(9 answers)
Closed 1 year ago.
I am new at php and am trying to learn CRUD applications. For this part of the code I have a table set up in a database (mysql). I am trying to interact with the table. I want a user to login (that part works) and when they are logged in- I store a message in $_SESSION that says ie. 'success'. This lets me know the user is logged in. Not the problem. The second piece is that IF there are rows IN THE TABLE already (from previous sessions) I want to print out these rows in a table. If there are no rows I want to print out "No rows"
I am trying to use simple logic here where first I create the $row variable by doing a fetch that comes from a pdo object(also fine). If that row is TRUE ie. it exists, print the table. If that row is false, print no rows. However, I keep getting the whole table printed, say 5 times. Instead of the 5 rows in the table.
Also, I am not sure I am using the correct type of while () statement. Which right now reads,
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
And then I get the WHOLE table and all rows 5 whole times. fetch and PDO::FETCH_ASSOC are a bit unclear to me, and I am understanding the $row as either true or false.
$stmt= $pdo->query("SELECT make, model, year, mileage from autos");
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ( isset($_SESSION['success']) && $row == true ) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo ('<table border="1">'."\n");
echo "<tr><td>";
echo "Make";
echo ("</td><td>");
echo "Model";
echo ("</td><td>");
echo "Year";
echo ("</td><td>");
echo "Mileage";
echo ("</td><td>");
echo "Action";
echo ("</td></tr>");
echo "<tr><td>";
echo (htmlentities($row['make']));
echo ("</td><td>");
echo (htmlentities($row['model']));
echo ("</td><td>");
echo (htmlentities($row['year']));
echo ("</td><td>");
echo (htmlentities($row['mileage']));
echo ("</td><td>");
echo ('Edit'.'/'.'<a
href="delete".php?user_id='.$row['user_id'].'>Delete</a>');
echo "</td></tr>";
}
} elseif ( isset($_SESSION['success']) && $row == false ){
echo "No rows found";
}
I keep getting the whole table printed, say 5 times.
Because you're printing the whole table on each iteration of the loop:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo ('<table border="1">'."\n");
// etc.
Instead of checking whether the first row is true, check the row count:
$stmt= $pdo->query("SELECT make, model, year, mileage from autos");
$count = $stmt->rowCount();
if ( isset($_SESSION['success']) && $count > 0 )
Then output your table outside the loop and just output each row inside the loop:
echo ('<table border="1">'."\n");
// etc, output the table header
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo "<tr><td>";
// etc.
echo "</td></tr>";
}
echo ('</table>'."\n");
I have a webpage that displays cars from the first car in the table to the last car with a while loop.
I have the following columns: Make, Model, Price. In my syntax I have an anchor tag around the Make rows that links to the description page of the Make you click on.
I want my <h> tags to change to the Model of the corresponding Make.
I've spent over an hour trying to achieve this but all I could come up with is this:
<?php
$query = "SELECT Model FROM inventory;";
$Vtitle = $conn->query($query);
$Vtitle_ar = mysqli_fetch_assoc($Vtitle);
echo "<h1>".$Vtitle_ar['Model']."</h1>";
?>
This works to an extent.
Every anchor I click replaces the <h> tags with only the first result under the Model column in my database.
Here is my code for the the entire car inventory page
<?php
$query = "SELECT * FROM inventory;";
/* Try to query the database */
if ($result = $conn->query($query)) {
// Don't do anything if successful.
}
else {
echo "Error getting cars from database:" .$conn->error()."<br>";
}
// Create the table headers
echo "<table id='Grid' style='width: 80%'><tr>";
echo "<th style='width: 50px'>Make</th>";
echo "<th style='width: 50px'>Model</th>";
echo "<th style='width: 50px'>Asking Price</th>";
echo "</tr>\n";
$class = "odd"; // keep track of whether a row was even or odd, so we can style it later
// Loop through all the rows returned by the query, creating a table for each row
while ($result_ar = mysqli_fetch_assoc($result)) {
echo "<tr class=\"$class\">";
echo "<td><a href='viewcar.php?VIN=".$result_ar['VIN']."'>".$result_ar['Make']."<a></td>";
echo "<td>".$result_ar['Model']."</td>";
echo "<td>".$result_ar['ASKING_PRICE']."</td>";
echo "</td></tr>\n";
// if the last row was even, make the next one odd and vice-versa
if ($class=="odd") {
$class = "even";
}
else {
$class = "odd";
}
}
echo "</table>";
$conn->close();
?>
Does anyone how I can do this?
I'm new to programming and I'm trying to use this for an actual project I'm working on for a hair salon's website
Add a WHERE clause to the query.
$vin = $_GET['VIN'];
$stmt = $conn->prepare("SELECT Model FROM inventory WHERE VIN = ?");
$stmt->bind_param("s", $vin);
$stmt->execute();
$stmt->bind_result($model);
$stmt->fetch();
echo "<h1>$model</h1>";
Though not a solution resolved with the use of a where clause as given by #Barmar whilst formatting the code I did find an error within the HTML which was not immediately obvious
The line echo "</td></tr>\n"; has an extra </td> which would break the flow of the html and can have detrimental effects. Also, // Don't do anything if successful. makes no sense - if there are results then process the recordset otherwise show the error ;-)
<?php
$query = "SELECT * FROM inventory;";
if ( $result = $conn->query( $query ) ) {
echo "
<table id='Grid' style='width: 80%'>
<tr>
<th style='width: 50px'>Make</th>
<th style='width: 50px'>Model</th>
<th style='width: 50px'>Asking Price</th>
</tr>";
$i=0;
while( $result_ar = mysqli_fetch_assoc( $result ) ) {
$class = $i %2 == 0 ? 'even' : 'odd';
echo "
<tr class='$class'>
<td><a href='viewcar.php?VIN={$result_ar['VIN']}'>{$result_ar['Make']}<a></td>
<td>{$result_ar['Model']}</td>
<td>{$result_ar['ASKING_PRICE']}</td>
</tr>";
$i++;
}
echo "</table>";
} else {
echo "Error getting cars from database:" .$conn->error()."<br>";
}
$conn->close();
?>
For styling alternate table rows ( the above uses a modulus function to calculate odd/even ) you can do it with some simple CSS - such as
tr:nth-child( odd ){/* rules */}
I have a simple project that I am working on and I'm having a hard time finding the code I need to get line breaks in the following table:
<?php
// connect to the database
$host = '###';
$username = '###';
$pass = '####';
mysql_connect($host,$username,$pass) or die(mysql_error());
mysql_select_db("####") or die(mysql_error());
// select everything from the table
$query = "SELECT * FROM Employees";
$result = mysql_query($query) or die(mysql_error());
echo "<table>";
echo "<tr>";
while( ($row = mysql_fetch_array($result)))
{
echo "<td>".$row['employeeid']."</td>";
echo "<td>".$row['firstname']."</td>";
echo "<td>".$row['lastname']."</td>";
echo "<td>".$row['department']."</td>";
}
echo "</tr>";
echo "</table>";
// disconnect from the database
mysql_close();
?>
Everything works correctly and it grabs data from the correct database and table. But when it displays results it is all on the same line ("record1record2record3") and I'd like a line break between employee records.
I've searched this question and it seems like my results all show me an entirely different way of doing this. I've already got the code written and fussed with it a lot to get it working. Can I just make a simple alteration to the above code to get the breaks I want?
The <tr> tags must also be inside the while loop so that they are outputted for each row. They make the rows in the HTML table.
while( ($row = mysql_fetch_array($result)))
{
echo "<tr>";
echo "<td>".$row['employeeid']."</td>";
echo "<td>".$row['firstname']."</td>";
echo "<td>".$row['lastname']."</td>";
echo "<td>".$row['department']."</td>";
echo "</tr>";
}
I am making a website for a mock book database using MSSQL where users can search for different books and select particular books that they might like to add to a list of favorites under their account name. The problem I am having is that I have no idea how to differentiate which book selection they want to add to their favorites because I can't figure out how to set the ISBN of the book, which uniquely identifies it, to a php session variable. If anyone can shed some light on this I would appreciate it, have been trying to figure it out all day.
//Set up connection
$connection = mssql_connect("$hostName", "$sqlUsername", "$sqlPassword")
or die("ERROR: selecting database server failed.");
//Select database
mssql_select_db($databaseName, $connection)
or die("ERROR: Selecting database failed");
//Search to run if searching for book title
if(isset($_GET['searchBook'])){
$searchBook = $_GET['searchBook'];
$query = "SELECT BOOK.ISBN, Title, Author, Publisher, NumberOfPages, Language, LocationName, ListPrice FROM BOOK, PRICE, LOCATION WHERE Title LIKE '%$searchBook%' AND BOOK.ISBN = PRICE.ISBN AND PRICE.LocationID = LOCATION.LocationID";
}
//Search to run is searching for a book author
if(isset($_GET['searchAuthor'])){
$searchAuthor = $_GET['searchAuthor'];
$query = "SELECT BOOK.ISBN, Title, Author, Genre, Publisher, NumberOfPages, Language, LocationName, ListPrice FROM BOOK, PRICE, LOCATION WHERE Author LIKE '%$searchAuthor%' AND BOOK.ISBN = PRICE.ISBN AND PRICE.LocationID = LOCATION.LocationID";
}
//Store query result
$query_result = mssql_query($query, $connection)
or die( "ERROR: Query is wrong");
//Set up table to display search results
echo "<form action=\"addFavorite.php\" method=\"POST\" name=\"table\">";
echo "<table border=1 align=\"center\">";
echo "<tr>";
// fetch attribute names
while ($filed = mssql_fetch_field($query_result)) {
echo "<th>".$filed->name."</th>";
}
echo "<th>Favorite</th>";
echo "</tr>";
// fetch table records
while ($line = mssql_fetch_row($query_result)) {
echo "<tr>\n";
foreach ($line as $eachline) {
echo "<td> $eachline </td>";
}
echo "<td><input name=\"".$line['index']."\" type=\"submit\" value=\"Add To Favorites\"></td>";
echo "</tr>\n";
}
echo "</table>";
echo "</form>";
Not sure if this is relevant but the following code is my best attempt at getting the value of ISBN that corresponds to the row of the button being clicked, which doesn't exactly work like I had hope.
//Get the ISBN
$data = mssql_fetch_assoc($query_result);
$ISBN = $data['ISBN'];
echo $ISBN;
Here is the code for my addFavorite.php which is where the form action is set to. This is the file that needs to know what user is adding a book as a favorite AND what book they are adding to that list.
//Set up connection
$connection = mssql_connect("$hostName", "$sqlUsername", "$sqlPassword")
or die("ERROR: selecting database server failed.");
//Select database
mssql_select_db($databaseName, $connection)
or die("ERROR: Selecting database failed");
$User = $_SESSION['userID'];
//Set up query
$query = "INSERT INTO FAVORITES VALUES(\"$User\",\"**I NEED A SESSION VARIABLE OR SOMETHING TO GO HERE\")";
//Store query result
$query_result = mssql_query($query, $connection)
//or die( "ERROR: Query is wrong");
Any help would be much appreciated. I know it's alot of information and if there is anything that doesn't make sense or I have forgotten to provide please let me know. Thanks.
EDIT
I have tried using the BUTTON instead of using INPUT but the value of the button is not setting to anything for some reason.
echo "<form action=\"addFavorite.php\" method=\"POST\" name=\"table\">";
echo "<table border=1 align=\"center\">";
echo "<tr>";
// fetch attribute names
while ($filed = mssql_fetch_field($query_result)) {
echo "<th>".$filed->name."</th>";
}
echo "<th>Favorite</th>";
echo "</tr>";
// fetch table records **PROBLEM IN HERE since $line['ISBN'] returns nothing**
while ($line = mssql_fetch_row($query_result)) {
echo "<tr>\n";
foreach ($line as $eachline) {
echo "<td> $eachline </td>";
}
echo "<td><button name=\"FavoriteButton\" type=\"submit\" value=\"".$line['ISBN']."\">Add To Favorites</button></td>";
echo "</tr>\n";
}
echo "</table>";
echo "</form>";
EDIT 2
Finally got it working, thanks to everyone for helping! Partial code that was problematic posted below in working condition.
echo "<form action=\"addFavorite.php\" method=\"POST\" name=\"table\">";
echo "<table border=1 align=\"center\">";
echo "<tr>";
// fetch attribute names
while ($filed = mssql_fetch_field($query_result)) {
echo "<th>".$filed->name."</th>";
}
echo "<th>Favorite</th>";
echo "</tr>";
// fetch table records
while ($line = mssql_fetch_row($query_result)) {
echo "<tr>\n";
foreach ($line as $eachline) {
echo "<td> $eachline </td>";
}
echo "<td><button name=\"FavoriteButton\" type=\"submit\" value=\"".$line[0]."\">Add To Favorites</button></td>";
echo "</tr>\n";
}
echo "</table>";
echo "</form>";
Use a BUTTON-element instead of the INPUT-element. That way, you can use the 'value'-attribute of this element to pass the correct value.
echo "<td><button name=\"$line['index']\" value=\"$line['ISBN']\" type=\"submit\">Add to favorites</button></td>";
Although I would suggest using AJAX instead of the above approach for this: use the onclick event from a button to execute javascript that calls a seperate php-file and passes the correct ISBN-number. This is then added to the database and your original page should be refreshed or part of the page reloaded.
I am building a table on a wordpress site that displays data that is sorted from one table.
What I cannot get right is to change the title to a URL, that is changeable (slug) from the same db.
The basic url stays the same only the slug changes
ie wwww.thesite.com/job/view/ --- and then the slug.
Here is my code so far.
function dbTEST($atts, $content = null) {
// Get all the data from the "job board" table
$result = mysql_query("SELECT * FROM wpjb_job WHERE job_country='72' ORDER BY job_title")
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>Job</th> <th>Company</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
#---------- I need this job_title to url link to the job_slug
echo $row['job_title'];
echo $row['job_slug'];
echo "</td><td>";
echo $row['company_name'];
echo "</td></tr>";
}
echo "</table>";
}
Try this:
echo "".$row['job_title'].""