Delete a database entry not working - php

I have two pages, the first shows all items from a particular field in a MySQL database:
DatabaseEntries.php
<?php
include('connect.php');
$result = mysqli_query($db, "SELECT * FROM names")
or die(mysqli_error($db));
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>Firstname</th> <th>lastname</th> <th>Email</th><th></th> ";
while($row = mysqli_fetch_array( $result )) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['firstname'] . '</td>';
echo '<td>' . $row['lastname'] . '</td>';
echo '<td>' . $row['email'] . '</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
?>
the second page contains the delete function:
Delete.php
<?php
include('connect.php');
// check if the 'id' variable is set in URL, and check that it is valid
if (isset($_GET['email']) )
{
// get id value
$email = $_GET['email'];
// delete the entry
$result = mysqli_query($db, "DELETE FROM names WHERE email=$email")
or die(mysqli_error($db));
// redirect back to the view page
header("Location: DatabaseEntries.php");
}
else
// if id isn't set, or isn't valid, redirect back to view page
{
header("Location: Error.php");
}
?>
I get the following error when trying to delete an item from the database:
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 '#gmail.com' at line 1
Can anyone tell me why? and what to do to fix it?
Thanks

Add quotes around the $email
DELETE FROM names WHERE email='$email'

Related

SQL Query to Delete in PHP

I have this below code but failing at getting it to delete the record, think i may be missing something.
<?php
//Open Database
class MyDB extends SQLite3
{
function __construct() {
$this->open('Name.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
}
//Select the Name Table
$sql =<<<EOF
SELECT * FROM Name;
EOF;
$ret = $db->query($sql);
// Display The Data In a Table
echo "<table border='1' cellpadding='10'>";
echo "<tr><th>First name</th> <th>Last Name</th> <th>Gender</th> <th></th>
<th></th></tr>";
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
echo "<tr>";
echo '<td>' . $row['FirstName'] . '</td>';
echo '<td>' . $row['LastName'] . '</td>';
echo '<td>' . $row['Gender'] . '</td>';
echo '<td>Delete
</td>';
echo "</tr>";
}
// check for id to be set and if it is delete the matching row from database
if (isset($_GET['id']))
{
// puts the id value in the variable
$id = $_GET['id'];
// delete the entry
$db->exec("Delete FROM Name WHERE VALUES TeamName=$id;");
header("Location: name.php");
} else {
header("Location: name.php");}
$db->close();
?>
Is there something im missing as it still wont delete the entire row from the db file. It displays the table perfect just fails to delete the matching id Record.
Other delete querie i have tried is
$db->exec("Delete FROM Name (FirstName, LastName, Gender) WHERE VALUES
FirstName=$id;");
You cannot delete some of the values, you can either update them or just delete the entire row.
Try
$db->exec("DELETE FROM Name WHERE TeamName=$id;");
and the other thing you need to do for safety is to escape the $id variable, otherwise it's trouble waiting to happen.
1) check whether the user you are using has the delete permission.
2)$db->exec("DELETE FROM Name WHERE TeamName = '".$id."'");

Data not required is being displayed

I have a form where the user enters data e.g. AXZAA QS1QS. This data is Posted to my PHP script. The PHP Script connects to a MYSQL database which contains at the moment 2 records.
The idea is that the PHP script will take the input and compare it to the records in the database. If the records exist they are displayed in a table on a web page otherwise, an error message is displayed.
I am having a number of problems with my PHP script and have modified my script a number of times. However, the thing I am having the biggest problem with is this:
When the form appears for the first time, the message record doesn't exist appears twice, this is before the user has entered any data and is seeing the form for the first time. See picture below.
After entering data (when the PHP script was partially working correctly), if there is a match i.e. records existed, along with the records in the table I would receive an error message telling me that records were not found. To see if I could resolve the problem I added code to tell me what records could not be found, the records that couldn't be found were the ones that were found and the other records from the database which I wasn't looking for. I know the SQL query in my PHP script tells the script to get everything from the database however, I would have thought the if statement would have fixed the problem.
Sorry about writing such a long problem and I hope it's not confusing.
enter code here
<?php
//Connect to the database connection file
require 'databaseconnection.php';
$searchBar=(isset($_POST['searchBar']) ? $_POST['searchBar'] :null);
$userdata = trim($searchBar);
$cleaned_data = preg_split('/[\s]+/', $userdata);
$sql = "SELECT DISTINCT * FROM atable_2";
$result = mysqli_query($database_connection, $sql);
echo "<table border>
<tr>
<th>Allocation</th>
<th>Codes</th>
<th>Names</th>
</tr>";
while($putdatabaseanswer_intoarray = mysqli_fetch_array($result)) {
$allocation_id = $putdatabaseanswer_intoarray["allocation"];
$codes_id = $putdatabaseanswer_intoarray["codes"];
$names_id = $putdatabaseanswer_intoarray["names"];
foreach($cleaned_data as $value) {
if($value==$codes_id) {
echo "<tr>";
echo "<td>" . $allocation_id. "</td>";
echo "<td>" . $codes_id . "</td>";
echo "<td>" . $names_id . "</td>";
echo "</tr>";
}
else
{
echo "<br />";
echo "One or more of the records have not been found: $codes_id";
echo"<br />";
}
}
}
echo "</table>";
?>
Wouldn't it be better to assign $searchbar after an if statement like
`<?php
//Connect to the database connection file
require 'databaseconnection.php';
if(isset($_POST['searchBar']))
{
$searchbar = $_POST['searchBar'];
$userdata = trim($searchBar);
$cleaned_data = preg_split('/[\s]+/', $userdata);
$sql = "SELECT DISTINCT * FROM atable_2";
$result = mysqli_query($database_connection, $sql);
echo "<table border>
<tr>
<th>Allocation</th>
<th>Codes</th>
<th>Names</th>
</tr>";
while($putdatabaseanswer_intoarray = mysqli_fetch_array($result)) {
$allocation_id = $putdatabaseanswer_intoarray["allocation"];
$codes_id = $putdatabaseanswer_intoarray["codes"];
$names_id = $putdatabaseanswer_intoarray["names"];
foreach($cleaned_data as $value) {
if($value==$codes_id) {
echo "<tr>";
echo "<td>" . $allocation_id. "</td>";
echo "<td>" . $codes_id . "</td>";
echo "<td>" . $names_id . "</td>";
echo "</tr>";
}
else
{
echo "<br />";
echo "One or more of the records have not been found: $codes_id";
echo"<br />";
}
}
}
echo "</table>";
}
else{
echo "<p>Please enter a search term</p>";
}
?>
You could then execute the MySQL query within that "if" statement rather than having it execute assuming there is a value

DELETE link does nothing in PHP when removing data from PHPMyAdmin

I have created a table in PHPMyAdmin, and I have connected to it via a localhost. My PHP code displays the data in a table.
I want to be able to delete a certain row, so I created a html/php link to delete the row within a table.
My problem is that whenever I press delete, the page just refreshes without an error but the record is still there.
Is there something missing within my code?
<?php
// Connect to the database
$username="root";$password="test";$database="products";
// Connect to the MySQL server and select the required database
$connection = new mysqli("localhost",$username,$password, $database);
$sql = "";
$sql = "SELECT * FROM products";
$ID = isset($row['ID']) ? $row['ID'] : '';{
$query = mysqli_query($connection, "DELETE FROM products WHERE ID=$ID");
}
$result = $connection->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<tr>\n";
echo "<td>" . $row['Name'] . "</td>\n";
echo "<td>" . $row['Description'] . "</td>\n";
echo "<td>" . $row['Price'] . "</td>\n";
echo "<td>" . $row['Cost_Price'] . "</td>\n";
echo "<td>" . $row['Stock'] . "</td>\n";
echo "<td>" . $row['EAN'] . "</td>\n";
?>
<td><a href="?mode=delete&ID=<?php echo $row["ID"]; ?>"
title="Delete <?php echo $row["ID"]; ?>">Delete</a></td>
<?php
echo "</tr>\n";
}
}
$stmt = $connection->prepare('SELECT * FROM products WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
$connection->close();
?>
Change
$ID = isset($row['ID']) ? $row['ID'] : '';{
$query = mysqli_query($connection, "DELETE FROM products WHERE ID=$ID");
}
To
if(isset($_GET['ID']) && ($_GET['mode'] == 'delete')) {
$ID = $_GET['ID'];
$query = mysqli_query($connection, "DELETE FROM products WHERE ID=$ID");
}
Explanations
When after clicking delete link, it comes to this line
$ID = isset($row['ID']) ? $row['ID'] : '';{.
Here, $row['ID'] is not set. So, $ID set to "" as you declared in your code. So, DELETE statement is not able to find that product which you wanted to delete.
Actually, in delete link. You are passing 2 variables. One is mode and other is ID of product. Catch those 2 variables through $_GET as I mentioned in my answer.
Quick Links
How to set $_GET variable
$_GET : PHP Manual

Use cookie to get id, perform inner join on matching fields

This is my first post, but I have found this forum to be very useful! I hope you can help me.
My conundrum is this: I have users log on and then rate each other. Once a user logs in, I want them to be able to see the ratings they made (this one I got working - the reviews I can select by a unique id generated by a form) and also see a summary of the ratings that they have received. This is where it seems to get tricky. I tried an inner join but it didn't produce any results.
Right now I have this part up above my html
<?php
include "connect.php";
if(isset($_COOKIE['ID_my_site']))
{
$username = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
while($info = mysql_fetch_array( $check ))
{
//if the cookie has the wrong password, they are taken to the login page
if ($pass != $info['password'])
{
header("");
}
//otherwise they are shown the admin area
else
{
echo "";
echo "";
}
}
}
else
//if the cookie does not exist, they are taken to the login screen
{
header("");
}
include "settings.php";
?>
And this part after my html
<?php
include('connect.php');
$result = mysql_query("SELECT r.user, r.rating1, r.rating2, r.rating3, u.username
FROM reviews r INNER JOIN users u ON r.user=u.username
WHERE r.user='$userid' ORDER BY r.user DESC")
or die(mysql_error());
echo "<table border='1' cellpadding='10'>";
echo "<tr>
<th></th>
<th>View Comments</th>
<th>Rating 1</th>
<th>Rating 2</th>
<th>Rating 3</th>
</tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr>";
echo '<td>View/Print</td>';
echo '<td>' . $row['rating1'] . '</td>';
echo '<td>' . $row['rating2'] . '</td>';
echo '<td>' . $row['rating3'] . '</td>';
echo "</tr>";
}
echo "</table>";
?>
Unfortunately, I don't get any results at all, though I see about 20 ratings for this person in the sql table.
It's also throwing a "Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in reviews.php on line 19" error.
There's probably a stupid mistake in there, but I'm getting codeblind and frustrated.
Thank you for any help!
if this is line 19:
while($row = mysql_fetch_array( $result )) {
echo "<tr>";
echo '<td>View/Print</td>';
echo '<td>' . $row['rating1'] . '</td>';
echo '<td>' . $row['rating2'] . '</td>';
echo '<td>' . $row['rating3'] . '</td>';
echo "</tr>";
}
you should use the position of the values inside the array like 1,2,3 .. and so on , not ratings1 ,ratings2 .. and so on.

Display result from database in two columns

EDIT: This is what I am trying to achieve: http://i.imgur.com/KE9xx.png
I am trying to display the results from my database in two columns. I'm a bit new to PHP so I haven't the slightest clue on how to do this. Can anybody help me with this? Thanks in advance.
Here is my current code:
include('connect.db.php');
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM todo ORDER BY id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// display records in a table
echo "<table width='415' cellpadding='0' cellspacing='0'>";
// set table headers
echo "<tr><td><img src='media/title_projectname.png' alt='Project Name' /></td>
<td><img src='media/title_status.png' alt='Status'/></td>
</tr>";
echo "<tr>
<td><div class='tpush'></div></td>
<td> </td>
</tr>"
while ($row = $result->fetch_object())
{
echo "<tr>";
echo "<td><a href='records.php?id=" . $row->id . "'>" . $row->item . "</a></td>";
echo "<td>" . $row->priority . "</td>";
echo "</tr>";
}
echo "</table>";
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
A good idea would be storing your data into a simple array and then display them in a 2-columned table like this:
$con = mysql_connect('$myhost', '$myusername', '$mypassword') or die('Error: ' . mysql_error());
mysql_select_db("mydatabase", $con);
mysql_query("SET NAMES 'utf8'", $con);
$q = "Your MySQL query goes here...";
$query = mysql_query($q) or die("Error: " . mysql_error());
$rows = array();
$i=0;
// Put results in an array
while($r = mysql_fetch_assoc($query)) {
$rows[] = $r;
$i++;
}
//display results in a table of 2 columns
echo "<table>";
for ($j=0; $j<$i; $j=$j+2)
{
echo "<tr>";
echo "<td>".$row[$j]."</td><td>".$row[$j+1]."</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
<table>
<tr>
<td>ProjectName</td>
<td>Status</td>
<td>ProjectName</td>
<td>Status</td>
</tr>
<?php
while($row = $result->fetch_object()) {
echo "<tr>";
echo "<td>".$row->ProjectName."</td>";
echo "<td>".$row->Status."</td>";
echo "<td>".$row->ProjectName."</td>";
echo "<td>".$row->Status."</td>";
echo "</tr>";
}
?>
</table>
This is the thing on picture. With a bit CSS you can manipulate the tds.
Your function should look similar to this:
$query = "SELECT *
FROM todo
ORDER BY id";
$result = $mysqli->query($query);
while($row = $result -> fetch_array()) {
$feedback .= "<tr>\n<td>" . $row['item'] . "</td><td>" . $row['priority'] . "</td>\n</tr>";
}
return $feedback;
Then, in your HTML have the <table> already setup and where you would normally insert your <td> and <tr> put <?php echo $feedback?> (where $feedback is the assumed variable on the HTML page that retrieves the $feedback from the function). This isn't a complete fix, your code is hard to read, but by starting here, you should be able to continue on the path filling in all the extra information you need for the table, including your CSS.

Categories