Unknown column ' ' in 'where clause - php

I have been scouring the stack-overflow site and tried most of the similar questions that had been asked/answered, but unfortunately none of the solutions have worked for me so far. I am trying to have a list that is being populated by an sql database (which is working) and then once selecting the item, hitting the "generate" button and grabbing the data from the table and posting ONLY the selected data into the table. Previously I had an issue where the tables where being populated with ALL the data from the weapons list. After working on it some I have am now getting the error "Unknown column (whichever weapon name I choose) in where clause 107 (which I am assuming is my line number). Any suggestions?
Here is the entirety of the form from populating the list from the database to trying to select the weapon from the list.
<form action="#" method="post">
<table class="table">
<thead>
Martial Weapon Name
</thead>
<tr>
<th>
<select name="Choosen">
<?php
echo'<option>Select Weapon</option>';
//Check if at least one row is found
if($result->num_rows >0){
//Loop through results
while($row = $result->fetch_assoc()){
//Display weapon info
$output = $row['weapon_name'];
echo '<option>'.$output.'</option>';
}
}
?>
</select>
</th>
</tr>
</table>
<input class="btn btn-default" type="submit" name="submit" value="Generate">
<h3>
Weapon
</h3>
<table class="table table-striped">
<tr>
<th>
Weapon Name
</th>
<th>
Weapon Type
</th>
<th>
Damage
</th>
</tr>
<?php
if (isset($_POST['submit'])) {
$selected_weapon = $_POST['Choosen'];
$choose = "SELECT
weapon_types_martial.id,
weapon_types_martial.weapon_name,
weapon_types_martial.weapon_type,
weapon_types_martial.weapon_damage
FROM weapon_types_martial WHERE weapon_types_martial.weapon_name = " . $selected_weapon;
$result = $mysqli->query($choose) or die($mysqli->error . __LINE__);
foreach ($result->fetch_assoc() as $item) {
//Display weapon
$show = '<tr>';
$show .= '<td>' . $item['weapon_name'] . '</td>';
$show .= '<td>' . $item['weapon_type'] . '</td>';
$show .= '<td>' . $item['weapon_damage'] . '</td>';
$show .= '</tr>';
//Echo output
echo $show;
}
}
?>
</table>
</form>
And lastly here is the screenshot of what I am getting

1)You will not get data in $_POST['choosen'] As you haven't pass value in dropdown(select)
2)In your database table may be field weapon_name is varchar so you have to pass it into single quote.
Change your code as below:
<form action="#" method="post">
<table class="table">
<thead>
Martial Weapon Name
</thead>
<tr>
<th>
<select name="Choosen">
<?php
echo '<option>Select Weapon</option>';
//Check if at least one row is found
if($result->num_rows >0){
//Loop through results
while($row = $result->fetch_assoc()){
//Display weapon info
$output = $row['weapon_name'];
echo '<option value="'.$output.'">'.$output.'</option>'; //<--------------change here
}
}
?>
</select>
</th>
</tr>
</table>
<input class="btn btn-default" type="submit" name="submit" value="Generate">
<h3>
Weapon
</h3>
<table class="table table-striped">
<tr>
<th>
Weapon Name
</th>
<th>
Weapon Type
</th>
<th>
Damage
</th>
</tr>
<?php
if (isset($_POST['submit'])) {
$selected_weapon = $_POST['Choosen'];
$choose = "SELECT
id,
weapon_name,
weapon_type,
weapon_damage
FROM weapon_types_martial WHERE weapon_name = '$selected_weapon'"; //<--------------change here
$result = $mysqli->query($choose) or die($mysqli->error . __LINE__);
if ($result->num_rows > 0) {
while($item = $result->fetch_assoc()) {
//Display weapon
$show = '<tr>';
$show .= '<td>' . $item['weapon_name'] . '</td>';
$show .= '<td>' . $item['weapon_type'] . '</td>';
$show .= '<td>' . $item['weapon_damage'] . '</td>';
$show .= '</tr>';
//Echo output
echo $show;
}
}
else
{
echo "No data found";
}
}
?>
</table>
</form>

You need to place quotes in your SQL query.
Try:
$choose = "SELECT
weapon_types_martial.id,
weapon_types_martial.weapon_name,
weapon_types_martial.weapon_type,
weapon_types_martial.weapon_damage
FROM weapon_types_martial WHERE weapon_types_martial.weapon_name = '" . $selected_weapon . "'";
Word of advice, this query is very unsafe. I suggest using a framework or library for database queries.

You need to give value inside single quotes,
$choose = "SELECT
weapon_types_martial.id,
weapon_types_martial.weapon_name,
weapon_types_martial.weapon_type,
weapon_types_martial.weapon_damage
FROM weapon_types_martial
WHERE weapon_types_martial.weapon_name = '" . $selected_weapon ."'";

$choose = "SELECT id, weapon_name, weapon_type, weapon_damage FROM weapon_types_martial WHERE weapon_name = '".$selected_weapon."'";
or
$choose = "SELECT weapon_types_martial.id, weapon_types_martial.weapon_name, weapon_types_martial.weapon_type, weapon_types_martial.weapon_damage FROM weapon_types_martial as weapon_types_martial WHERE weapon_types_martial.weapon_name = '" . $selected_weapon ."'";

The options in your select element don't have a value=.. attribute, meaning that nothing is present in your query.
So $_POST['Choosen'] will = ''.
Not to mention that you're trying to pass a string, so your query will need to be wrapped in ':
$choose = "SELECT id, weapon_name, weapon_type, weapon_damage FROM weapon_types_martial WHERE weapon_name = '".$selected_weapon."'";

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 list PHP table query as non repeatable heading

I have a PHP table which consists of three catagories:
finit "material"
disc "discription"
size "dimension"
Similar 'finit' comes in different 'disc' and 'size'
I would like to display the results in a way that 'finit' are displayed only once depending upon the quantity while 'disc' and 'size' are listed within the table under their associated 'finit'
I am able to display 'finit' only once if it contains multiple discriptions etc.
But the listings are not properly set within the table.
they are listed directly under 'finit' and horizontally listed.
<?php
include("connect.php");
$query = "SELECT * FROM prime order by finit asc";
$info = mysqli_query($conn, $query);
$finit = $rows['finit'];
?>
<table class="table table-striped">
<tr>
<th>Material</th>
<th>Discription</th>
<th>Dimension</th>
</tr>
<?php
while($rows = mysqli_fetch_assoc($info)):
if($rows['finit'] != $finit) {
echo '<tr><td>'.$rows['finit'].'</td></tr>';
$finit = $rows['finit'];
}
echo'<td>'.$rows['disc'].'</td>';
echo'<td>'.$rows['size'].'</td>';
endwhile;
?>
</table>
</div>
</body>
</html>
Your code was not generating correct HTML which may well explain the presentation issues. You would also have lost the first finit value. See comments in code
<?php
include("connect.php");
$query = "SELECT * FROM prime order by finit asc";
$info = mysqli_query($conn, $query);
// this will cause the first finit to be completely lost
//$finit = $rows['finit'];
$finit = NULL;
?>
<table class="table table-striped">
<tr>
<th>Material</th>
<th>Discription</th>
<th>Dimension</th>
</tr>
<?php
while($row = mysqli_fetch_assoc($info)):
echo '<tr>';
if($row['finit'] != $finit) {
echo '<td>'.$row['finit'].'</td>';
$finit = $row['finit'];
} else {
// when you dont print a finit, you need to output something in that column
echo '<td> </td>';
}
echo '<td>' . $rows['disc'] . '</td>';
echo '<td>' . $rows['size'] . '</td>';
echo '</tr>';
endwhile;
?>
</table>
UPDATE
To format the table so that the finit value is always on its own row followed by rows containing only the other 2 columns, you could try.
All you have to remember is that you have to output the same number of <td>'s on each line, so in this case 3, unless you use the colspan="2" attribute, but try that once you have the simple route working.
<?php
include("connect.php");
$query = "SELECT * FROM prime order by finit asc";
$info = mysqli_query($conn, $query);
// this will cause the first finit to be completely lost
//$finit = $rows['finit'];
$finit = NULL;
?>
<table class="table table-striped">
<tr>
<th>Material</th>
<th>Discription</th>
<th>Dimension</th>
</tr>
<?php
while($row = mysqli_fetch_assoc($info)):
if($row['finit'] != $finit) {
echo '<tr><td>'.$row['finit'].'</td><td> </td><td> </td></tr>';
$finit = $row['finit'];
}
echo '<tr><td> </td>';
echo '<td>' . $rows['disc'] . '</td>';
echo '<td>' . $rows['size'] . '</td>';
echo '</tr>';
endwhile;
?>
</table>

How can I use a select box in HTML to search for a specific user in the database and show that information on a table?

I have a select box that shows the names of all the users in the database, however, I need, using a "Find Button" on the selected user on the combo box, that the data attached to that user shows up on the table
Table that currently shows the data of all users
<table class="table table-hover">
<thead class="thead-dark"></thead>
<tr>
<th scope="col">Shift ID</th>
<th scope="col">Name</th>
<th scope="col">Origin</th>
<th scope="col">Destination</th>
<th scope="col">Date</th>
</tr>
</thead>
<?php
global $result, $query;
$sql = "SELECT * FROM shifts";
$result = $db->query($sql);
//Fetch Data form database
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["shift_id"]. "</td><td>" . $row["name"] . "</td><td>" . $row["origin"] . "</td><td>" . $row["destination"] . "</td><td>" . $row["date"] . "</td><td>"
. $row["password"]. "</td></tr>";
}
echo "</table>";
} else { echo "0 results"; }
?>
</table>
And here's the form that shows the users in the select box
<form name="form1" method="POST" action="">
<select name="getUser">
<?php
$res = mysqli_query($db, "SELECT * FROM shifts");
while ($row = mysqli_fetch_array($res))
{
?>
<option><?php echo $row ["name"]; ?></option>
<?php
}
?>
</select>
<button class="btn-primary rounded">Find</button>
</form>
I'm trying to make it that so when the selected user in the combo box and the find button is pressed, that the data found goes all into the table described above.
I was maybe gonna try to attach a variable to the select box and compare it with the names field on the database.
Something like this
$query = "SELECT * FROM shifts WHERE $name == $nameSelected ";
Thanks.
first echo the user id into the option's value
<option value-"<?echo your id?>"><?php echo $row ["name"]; ?></option>
then when your form submits you get get the value from the $_POST
$userId = $_POST['getUser'];
not you can use the variable to query the database, but you should NEVER put it straight in, you should use PDO prepared statements to prevent injection.
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
//something like this
$query = $conn->prepare("SELECT * FROM shifts WHERE id = :id");
$query->bindParam(':id',$userId,PDO::PARAM_INT);
$query->execute()
return $query->fetchAll();// I realised you wanted to get all the shifts so you don want fetchAll(),
notice that in mysql we only use a single = for our comparison unlike php. Also i've changed name to the unique row in the database, as unless your name field is unique how do you know which use called Dan you want?
If you want to do this without re-loading the whole page you will need to look into using Ajax and passing the value of the option tag via jQuery.
Here are some places to start:
https://www.w3schools.com/php/php_mysql_connect.asp
https://www.w3schools.com/xml/ajax_intro.asp
if you are not comfortable with javascript (AJAX), try on your form
<?php $res = mysqli_query($db, "SELECT * FROM shifts"); ?>
<form name="form1" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>"
<select name="getUser">
<option value='All'>All</options>
<?php
while ($row = mysqli_fetch_array($res)) { ?>
<option value='$row ["name"]'><?php echo $row ["name"]; ?></option>
<?php } ?>
</select>
<button class="btn-primary rounded">Find</button>
</form>
And in your table
<table class="table table-hover">
<thead class="thead-dark"></thead>
<tr>
<th scope="col">Shift ID</th>
<th scope="col">Name</th>
<th scope="col">Origin</th>
<th scope="col">Destination</th>
<th scope="col">Date</th>
</tr>
</thead>
<?php
global $result, $query;
if ($_POST['getUser'] == 'All'){
$sql = "SELECT * FROM shifts";
} else {
$sql = "SELECT * FROM shifts WHERE name = " . $_POST['getUser'];
}
$result = $db->query($sql);
//Fetch Data form database
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["shift_id"]. "</td><td>" . $row["name"] . "</td><td>" . $row["origin"] . "</td><td>" . $row["destination"] . "</td><td>" . $row["date"] . "</td><td>"
. $row["password"]. "</td></tr>";
}
echo "</table>";
} else { echo "0 results"; }
?>
</table>

php-mysql - need to match two keywords which are supplementary to each other rather than independent ones

I have a database table cav in mysql.
I need to fetch result using php on the basis of two keywords which would search in two columns viz. 'caseno' and 'year'.
In the user form I provide two input fields namely 'keyword' and 'keyword1'.
Wish to show result only when keyword and keyword1 matched exactly with the values already exist in the column 'caseno' and 'year' (in a single row) in the database .
for example if user put 684 as keyword and 2007 as keyword1 query should fetch data of a row where value of caseno column is 684 and value of year column is 2007.
My problem is that suppose I am putting 684 as keyword and nothing in keyword1 even then it is showing the row containing 684, if I put 684 as keyword and 2010 as keyword1 even then it is showing row containing 684.
Wish to show the data of a row where 'caseno' is 684 (user defined keyword) and 'year' is 2007 (user defined keyword.
Have tried the following code:-
<?php
$db_host="";
$db_user="";
$db_pass="";
$db_name="";
$db = new mysqli($db_host, $db_user, $db_pass, $db_name);
if($db->connect_error){
die("Connection failed: " . $db->connect_error);
}
?>
<?php
if(!empty($_POST))
{
$aKeyword = explode(" ", $_POST['keyword']);
$bKeyword = explode(" ", $_POST['keyword1']);
$query ="SELECT * FROM cav WHERE caseno like '%" . $aKeyword[0] . "%' AND
year like '%".$bkeyword[0]."%'";
$result = $db->query($query);
if(mysqli_num_rows($result) > 0) {
$row_count=0;
echo '<br><br><br><br><br>
<center><table class="table-1 mt-2 table-responsive table border="1"
table-bordered"><TABLE BORDER=2 BORDERCOLOR=BLACK font size="2">
<tr>
<th>S.No.</th>
<th>Case Type</th>
<th>Case No.</th>
<th>Year</th>
<th>Petitioner Name</th>
<th>Respondent Name</th>
<th>First Coram</th>
<th>Second Coram</th>
<th>Third Coram</th>
<th>Written By</th>
</tr></center> ';
While($row = $result->fetch_assoc()) {
$row_count++;
echo "<tr><td> ".$row_count." </td><td>". $row['casetype'] . "</td><td>".
$row['caseno'] . "</td><td>". $row['year'] . "</td><td>".
$row['petitioner'] . "</td><td>". $row['respondent'] . "</td><td>".
$row['firstcoram'] . "</td><td>". $row['secondcoram'] . "</td><td>".
$row['thirdcoram'] . "</td><td>". $row['writtenbycoram'] . "</td>
</tr>";
}
echo "</table>";
}
else {
echo "<br>Result Found: NONE";
}
}
?>
html form is
<input type="text" name="keyword" autocomplete "off">
<input type="text" name="keyword1" autocomplete "off">
<input type="submit" value="Search"><FORM><INPUT Type="button"
VALUE="Back" onClick="history.go(-1);return true;">
Wish to show result only when values of both the columns i.e.'caseno' and 'year' match exactly to the keywords given by user. if user put only 684 or only 2007 or 684 and 2010 or 784 and 2007 it will show 'no result found'
I think this code here could solve your issue much easily since I see you were just missing a few points to make it work as you wanted. I have also made the rest code much better to manage
$html = '';
if(!empty($_POST))
{
$aKeyword = explode(" ", $_POST['keyword']);
$bKeyword = explode(" ", $_POST['keyword1']);
$query = 'SELECT * FROM cav WHERE caseno LIKE "%'.$aKeyword[0].'%" OR caseno LIKE "%'.$bKeyword[0].'%"';
$result = $db->query($query);
if(mysqli_num_rows($result) > 0) {
$row_count=0;
$html .= '<br><br><br><br><br>';
$html .= '<center><table class="table-1 mt-2 table-responsive table border="1"
table-bordered"><table border="2" bordercolor="black" font-size="2">';
$html .= '<tr>
<th>S.No.</th>
<th>Case Type</th>
<th>Case No.</th>
<th>Year</th>
<th>Petitioner Name</th>
<th>Respondent Name</th>
<th>First Coram</th>
<th>Second Coram</th>
<th>Third Coram</th>
<th>Written By</th>';
$html .= '</tr></center> ';
While($row = $result->fetch_assoc()) {
$row_count++;
$html .= '<tr><td> '.$row_count.' </td><td>'. $row['casetype'] . '</td><td>'.
$row['caseno'] . '</td><td>'. $row['year'] . '</td><td>'.
$row['petitioner'] . '</td><td>'. $row['respondent'] . '</td><td>'.
$row['firstcoram'] . '</td><td>'. $row['secondcoram'] . '</td><td>'.
$row['thirdcoram'] . '</td><td>'. $row['writtenbycoram'] . '</td>
</tr>';
}
$html .= '</table>';
}
else {
$html .= '<br>No results found';
}
}
echo $html;
Your problem was using AND instead of using OR

Increment database by 1, using UPDATE (mysql). What's wrong with my code?

I try to write code that receive a student ID as an input in student_list.php, and pass this ID to score.php.
At score.php, use that ID to match and pull out student's name from database, and display it here.
Then, below the name, there is an input field, for adding 1 score to database for this student.
But I got this message, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1".
Any help would be appreciated. Thank you.
student_list.php
<?php
include_once 'DBconnect.php';
?>
<html>
<head>Student List</head>
<body>
<form method="post" action="score.php">
<?php
$result = mysql_query("SELECT * FROM term3")
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>Student ID</th> <th>First Name</th> <th> Button </th> </tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr>";
echo '<td>' . $row['student_id'] . ' </td> ';
echo '<td>' . $row['student_fname'] . ' </td>';
echo '<td> <button type="submit" name="btn_student_id" value=" ' . $row['student_id'] . ' " >Select</button> </td>';
echo '</tr>';
}
echo "</table>";
?>
</form>
</body>
</html>
score.php
<?php
include_once 'database_connect.php';
?>
<html>
<head>Add Score</head>
<body>
<?php
$student_id = $_POST["btn_student_id"];
$result = mysql_query("SELECT * FROM term3 WHERE student_id=".$_POST['btn_student_id'])
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>Student ID</th> <th>First Name</th> </tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr>";
echo '<td>' . $row['student_id'] . ' </td> ';
echo '<td>' . $row['student_fname'] . ' </td>';
echo '</tr>';
}
echo "</table>";
if(isset($_POST['btn_add_score'])) {
$score = $_POST['score'];
mysql_query ("UPDATE term3 SET score = score + 1 WHERE student_id = ' ".$_POST['btn_student_id']. " ' ");
}
?>
<form method="post">
<table>
<tr>
<td>Score</td>
<td> <input type="number" name="score" size="8">
<button type="submit" name="btn_add_score" >Add</button>
</td>
</tr>
</table>
</form>
</body>
</html>
----------------------------------------
Student ID | Name | Select |
----------------------------------------
10001 | Pat | Button (submit) |
----------------------------------------
10002 | Jess | Button (submit) |
----------------------------------------
Try to remove the quotation marks around the student id in the update query. It is redundant
UPDATE term3 SET score = score + 1 WHERE student_id = ".$_POST['btn_student_id']);
Update
$result = mysql_query("SELECT * FROM term3 WHERE student_id=".$_POST['btn_student_id'])
to
$result = mysql_query("SELECT * FROM term3 WHERE student_id='".$_POST['btn_student_id']."'")

Categories