Unknown column 'chenzhen' in where clause - php

I have a PHP script that connects to a MySQL database using the mysqli extension to search for Blog Posts based on Username or ID. I created a VIEW called BlogSearch that uses joins form other tables to aggregate the information I need together that is represented like this:
The Tables it pulls from are called Profiles that has the User information, BlogPosts and BlogCategory
Everytime I search I get the error:
Unknown column 'chenzhen' in 'where clause'
The PHP code I'm using below:
require 'database.php';
$query = "SELECT * FROM BlogSearch";
echo <<<EOF
<form method='post' action='' style="padding: 30px 0;">
<table cellspacing="0" border="0" style="float: left;">
<tr>
<td>Search Blog Posts by Username/ID</td>
<td><input type="text" id="search" name="search" style="width: 300px;"/></td>
<td><input type="submit" id="submit_button" value="Search" name="submit_button" style="float: right;" /></td>
</tr>
</table>
</form>
EOF;
if(isset($_POST['submit_button']))
{
$search_term = $_POST['search'];
$query = $query . " WHERE `NickName` LIKE '%$search_term%' OR ID = $search_term ";
// run the query and store the results in the $result variable.
$result = $mysqli->query($query) or die(mysqli_error($mysqli));
}
if ($result) {
// create a new form and then put the results
// into a table.
echo "<form method='post' action='delete.php' style='clear: both;'>";
echo "<table cellspacing='0' cellpadding='15'>
<th width='5%'>
<input type='checkbox' id='allcb' onclick='checkAll(this)' name='allcb' />Check All
</th>
<th width='10%'>User</th>
<th width='85%'>Blog Post Title</th>
";
while ($row = $result->fetch_object()) {
$title = substr($row->PostCaption,0,50);
$id = $row->PostID;
$user = $row->NickName;
//put each record into a new table row with a checkbox
echo "<tr>
<td><input type='checkbox' name='checkbox[]' id='checkbox[]' value=$id />
<td>$user</td>
<td>$title</td>
</tr>";
}
// when the loop is complete, close off the list.
echo "</table><p><input id='delete' type='submit' class='button' name='delete' value='Delete Selected Items'/></p></form>";
}
I don't know why it's even identify the username as a column. Can anyone point me in the right direction to fix this?
Thanks in advance.

Any element in an SQL query that isn't an SQL keyword or a literal (denoted by single quotes), is assumed to be an object (e.g. table, column) name.
Your problem is the missing quotes around $search_term in your WHERE clause:
$query = $query . " WHERE `NickName` LIKE '%$search_term%' OR ID = $search_term ";
You should add them, as thus:
$query = $query . " WHERE `NickName` LIKE '%$search_term%' OR ID = '$search_term' ";

Enclose your $search_term in single quotes in where clause like this '$search_term'

Related

SQL Delete Row by id

I'm trying to delete a row in an SQL database by an id. I have found questions here related to this but nothing seems to work, perhaps because my page is populated (dynamically?) based on selecting a variable. The rows are displayed on my page based on a dropdown (locationlab) and I have a delete button after each row. It looks like this.
I have the Id displayed temporarily at the end of the row just be sure that the code sees the variable (& it does!).
The code to populate the page looks like this:
<?php
$locationlab = $_POST[locationlab];
$sql = "SELECT * FROM lab WHERE locationlab LIKE '{$locationlab}'";
echo($locationlab);
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo'
<table>
<form action=testpage2.php method=post>
<td width="10%"><input type=text name=make value='. $row["make"].'></td>
<td width="10%"><input type=text name=model value='. $row["model"].'></td>
<td width="20%"><input type=text name=hostname value='. $row["hostname"].'></td>
<td width="15%"><input type=text name=ipaddress value='. $row["ipaddress"].'></td>
<td width="20%"><input type=text name=ipmiipaddress value='. $row["ipmiipaddress"].'></td>
<td width="15%"><input type=text name=terminalserveraddress value='. $row["terminalserveraddress"].'></td>
<td width="10%"><input type=text name=locationlab value='. $row["locationlab"].'></td>
<td><input type=submit name=update value=update></td>
<td><input type=submit name=delete value=delete></td>
<td id=id name=id value='. $row["id"].'>'. $row["id"].'</td>
</table>
</form>';
}}
?>
I can input the SQL query below manually in the phpMyAdmin page so I know it is correct.
The code for the Delete button looks like this:
<?php
if(isset($_POST['delete'])) {
$deletequery = ("DELETE * FROM lab WHERE ='$_POST[id]'");
mysql_query($deletequery, $conn);
};
?>
When I click the delete button it appears to refresh the page but nothing changes. I imagine that if I can get the delete button working, the update will work in a similar fashion but for now I'm stumped.
<?php
if(isset($_POST['delete'])) {
$deletequery = ("DELETE FROM lab WHERE **columnName** ='$_POST[id]'");
mysql_query($deletequery, $conn);
}
?>
You are missing column name in query. Also there is no * in DELETE statement, because deleting means deleting row.
First of all let me help you in formatting the code
you should not write entire HTML code in echo...
instead try this one....
<?php
while($row = $result->fetch_assoc()) {
?>
<table>
<form action="testpage2.php" method="pos">
<td width="10%"><input type="text" name="make" value="<?= $row["make"] ?>"></td>
....
....
</table>
</form>
<?php
}
?>
also you should use mysqli instead of mysql
and your database query is also incorrect, it must be like this..
DELETE FROM lab WHERE id ='$_POST[id]'
if you use mysqli then you can also use some functions like this..
mysqli_query($con,$deletequery)
if(mysqli_errno($con))
{
echo("SOme error while executing query : ".mysqli_error($con));
}

Delete multiple mysql rows with check box not working

Here Is my problem: I do not get any error with my code but my problem is when i click the 'Delete Multiple' Button it does nothing not even reload the page.
Note: By The Way the redirect_to(); function i created so do not get confused by thinking that is a php function or anything
PHP Code:
display_errors(E_ALL);
if(isset($_POST['muldelete'])) {
$mul = $_POST['checkdelete'];
$sql = "DELETE FROM cmarkers WHERE id = " . $mul;
$result = mysqli_query($db, $sql);
redirect_to("elerts.php");
}
HTML Code:
<form action="elerts.php" method="post">
<table class="table table-striped">
<tr>
<td> </td>
<td>Date</td>
<td>Comment</td>
<td>Actions</td>
</tr>
<?php
$sql = "SELECT * FROM cmarkers";
$result = $db->query($sql);
while ($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><input type="checkbox" name="checkdelete[]" value="<?php echo $row['id']; ?>" /></td>
<td><?php echo $row['date']; ?></td>
<td><?php echo $row['comment']; ?></td>
<td>DeleteEdit</td>
</tr>
<?php
}
?>
<input type="submit" name="muldelete" value="Delete Multiple" />
</table>
</form>
Thank You
If you need more info please let me know
First, your code contain some attention and placements errors.
input between <table> outer of td's is incorrect.
You can't make a multiple delete if you generate one form by value to
delete.
Fix them.
Getting Array of muldelete
To all the checked inputs, you must add the array field symbol
to clusterize the name "muldelete" to a post array.
<td><input type="checkbox" name="checkdelete[]" value="<?php $row['id']; ?>" /></td>
PHP side
Now you can fetch whole deletion array, like this:
if(!empty($_POST["muldelete"]))
{
$mul = join(',', $_POST['checkdelete']);
// Using IN() to make only one query for all records instead of multiple
// ex: IN(3, 4, 54, 8)
$query = "DELETE FROM cmarkers WHERE id IN(".$mul.")";
$result = mysqli_query($db, $query);
redirect_to("elerts.php");
}
Security
If ID's are integer value, you can prevent string injection into the sql query
$mul = array_map(function($id)
{
return intval($id);
}, $mul);
Your button is outside the <form></form> tags, so it is not related to the form elements or the form method at all. Instead of having a different form for each checkbox you should surround the entire table with the form tags thus ensuring that all the checkboxes and the button are in the same form.
<form method='post' action='elerts.php'>
<table class="table table-striped">
...all your table data including checkboxes...
<input type="submit" name="muldelete" value="Delete Multiple" />
</table>
</form>
I think because You are closing form tag earlier than submit button.
Try to put whole table into and should work.
PHP should looks like
display_errors(E_ALL);
if(isset($_POST['muldelete'])) {
$mul = implode(',',$_POST['checkdelete']);
$sql = "DELETE FROM cmarkers WHERE id IN(" . $mul.")";
$result = mysqli_query($db, $sql);
redirect_to("elerts.php");
}

Give unique value for submit button

In my table each and every row has a cell with a submit button.
Here is my code
<?php
# Init the MySQL Connection
mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("selfie") or die(mysql_error()) ;
# Prepare the SELECT Query
$selectSQL = 'SELECT * FROM `image_upload` INNER JOIN user_table
ON image_upload.user_id=user_table.user_id WHERE flag="0" ORDER BY timestamp DESC';
# Execute the SELECT Query
if( !( $selectRes = mysql_query( $selectSQL ) ) ){
echo 'Retrieval of data from Database Failed - #'.mysql_errno().': '.mysql_error();
}else{
?>
<table border="2">
<thead id="head">
<tr>
<th id="head">User name</th>
<th>Category</th>
<th>Description</th>
<th>Image</th>
<th>Location</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
if (isset($_GET['submit'])) {
$mobile = $_GET['dmobile'];
$query = mysql_query("update image_upload set
flag='$mobile' " );
}
if (isset($_GET['submit'])) {
header("Location: imageManagement.php");
}
if( mysql_num_rows( $selectRes )==0 ){
echo '<tr><td colspan="4">No Rows Returned</td></tr>';
}else{
while( $row = mysql_fetch_assoc( $selectRes ) ){
echo "<tr>
<td>{$row['user_name']}</td>
<td>{$row['category']}</td>
<td>{$row['description']}</td>
<td ><img src='uploads/".$row['image']."'width=300px height=200px></td>
<td>{$row['location']}</td>
<td><form class=\"form\" method=\"get\"><label></label><br/>
<input class=\"input\" type=\"text\" name=\"dmobile\" value=\" {$row['flag']}\" />
<br>
<input class=\"submit\" type=\"submit\" name=\"submit\" value=\"update\" />
</form></td>
</tr>\n";
}
}
?>
</tbody>
</table>
<?php
In here when do changes and click on submit button of one row each and every rows are updated. How can I give unique value for each and every submit button.
Comment to answer, since OP said it works.
OP: "It's work. Thank you very much.... :) – Lanka"
Add this to your form:
<input type=\"hidden\" name=\"the_id\" value=\"{$row['id']}\" />
then add:
$theid = $_POST['the_id'];
then,
$query = mysql_query("update image_upload set flag='$mobile'
WHERE id = '$theid' " );
You may need to play around with it a bit, in the hidden input that is.
This is based on having an "id" column of course.
N.B.:
You should validate the user input (even if it's a hidden field)
Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
As it stands, you are using a deprecated MySQL library, which leaves you open to SQL injection.
else{
$counter=0 ;
while( $row = mysql_fetch_assoc( $selectRes ) ){
$value="Update ".$counter ;
$counter++ ;
echo "<tr>
<td>{$row['user_name']}</td>
<td>{$row['category']}</td>
<td>{$row['description']}</td>
<td ><img src='uploads/".$row['image']."'width=300px height=200px></td>
<td>{$row['location']}</td>
<td><form class=\"form\" method=\"get\"><label></label><br/>
<input class=\"input\" type=\"text\" name=\"dmobile\" value=\" {$row['flag']}\" />
<br>
<input class=\"submit\" type=\"submit\" name=\"submit\" value=\"".$value."\" />
</form></td>
</tr>\n";
}
}
I do not think the question is clearly framed but by replacing the else part of your code with the above code you will get different values for submit button ie., update 0,update 1 and so on.. Hope this helps.

Update Multiple rows at one time in PHP

I am trying to update multiple rows on submit of a form (in particular this one is the "hours" field.
I have it working but only one of the value updates vs all of them.
There is the possibility of having different values for each update.
The form code:
$query2 = "select * FROM work_hours WHERE formid = $formid ";
$result = $mysqli->query( $query2 );
$num_results = $result->num_rows;
if( $num_results > 0){
echo " <table border='0' align='center'>
<tr>
<td colspan='2' align='center'>
<strong> Time Away Break Down</strong>
</td>
</tr>
<tr>
<td align='center'>Date</td>
<td align='left'>Hours</td>
</tr>";
while( $row = $result->fetch_assoc() ){
extract($row);
echo " <tr>
<td class='hidden_sm' align='center'>
<input type='text' name='id' size='10' value='$id' class='dept' readonly style='width:30px;'>
<input type='text' name='date' size='40' value='$date' class='dept' readonly> <input type='text' name='end_date' size='40' value='$end_date' class='dept' readonly>
</td>
<td class='hidden_sm' align='left' >
<input type='text' name='hours' size='10' style='width:30px;' value='$hours' class='dept' >
</td>
</tr>
";
}
echo "<tr>
<td colspan='2' align='center'>
<input type='submit' name='Submit' value='Submit Request'>
</td>
</tr>
</form>
</table>";//end table
Submit Code:
$id = $_POST['id'];
$formid = $_POST['formid'];
$hours = $_POST['hours'];
include 'connect-db.php';
$stmt = $mysqli->prepare("UPDATE work_hours SET hours = ? WHERE formid = ?");
$stmt->bind_param('si',
$_POST['hours'],
$_POST['formid']);
$stmt->execute();
if ( $stmt ) {
echo "<p align='center'>Thank you, this request has been approved.<BR>You will be redirected in 5 seconds</p>";
} else {
echo "Error, you status cannot be updated. <BR> Please contact your system administrator.";
}
$stmt->close();
?>
Could anyone point me in the right direction to have all values update on submit, as I have had zero luck.
As well I do understand the need to prevent SQL Injections, and that I am working, so no need to remind me.
Thanks in advance!
Looks like you'll want to use a CASE statement as explained here:
How does MySQL CASE work?
Use a loop to build the statement and you're better off using the id as the identifier instead of formid, since the id is the unique value and you could have different results in the form.

Attempting to update results generated from a while loop

My main issue that I am running into is basically this:
I have a while loop that generates results from a query. With the results that have been generated, I want the ability to update the table the original query was from.
The query produces the expected results, but the table is not being updated when I click the REMOVE button. I am also trying to find a solution for the results to be updated after the UPDATE query executes...
<?php
$sql = "SELECT * FROM vehicles WHERE sold='n' ORDER BY year DESC";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
echo
"
<tr>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['year'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['make'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['model'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'><input type='submit' name='remove' value='REMOVE' style='background-color:#C33;color:white;padding:10px;border-radius:5px;width:70px'/></td>
</tr>";
if(isset($_POST['remove'])){
$removeSql = "UPDATE `table`.`vehicles` SET `display`='0' WHERE `vin`='{$row['vin']}'";
mysql_query($removeSql) or die('check that code dummy');
}
}
mysql_close($connection);
?>
That's a submit button, will not work without form tag. You can't do it this way.
You can write the remove code on a separate page and convert that submit button to normal button and pass vin id on click of that button and call that page using ajax.
Or if you don't know ajax and want to do it on that page itself then do it this way :
<?php
$sql = "SELECT * FROM vehicles WHERE sold='n' ORDER BY year DESC";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
echo
"
<tr>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['year'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['make'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>",$row['model'],"</td>
<td style='border-bottom-style:dotted;padding-top:10px;padding-bottom:10px;font-size:.9em'>
<form action="" method="POST">
<input type="hidden" name="vin_id" value="<?php echo $row['vin']; ?>">
<input type='submit' name='remove' value='REMOVE' style='background-color:#C33;color:white;padding:10px;border-radius:5px;width:70px'/>
</form></td>
</tr>";
}
if(isset($_POST['remove'])){
$removeSql = "UPDATE `table`.`vehicles` SET `display`='0' WHERE `vin`='".$_POST['vin_id']."'";
mysql_query($removeSql) or die('check that code dummy');
}
mysql_close($connection);
?>

Categories