Running mysql queries onclick from index page - php

I have an index.php on my localhost and I'd like to put several buttons to run different sql queries here. The queries will be like this one :
<table class="table1">
<tr>
<th>Date</th>
<th>Model</th>
<th>Type</th>
<th>InProduction</th>
<th>Price</th>
<th>Range</th>
<th>MaxSpeed</th>
<th>HP</th>
<th>Country</th>
<th>EType</th>
<th>Make</th>
<th>MPG</th>
<th>Seats</th>
</tr>
<?php
include ("config.php");
$sql = "SELECT Date, Model, Type, InProduction, Price, Range, MaxSpeed, HP, Country, EType, Make, MPG, Seats FROM Auto order by Date DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$counter = 0;
while($row = $result->fetch_assoc())
{
echo "<tr><td>" . $row["Date"]."</td><td>" . $row["Model"] . "</td><td>"
. $row["Type"]. "</td><td>". $row["InProduction"]. "</td><td>". $row["Price"]. "</td><td>".$row["Range"]. "</td><td>". $row["MaxSpeed"].
"</td><td>". $row["HP"]."</td><td>". $row["Country"]."</td><td>". $row["Etype"]."</td><td>". $row["Make"]. "</td><td>". $row["MPG"].
"</td><td>". $row["Seats"]."</td></tr>";
$counter++;
if($counter % 33 == 0) { ?>
</table>
<table class="table1">
<tr>
<th>Date</th>
<th>Model</th>
<th>Type</th>
<th>InProduction</th>
<th>Price</th>
<th>Range</th>
<th>MaxSpeed</th>
<th>HP</th>
<th>Country</th>
<th>EType</th>
<th>Make</th>
<th>MPG</th>
<th>Seats</th>
</tr>
<?php }
}
echo "</table>";
} else { echo "0 results"; }
$conn->close();
?>
</table>
Here I included all the parameters to be displayed on the page. Instead, what I would like to do is to use different parameters in each query. So with every click of a button, I'll be able to see different parameters listed as a table on the index page. So I plan to create several php files to list different parameters, and run them with the click of a button on the index.php. How can I do this with onclick button? and is this the most suitable way for this task? Note: I will publish this only locally. Thanks.

I found an ajax solution to the problem. It is not very neat and short but it works. I am open to any shorter way to achieve this task, I'd be grateful if you share. thanks. Here is the source of the solution: http://javascript-coder.com/tutorials/re-introduction-to-ajax.phtml
So for every button, the ajax code needs to be repeated with corresponding Id's.
HTML:
<div id="querydiv"> </div>
<button id='actbutton1'>query1</button>
AJAX:
<script>
document.getElementById('actbutton1').onclick=function()
{
var xhr = new XMLHttpRequest();
xhr.open("GET", "query1.php", true);
xhr.onreadystatechange = function ()
{
if (xhr.readyState==4 && xhr.status==200)
{
document.getElementById("querydiv").innerHTML=xhr.responseText;
}
}
xhr.send();
}
</script>

Depending on what exactly you want to do, you can also just use a query string to switch on/off of what queries/data you want the user to see. You can easily add the query string to the url in a button as you wish by simply setting the parameter in the onclick event:
<button onclick="location.url = '/mypage.php?show=firstdata';">Button1</button>
The switch of the queries in the PHP could look like the following:
if($_GET['show'] == "firstdata") {
//
// the first type query here
//
}elseif($_GET['show'] == "seconddata") {
//
// the second type query here
//
}

Related

How to delete the entire row in the database from html table instead of deleting entire table in the database

I have added delete button to the html table on each row and when clicked on delete button the entire row should be deleted but instead whole table in the database is being deleted.
here is my code for admin.php
<div class="container mt-3 ml-3">
<table class="table">
<thead>
<tr>
<th>S.No</th>
<th>Name</th>
<th>Email</th>
<th>Rating</th>
<th>Review</th>
<th>Image</th>
<th>Suggestion</th>
<th>NPS</th>
<th>Delete</th>
</tr>
</thead>
<tbody class="table-warning">
<?php
include 'database_conn.php'; // makes db connection
$sql = "SELECT feedbackID, name, email, rating, review, image, suggestion, nps
FROM feedback
ORDER BY feedbackID Desc";
$queryResult = $dbConn->query($sql);
// Check for and handle query failure
if($queryResult === false) {
echo "<p>Query failed: ".$dbConn->error."</p>\n";
exit;
}
// Otherwise fetch all the rows returned by the query one by one
else {
if ($queryResult->num_rows > 0) {
while ($rowObj = $queryResult->fetch_object()) {
echo "<tr>
<td>{$rowObj->feedbackID}</td>
<td>{$rowObj->name}</td>
<td>{$rowObj->email}</td>
<td>{$rowObj->rating}</td>
<td>{$rowObj->review}</td>
<td>{$rowObj->image}</td>
<td>{$rowObj->suggestion}</td>
<td>{$rowObj->nps}</td>
<td><a id='delete' href=delete.php?id={$rowObj->feedbackID}>Delete</a></td>
";
}
}
}
?>
</tr>
</tbody>
</table>
</div>
And here my code for delete.php. I think there is something wrong in the sql query I made.
<?php
include 'database_conn.php'; // makes db connection
$sql = "DELETE FROM feedback WHERE feedbackID=feedbackID";
if ($dbConn->query($sql) === TRUE) {
echo "Record deleted successfully. Please go to Customer Feedback Page by clicking"; echo "<a href='http://unn-w18031735.newnumyspace.co.uk/feedback/admin.php'> here</a>";
} else {
echo "Error deleting record: " . $dbConn->error;
}
$dbConn->close();
?>
This is wrong:
DELETE FROM feedback WHERE feedbackID=feedbackID
it is always true as it will be equal to itself.
What you want to use is parameters here. $_GET['id'] is where the id is.
If you use PDO, something like
$stmt = $dbConn->prepare("DELETE FROM feedback WHERE feedbackID=:feedback_id");
$stmt->execute(['feedback_id' => $_GET['id']]);
For mysqli,
$stmt = $mysqli->prepare("DELETE FROM feedback WHERE feedbackID=?");
$stmt->bind_param("i",$_GET['id']);
$stmt->execute();
this solution in delete.php has worked.
$feedbackID = $_GET["id"];
$sql = ("DELETE FROM feedback WHERE feedbackID= '$feedbackID'");

Like to jQuery sum values

I like to sum all values with script but get it the result: total:NaN
(need to sum all columns except the first column)
The code PHP and script are in the same file and this is my code:
For php:
<table id="table">
<thead class="thead-dark">
<tr class="titlerow">
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
<th>Col4</th>
<th>col5</th>
</tr>
</thead>
<tbody>
<tr>
<?php
include("conn.php");
$result = mysql_query("SELECT id,name,col1,col2 FROM table GROUP BY name");
while($test = mysql_fetch_array($result))
{
$id = $test['id'];
echo"<td class='rowDataSd'>".$test['col1']."</td>";
echo"<td class='rowDataSd'>".$test['col1']."</td>";
echo"<td class='rowDataSd'>".$test['col2']."</td>";
echo"<td class='rowDataSd'>".$test['col2']."</td>";
echo"<td class='rowDataSd'>".$test['col2']."</td>";
echo "</tr>";
}
mysql_close($conn);
echo '<tfoot>
<tr class="totalColumn">
<td>.</td>
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
</tr>
</tfoot>';
?>
</table>
For script:
var totals=[0,0,0];
$(document).ready(function(){
var $dataRows=$("#table tr:not('.totalColumn, .titlerow')");
$dataRows.each(function() {
$(this).find('.rowDataSd').each(function(i){
totals[i]+=parseInt( $(this).html());
});
});
$("#table td.totalCol").each(function(i){
$(this).html("total:"+totals[i]);
});
});
Where is the exact problem?
I'm not sure, but... as far as i know, and maybe i'm wrong (would be happy to get advise on that) => mysql_fetch_array and mysql_query is kinda "dead" and instead, today you should use: mysqli_fetch_array and mysqli_result (see the additional i), and that depends on the version you are running on your server that is. Does the query works for you?. If not, i would defently look into that.
See an example here:
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform queries
mysqli_query($con,"SELECT * FROM Persons");
mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)
VALUES ('Glenn','Quagmire',33)");
mysqli_close($con);
?>
I wouldn't sum them with jQuery at all. I would do it in PHP:
...
<tr> <!--- this tr is out of place, needs to be in the loop -->
<?php
//include("conn.php"); this should be require as it's necessary
//include will ignore missing files, require with throw an error
//this code will not work without that file, so let PHP tell you
//when it goes missing, instead of wondering why your DB calls don't work
require "conn.php"; // inlude/require are not functions they will work with (...) but it's not best practice.
$result = mysql_query("SELECT id,name,col1,col2 FROM table GROUP BY name");
//define default values for increment without errors
$totals = ['col1'=>0,'col2'=>0,'col3'=>0,'col4'=>0,'col5'=>0];
while($test = mysql_fetch_array($result))
{
$id = $test['id'];
echo "<tr>"; //-- this is the tr from above --
//use a loop if the HTML is all the same
for($i=1;$i<=5;++$i){
$key = 'col'.$i;
echo"<td class='rowDataSd'>".$test[$key]."</td>";
//simply add the values on each iteration (sum)
$totals[$key] += $test[$key];
}
echo "</tr>"; //-- without fixing the open tag as mentioned above, your HTML would be messed up --
}
mysql_close($conn);
echo '<tfoot>';
echo '<tr class="totalColumn">';
echo '<td>.</td>';
for($i=1;$i<=5;++$i){
echo '<td class="totalCol">total:'.$totals['col'.$i].'</td>';
}
echo '</tr>';
echo '</tfoot>';
...
If this stuff doesn't change dynamically (which it doesn't seem to), there is no need to do it with Javascript.
You can also reduce the code by using a simple for loop.
Cheers!

PHP/MYSQL - Fetch DB values from dropdown menu, then into table in same page

I'm building an exam management website and one of the pages I'm working on is for adding students to a course. I have a dropdown menu for the student number (which fetches values from a table), however I'd like to make it so that when the teacher selects the student number from the dropdown menu, that student's name and major appear on a table below. I have pretty much all the code for it however I can't seem to make it work. The way it is right now it shows the head of the table but it doesn't show any lines.
The errors are always in the lines where I declare $sql1 and $sql2 and vary according to how I define the condition in the statement.
Code for my dropdown menu : (works fine)
<label class="control-label" for="number">Student Number</label>
<?php
$sql = "SELECT number FROM students";
$result = $conn->query($sql);
echo "<select class=".'"form-control"'.' id="number" name="number" for="number">';
while ($row = $result->fetch_assoc()) {
echo '<option value="' . $row['number'] . '">' . $row['number'] . "</option>";
}
echo "</select>";
?>
Code for my table : (shows only head of table, which is the best I got after moving around the code and getting conversion errors and such)
The errors are always in the lines where I declare $sql1 and $sql2 and vary according to how I define the condition in the statement.
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Major</th>
</tr>
</thead>
<tbody>
<?php
$sql1 = "SELECT name FROM students WHERE number='$row'";
$result1 = $conn->query($sql1);
$value = $result1->fetch_object();
$sql2 = "SELECT major FROM students where number='$row'";
$result2 = $conn->query($sql2);
$value1 = $result2->fetch_object();
echo "<tr>
<td>".$value."</td>
<td>".$value1."</td>
</tr>";
?>
</tbody>
</table>
Thank you for all your help!!
Before I can formulate a complete answer, I must advise you that there are a few logical errors in your code.
How does your page "know" that a user selected an option from the select? You should perhaps intercept the event and respond to that using an asynchronoys mechanism, e.g. via AJAX.
Anyhow, there's no need to run two queries when you can make it with just one:
SELECT name, major FROM students WHERE number = ...
Once you have described how you mean to address issue #1 we can continue discussing the complete solution.
Well, I think there will be no $row in the the second snippet.
It seems that you didn't pass your $row from 1st snippet to 2nd snippet.
You can read this:
PHP Pass variable to next page
You can use session, cookie, get and post.
Or can just simply use "include", then the variables you defined can be used in the second page.
<?php
include "page1.php";
?>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Major</th>
</tr>
</thead>
<tbody>
<?php
$number = $row['number'];
$sql1 = "SELECT name, major FROM students WHERE number='$number'";
$result1 = $conn->query($sql1);
$value = $result1->fetch_object();
echo "<tr>
<td>".$value['name']."</td>
<td>".$value['major']."</td>
</tr>";
?>
</tbody>
</table>
According to godzillante's answer below, the mysql query should be like this:
Anyhow, there's no need to run two queries when you can make it with just one:
SELECT name, major FROM students WHERE number = ...
I notice that you use $row as the key of your second query.
But in the first snippet, the data you fetch is "$row" (it is an array, see PHP - fetch_assoc)
You should use $row['number'] instead.

PHP echoing MySQL data into HTML table

So I'm trying to make a HTML table that gets data from a MySQL database and outputs it to the user. I'm doing so with PHP, which I'm extremely new to, so please excuse my messy code!
The code that I'm using is: braces for storm of "your code is awful!"
<table class="table table-striped table-hover ">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Description</th>
<th>Reward</th>
<th>Column heading</th>
</tr>
</thead>
<tbody>
<?php
$con = mysql_connect("localhost", "notarealuser", 'notmypassword');
for ($i = 1; $i <= 20; $i++) {
$items = ($mysqli->query("SELECT id FROM `items` WHERE id = $i"));
echo ("<tr>");
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['id'];
}</td>");
$items = ($mysqli->query("SELECT name FROM `items` WHERE id = $i"));
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['name'];
}</td>");
$items = ($mysqli->query("SELECT descrip FROM `items` WHERE id = $i"));
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['descrip'];
}</td>");
$items = ($mysqli->query("SELECT reward FROM `items` WHERE id = $i"));
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['reward'];
}</td>");
$items = ($mysqli->query("SELECT img FROM `items` WHERE id = $i"));
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['img'];
}</td>");
echo ("</tr>");
}
?>
</tbody>
</table>
However, this code is not working - it simply causes the page to output an immediate 500 Internal Server Error. IIS logs show it as a 500:0 - generic ISE. Any ideas?
You are mixing mysql and mysqli, not closing php code block and you are not selecting a database. Plus you don't have to run a query for each field
Try this:
<table class="table table-striped table-hover ">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Description</th>
<th>Reward</th>
<th>Column heading</th>
</tr>
</thead>
<tbody>
<?php
$con = new mysqli("host","user", "password", "database");
$execItems = $con->query("SELECT id, name, descrip, reward, img FROM `items` WHERE id BETWEEN 1 AND 20 ");
while($infoItems = $execItems->fetch_array()){
echo "
<tr>
<td>".$infoItems['id']."</td>
<td>".$infoItems['name']."</td>
<td>".$infoItems['descrip']."</td>
<td>".$infoItems['reward']."</td>
<td>".$infoItems['img']."</td>
</tr>
";
}
?>
</tbody>
</table>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Description</th>
<th>Reward</th>
<th>Column heading</th>
</tr>
</thead>
<tbody>
<?php
$con = mysqli_connect("hostname","username",'password');
$sql= "SELECT * FROM `items` WHERE id <20 ";
$items = (mysqli_query($sql));
while ( $db_field = mysqli_fetch_assoc($items) ) {?>
<tr><td><?php echo $db_field['id'];?></td></tr>
<tr><td><?php echo $db_field['name'];?></td></tr>
<tr><td><?php echo $db_field['descrip'];?></td></tr>
<tr><td><?php echo $db_field['reward'];?></td></tr>
<tr><td><?php echo $db_field['img'];?></td></tr>
<?php}
</tbody>
</table>
Try these, not tested
Where is the question?
There's many problems with this code.
First, you are confused between PHP and HTML.
Code between is PHP. It's executed on the server, you can have loops and variables and assignments there. And if you want some HTML there you use "echo".
Code outside is HTML - it's sent to the browser as is.
Second - what you seem to be doing is querying each field separately. This is not how you work with SQL.
Here's more or less what you need to do:
//Query all rows from 1 to 20:
$items = $mysqli->query("SELECT id,name,descrip,reward,img FROM `items` WHERE id between 1 and 20");
//Go through rows
while ( $row = mysqli_fetch_assoc($items) )
{
echo "<tr><td>{$db_field['id']}</td>";
//echo the rest of the fields the same way
});
I'm going to go ahead and assume that the code isn't working and that's because there's several basic errors. I'd strongly suggest doing some hard reading around the topic of PHP, especially since you're using databases, which, if accessed with insecure code can pose major security risks.
Firstly, you've set-up your connection using the procedural mysql_connect function but then just a few lines down you've switched to object-orientation by trying to call the method mysqli::query on a non object as it was never instantiated during your connection.
http://php.net/manual/en/mysqli.construct.php
Secondly, PHP echo() doesn't require the parentheses. PHP sometimes describes it as a function but it's a language construct and the parentheses will cause problems if you try to parse multiple parameters.
http://php.net/manual/en/function.echo.php
Thirdly, you can't simply switch from HTML and PHP and vice-versa with informing the server/browser. If you wish to do this, you need to either concatenate...
echo "<td>".while($db_filed = mysqli_fetch_assoc($item)) {
print $db_field['id'];
}."</td>;
Or preferably (in my opinion it looks cleaner)
<td>
<?php
while($db_filed = mysqli_fetch_assoc($item)) {
print $db_field['id'];
}
?>
</td>
However, those examples are based on your code which is outputting each ID into the same cell which I don't think is your goal so you should be inserting the cells into the loop as well so that each ID belongs to its own cell. Furthermore, I'd recommend using echo over print (it's faster).
Something else that may not be a problem now but could evolve into one is that you've used a constant for you FOR loop. If you need to ever pull more than 20 rows from your table then you will have to manually increase this figure and if you're table has less than 20 rows you will receive an error because the loop will be trying to access table rows that don't exist.
I'm no PHP expert so some of my terminology might be incorrect but hopefully what knowledge I do have will be of use. Again, I'd strongly recommend getting a good knowledge of the language before using it.

How do i display specific results from SQL database in a HTML TABLE using select menus

I've been at this for hours and i have gotten a slight break through, however i am at a stand still at the moment. I have a SQL Database that store vehicle information, such as make, model and year. What i want to do is allow users to modify the query and only display specific results.
I understand how to display all the records at once but what i want to add is when the user selects say for example the make as "Toyota" i want only that specific make to appear. I did reach some where in this, by using this code:
<form method="post" action="">
<div id="search_query" >
Make
<select name="make" size="0">
<option value="honda">Honda</option>
<option value="toyota">Toyota</option>
<option value="nissan">Nissan</option>
</select>
<input type="submit" name="submit" value="submit">
</div>
</form>
<?php
$db_con = mysql_connect('localhost', 'root', '');
if (!$db_con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('my_db', $db_con);
$make = mysql_real_escape_string($_POST['make']);
$sql = sprintf("SELECT * FROM chjadb_vehicles WHERE v_make= '$make' ");
$result = mysql_query($sql);
echo "<table width= 970 border=1>
<tr>
<th width='120' scope='col'>Image</th>
<th width='170' scope='col'>Details</th>
<th width='185' scope='col'>Seller</th>
<th width='126' scope='col'>Price</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td> <img src=" .$row['v_image']. " width =200 height = 130>" . "</td>";
echo "<td>". $row['v_year'] . " " . $row['v_make'] . " ". $row['v_model'] . " ". $row['b_type']. "</td>";
echo "<td>". $row['user_id'] ."</td>";
echo "<td>". $row['v_price'] ."</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($db_con);
?>
however when i run the page initially i get this error: "Notice: Undefined index: make in C:\xampp\htdocs\carhuntja.com\buy_a_car.php on line 62"
i did some research and realized that this was happening because i had no make value set, what i wish to do here is at the start of going to that page i want all vehicles to be displayed.
The problem is that the query is being sent before the user chooses a make. To fix this, you need check that the user has actually submitted the form by enveloping your PHP code in if(isset($_POST['submit'])) ("submit" is used because that is the name of your submit button).
//place connection code here (do not query the database yet)
if(isset($_POST['submit']))
{
//all of the database retrieval code
}
else
{
$query_makes = "SELECT v_make FROM chjadb_vehicles";
$result_makes = mysqli_query($query_makes);
echo "Please choose a make."
//echo opening select tag
while($row = mysql_fetch_array($result_makes))
{
//echo each option tag
}
//echo ending select tag
}
Also, you are missing a slash in the self-contained input tag.
Finally, you should use MySQLi functions because MySQL functions are deprecated in PHP.
When the page loads for the first time you need to run this query:
SELECT * FROM chjadb_vehicles
You need to check if the user clicked the submit button and posted the make field, to do that use isset():
if (isset($_POST['make']){
$make = mysql_real_escape_string($_POST['make']);
}
I strongly suggest you use jquery and ajax
EDIT:
First time the page loads you display all vehicles.
In your javascript you bind a onSelect evvent to the dropdown and once the user selects a make, you send an ajax request to the server and display the new results from the server, so it'll look something like that:
$('#search_query select').change(function(){
//get the selected option text
var selectedVal = $(this).find('option:selected').text();
//send ajax request
$.ajax( {
url : url,
type : "POST",
data : selectedVal ,
dataType : 'json',
success : function(data) {//handle returned data}
})
});
I suggest you take a look here, for a complete VIDEO tutorial on jquery.

Categories