error when using php to connect to mysql - php

I am trying to dynamically build a table on my page through ajax, using jquery and php. The following is my php code:
<?php
$con = mysql_connect("127.0.0.1","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("tbl_name", $con);
$result = mysql_query("SELECT `Book ISBN` FROM tbl_name");
echo "<table id='booklist'><tr>
<th>Edit</th>
<th class='coursename'>Course Name</th>
<th class='startdate'>Start Date</th>
<th class='booktitle'>Book Title</th>
<th class='author'>Book Author</th>
<th class='isbn'>Book ISBN</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>
<td><input type='checkbox'></input></td>
<td class='coursename'>" . $row[`Course Name`] . "</td>
<td class='startdate'>" . $row[`Start Date`] . "</td>
<td class='booktitle'>" . $row[`Book Title`]. "</td>
<td class='author'>" . $row[`Book ISBN`]. "</td>
<td class='isbn'><input class='ISBN_number' type='text' value='' size='13' maxlength='13'></input></td>
</tr>";
}
echo "</table>";
mysql_close($con);
?>
(Note: the row names have spaces in them (thats how the database came). I used back ticks instead of single quotes because someone online said thats how you can keep the spaces... If I get over this issue I'll see if that works.)
Next my jquery script:
$(document).ready(function()
{
$("#build_table").click(function()
{
$.get("build_table.php",
function(table)
{ console.log("Entered table function");
$("#input_table").replaceWith("<div id='input_table'>" + table + "</div>");
});
});
});
and the html:
<input id="build_table" style="clear:both" type="button" value="Submit"></input>
When I click on this button, though, I get the following php error:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:...pathname...\build_table.php on line 13
What is this error?

run this query this way
$sql = "SELECT `Book ISBN` FROM tbl_name";
$result = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
and see

The problem lies in your query. Are you sure that your database and table is named tbl_name? Change your statement into this:
$result = mysql_query("SELECT `Book ISBN` FROM tbl_name") or die(mysql_error());
And you'll get a error message from MySQL.

Related

Loading a specific row from database into a html table

As you can see I have developed a html/php page to create orders and I am having issues trying to load data from a table (MySQL) into that table I created in html. What I want is the user to digit an ID (identification) a secondary key like order number and then the whole row goes to my table. where he can edit, delete and save the row. So far i have the table and I was able to load the whole tabe in the html page.
HTML:
<p>What order number would you like to load?<input type="text" id="SKU" maxlength="10" size="10" placeholder="Search for SKU..." title="Type an SKU..."><button onclick="myCreateFunction()">LOAD</button></p>
<table id="itemsTable"> <tr> ID <th>Quantity</th>
<th>Item</th>
<th>SKU</th>
<th>Item Name</th>
<th>Item Price</th>
<th>Subtotal</th>
<th>Cartons Scanned</th>
<th>Individually Scanned</th>
<th>Current Inventory</th>
<th>Location Selected</th>
<th>Image</th>
<th>Edit</th>
</tr>
<tr>
</tr>
</table>
now the php:
<?php
//Step2
$query = "SELECT * FROM item_new WHERE SKU=input ";
mysqli_query($db, $query) or die('Error querying database.');
$result = mysqli_query($db, $query);
$all_property = array(); //declare an array for saving property
//showing property
echo '<table id="itemsTable" class="data-table">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>'; //end tr tag
//showing data selected by the user (input)
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
database table
script
<script>
function myCreateFunction() {
var input
input = document.getElementById("SKU");
}
You can use following code block for you solution
there will be two ways to fetch data as you want one can be using AJAX which is bit of complex and another is using form.
<p>What order number would you like to load?</p>
<form type="post" action=''>
<input type="text" name='input_field' id="SKU" maxlength="10" size="10" placeholder="Search for SKU..." title="Type an SKU...">
<input type='submit' name='search'>
</form>
<table id="itemsTable">
<tr>
<th>ID</th>
<th>Quantity</th>
<th>Item</th>
<th>SKU</th>
<th>Item Name</th>
<th>Item Price</th>
<th>Subtotal</th>
<th>Cartons Scanned</th>
<th>Individually Scanned</th>
<th>Current Inventory</th>
<th>Location Selected</th>
<th>Image</th>
<th>Edit</th>
</tr>
<?php
//Check if form is submitted
if(isset($_POST['search'])){
$query = "SELECT * FROM item_new WHERE SKU='".$_POST['input_field']."'";
mysqli_query($db, $query) or die('Error querying database.');
$result = mysqli_query($db, $query);
$all_property = array();
//showing property
while ($property = mysqli_fetch_field($result)) {
array_push($all_property, $property->name); //save those to array
}
//showing data selected by the user (input)
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo "<a href='myeditpage?id=".$_row['id']."' >Edit product</a>"
echo '</tr>';
}
}
?>
</table>
in upper example we first let the user to input the data using input and when user click on search it will submit the form to current URL.
after that we check if user submitted the form or not if submitted the we will fetch data and print on the table.

How to Add update button in html table for editing table data?

Following code extracting values from MySQL table using PHP. I want to add an update button in the last column of this table. I have done some coding, but when I am clicking on update its showing white screen. I want HTML table to become editable when the user clicks on update button and after submitting the values will be changed in MySQL table.
Here is code:
<?php
$connection = mysqli_connect ('localhost', 'user', 'password', 'testdb');
if (!$connection){
echo 'Not connected to server';
}
$select_db = mysqli_select_db($connection, 'testdb');
if (!$select_db){
echo 'Not connected to database';
}
$sql= "SELECT * FROM students";
$query = mysqli_query($connection, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($connection));
}
if(isset($_POST['update'])){
$UpdateQuery = "UPDATE `students` SET `elected_subject`='$ElectedSubject'";
mysql_query($UpdateQuery, $con);
};
?>
<h1><strong>Student Record</strong></h1>
<table id = "result" class="data-table">
<caption class="title"></caption>
<thead>
<tr>
<th>Student ID</th>
<th>Student Name</th>
<th>Father Name</th>
<th>Class</th>
<th>Selected Subject</th>
<th>View/Update</th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
$total = 0;
while ($row = mysqli_fetch_array($query))
{
echo "<form action=update_students.php method=post>";
$student = $row['stu_id'] == 0 ? '' : number_format($row['stu_id']);
echo '<tr>
<td>'.$row['student_id'].'</td>
<td>'.$row['student_name'].'</td>
<td>'.$row['father_name'].'</td>
<td>'.$row['class'].'</td>
<td>'.$row['elected_subject'].'</td>
<td>' . "<input type='submit' name='update' value='update'>" . '</td>
</tr>';
$total += $row['stu_id'];
$no++;
}?>
</tbody>
</table>
update_students.php is the same file which is having this code.

how to show images in php page from link saved in DB

So if you feel the question is repeated ,I have tried other solutions but not working.I have link of images stored in Database(phpMyAdmin) as string.I want to load the image as a part of the second column of a table from DB using the links.
<table style="width:100%" id="to1">
<tr>
<th>ID</th>
<th>Featured Image</th>
<th>Title</th>
<th>Brand Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Shipping Cost</th>
<th>Delivery Time </th>
<th>Delivery Distance</th>
</tr>
<?php
$conn = mysqli_connect("localhost","root", "", "products");
if ($conn-> connect_error){
die("Connection Failed: ". $conn-> connect_error);
}
$sql = "SELECT id,featured_image,title,brand_name,price,quantity,shipping_cost,delivery_time,delivery_distance from products";
$result = $conn-> query($sql);
if ($result-> num_rows > 0){
while ($row = $result-> fetch_assoc()){
$val = $row["featured_image"];
echo "<tr><td>".$row["id"] ."</td><td>". '<img src='<?= **HERE** ?>' alt="">' ."</td><td>".$row["title"] ."</td><td>".$row["brand_name"] ."</td><td>".$row["price"] ."</td><td>".$row["quantity"] ."</td><td>".$row["shipping_cost"] ."</td><td>".$row["delivery_time"] ."</td><td>".$row["delivery_distance"] ."</td></tr>";
}
echo "</table>";
}
else{
echo "0 tables";
}
$conn-> close();
?>
I have shown the place as here .please suggest some ways so that I can show images instead of links in the table.
Here is what I want it to look like.
I think, you had quotes problems:
UPDATED:
echo "<tr><td>".$row["id"] ."</td><td><img src='".$row["featured_image"]."' alt=''></td><td>".$row["title"]."</td><td>".$row["brand_name"]."</td><td>".$row["price"]."</td><td>".$row["quantity"]."</td><td>".$row["shipping_cost"]."</td><td>".$row["delivery_time"]."</td><td>".$row["delivery_distance"] ."</td></tr>";
echo "
<tr>
<td>.$row["id"].</td>
<td>.<img src='$row["featured_image"]' alt="">.</td>
<td>.$row["title"].</td>
<td>.$row["brand_name"].</td>
<td>.$row["price"].</td>
<td>.$row["quantity"].</td>
<td>.$row["shipping_cost"].</td>
<td>.$row["delivery_time"].</td>
<td>.$row["delivery_distance"].</td>
</tr>"
Try this

live search in html table

I want to search by product name then get productdetailsid from db then compare it with each row in this table if it exists , set bachground-color for row!
<div class="input-group m-b"><span class="input-group-btn">
<button type="button" class="btn btn-primary">Go!</button> </span> <input type="text" class="form-control"id="autocomplete">
</div>
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th style="text-align: center">#</th>
<th style="text-align: center">Product Name</th>
<th style="text-align: center">Quantity</th>
<th style="text-align: center">Product Price</th>
<th style="text-align: center">Whole Price</th>
<th style="text-align: center">Supplier Name</th>
<th style="text-align: center"></th>
</tr>
</thead>
<tbody>
<?php
$per_page=5;
if (isset($_GET["page"])) {
$page = $_GET["page"];
}
else {
$page=1;
}
$start_from = ($page-1) * $per_page;
$sql = "select p.productname,p.quantity,p.onesale,p.wholesale,p.productdetailsid,s.fullname from productdetails p , supplier s where s.supplierid = p.supplierID LIMIT $start_from,$per_page";
$count = ($page*5)-4;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<form method=\"post\" action=\"\">";
echo "<tr>";
echo "<td>" . $count++ . "</td>";
echo "<td>" . $row["productname"] . "</td>
<td>" . $row["quantity"] . "</td>
<td>" . $row["onesale"] . "</td>
<td>" . $row["wholesale"] . "</td>
<td>" . $row["fullname"] . "</td>
<td><button type=\"submit\" class=\"btn btn-xs btn-danger\" name=\"removeBtn\"><i class=\"fa fa-times\"></i> </button></td>
<td style=\"display:none;\"><input type=\"hidden\" name=\"id\" value='".$row["productdetailsid"]."'>
</td>"
;
echo "</tr>";
echo "</form>";
}
}
$conn->close();
?>
</tbody>
</table>
</div>
For Live search in the table you need to use AJAX for getting the result, then using that result you can use Javascript loop to find which rows are found and change the color. I would prefer JSON output (JSON array output) from the PHP script, I can use that in Javascript Loop...
in PHP
You need to make a seperate PHP file for getting ajax output...say ajax.php
<?php
//Assuming that 'q' is the POST variable for finding the query
if(!empty($_POST['q']))
{
//Put your database query execution code here with using q as search query
//Set header to JSON
header('Content-Type:application/json');
//assuming that $result is associative array of your SQL query output
which contains array of the rows to be hightlighted
echo json_encode($result);
}
This will give a JSON array output which can be easily read by AJAX or $.post functions...
in Javascript
here's the tricky part. you need to make an ajax call and then use that data to highlight the rows....but first need to give an ID to the table body...
...<tbody id="table1">....</tbody></table>
Then you need to use ajax or $.post function to make the call, I have used $.post as it's simple
/**** Cosidering "input1" is a input element for getting query to be searched with id = input1 ****/
var q_data = $("#input1").val();
$.post(ajax.php,
{
q: q_data
},
function(data,status)
{
$.each($("#table1").find("<tr>"),function(i,value)
{
var element = $(this);
$.each(data,function(i,val2){
if(val2 == $(element).find("<td>").text())
{
$(element).css('background','lgihtyellow');
}
});
});
}
);
The code may not work before suitable changes, but this is the logic and concept of ajax based live search in the table

DataTables warning (table id = 'My Table'): Requested unknown parameter '0' from the data source

I have a datatable to show fields from a MYSQL database however I keep getting the error:
DataTables warning (table id = 'My Table'): Requested unknown
parameter '0' from the data source
Here is my code:
<table class="table table-striped table-bordered" id="sample_1">
<thead>
<tr>
<th style="width:8px;"><input type="checkbox" class="group-checkable" data-set="#sample_1 .checkboxes" /></th>
<th>Username</th>
<th class="hidden-phone">Email</th>
<th class="hidden-phone">Points</th>
<th class="hidden-phone">Joined</th>
<th class="hidden-phone"></th>
</tr>
</thead>
<tbody>
<?php
$con = mysql_connect("localhost","cl49-XXX","XXX");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("cl49-XXX", $con)or die( "Unable to select database");
$result=mysql_query("SELECT * FROM products ")or die('You need enter a catagory ' );
echo "<tr>"; // first row beginning
for ($i = 1; $i <= mysql_num_rows($result); $i++)
{
$row = mysql_fetch_array($result);
$prodname = $row['prodname'];
$prodID = $row['prodID'];
$catagory = $row['catagory'];
echo "<tr class='odd gradeX'>
<td><input type='checkbox' class='checkboxes' value='1'/></td>
<td class='hidden-phone'>$prodID</td>
<td class='hidden-phone'>$prodname</td>
<td class='hidden-phone'>$catagory</td>
<td class='hidden-phone'><a href='deleteproduct.php?q=$prodID'><button class='btn btn-danger'type='submit'><font color='white'>Delete</font> </a>
";
echo "</tr><tr>"; // it's time no move to next row
}
echo "</tr>"; // last row ending
?>
</tbody>
</table>
Does anyone know what this error means?
The number of td's should match what you have given while calling out the datatable();
Quick fix(if you do not want to customize the default functionalities) would be :
$('#sample_1').dataTable();
If you have given anything inside datatable({/configs/}) just remove it completely and it should work well.

Categories