cannot delete database mysql with php [duplicate] - php

This question already has answers here:
PHP Mysql delete Query not working properly
(3 answers)
Closed 3 years ago.
I tried to delete user from mysql database with this code
if (isset($_POST['user_delete'])) {
$key = $_POST['keyToDelete'];
$check = "DELETE FROM user WHERE id = ". $key or die(mysqli_error($connection));
$result2 = $connection->query($query);
if($result2->num_rows >0){
$query_delete = "DELETE FROM user WHERE id =". $key or die(mysqli_error($connection));
var_dump($query_delete);
} else {
}
but it don't want to delete my database. but the sql already right and I also got the id because I tried to var_dump it. please help what was wrong with my code

You have a few issues here,
Your or die(mysqli_error($connection)) is to the querystrings, not the actual queries. Besides, instead of manually checking for errors it's much better to configure to throw errors automatically. For this add the following line to the connection code:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
You attempt to delete it twice? Though the second query is never executed, you just define the querystring (and never run it).
num_rows is only usable on select-statements. You want affected_rows to check if the query actually deleted any data.
You're not using a prepared statement.
if (isset($_POST['user_delete'])) {
$key = $_POST['keyToDelete'];
$query = "DELETE FROM user WHERE id = ?";
$stmt = $connection->prepare($query);
$stmt->bind_param("s", $key);
$stmt->execute();
if ($stmt->affected_rows) {
echo "Deleted ".$stmt->affected_rows." rows";
} else {
echo "No rows matched the criteria.";
}
$stmt->close();
}

Related

How to show an error message if row is not present in SQL after a SELECT query? [duplicate]

This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 2 years ago.
I am trying to run a SELECT * FROM <table> WHERE <param> = <value> LIMIT 1 SQL query with MySQLi
I have built this code snippet, which works perfect if the input id is present in SQL DB.
$id = $_GET['id'];
// preparing and binding
$stmt = $conn->prepare("SELECT * FROM `testtable1` WHERE `userid` = ? LIMIT 1");
$stmt->bind_param("i", $id);
// setting parameters and execute
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
echo $row['email'] . '<br><br>';
What I want to know is, how would I know if the input id (which was passed along with the URL) is NOT present in the DB? Currently, If the ID's present in the DB, the email param's value shows up. But if it's not present, nothing shows up..
So with the above piece of code, how do check whether the input ID is correct or not - so if incorrect I could show an 'Incorrect ID' message there?
PHP like most programming languages has a language structure called if statement. An if statement expects a boolean value and if the value is true (or true-ish) then the following block of code is executed.
In PHP an empty array is considered to be false-ish so you can simply do the following to check if any value was returned by the SELECT statement:
$stmt = $conn->prepare("SELECT * FROM `testtable1` WHERE `userid` = ? LIMIT 1");
$stmt->bind_param("i", $id);
// setting parameters and execute
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if($row) {
echo $row['email'] . '<br><br>';
} else {
echo 'Incorrect ID - no value found in the database!';
}
The else block will be executed if the condition inside of if(condition) is false-ish. If there is a value returned by SQL then you will have a non-empty array in $row which will evaluate to true and the first block of code will be executed.
First thing to remember is that a valid query can return an EMPTY recordset. Meaning you are not looking for an error, but it is possible to get an empty result.
One way is to check the number of rows returned
$id = $_GET['id'];
$stmt = $conn->prepare("SELECT *
FROM `testtable1`
WHERE `userid` = ?
LIMIT 1");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->store_result();
if ( $stmt->num_rows > 0 )
$result = $stmt->get_result();
$row = $result->fetch_assoc();
echo $row['email'] . '<br><br>';
} else {
//no rows returned id must not exist
echo 'That use does not exist';
}

How to assign php variable in select statement where condition [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 3 years ago.
I tried various ways to get the id from database but I can't get that Please help me!
Below is my query :
$username = $_POST['username'];
$query = "SELECT id FROM wp_users WHERE user_login ='".$username."'";
$result=mysqli_query($conn, $query);
if(mysqli_num_rows($result) == 1)
{
while($row = mysqli_fetch_array($result))
{
$id = $row['id'];
}
}
echo $id;
Also I tried this:
$query = "SELECT id FROM wp_users WHERE user_login ='$username'";
You should, at the very least, be using prepared statements in your queries if you're passing them user-supplied data.
use prepared statements ? and bind_param
use bind_result to bind the column to a variable. This variable is now bound by reference which means it will be updated on every iteration of the loop.
it is important to realize that you want to access the $id variable inside the loop as you're iterating over the dataset. If you use it outside/below the loop you are only working with the final row of data because it is being overwritten on every iteration.
turn on error reporting
Finally, I left your loop in place but usually, you'd only have a single user for a given username so you could use mysqli_fetch_assoc - Single Result from Database by using mySQLi
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$username = $_POST['username'];
$query = "SELECT id FROM wp_users WHERE user_login = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($id);
while ($stmt->fetch()) {
echo "ID: $id\n";
}
$stmt->close();

mysql data existence code not working [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
i am trying to check a data existence from mysql table but following script not working. bellow my codes are provided please find out where is my mistake there.
<?php
//including the database files
include("../inc/settings.php");
$email = $_POST['email'];
$password = $_POST['password'];
$query = mysql_query("SELECT easy123 FROM users WHERE email=$email", $conn);
if (mysql_num_rows($query) != 0)
{
echo "Username already exists";
}
else
{
echo "this username not used";
}
?>
The error i am getting is-
Warning: mysql_query() expects parameter 2 to be resource, object
given in C:\xampp\htdocs\myfiles\Easy123\master\login.php on line 8
Warning: mysql_num_rows() expects parameter 1 to be resource, null
given in C:\xampp\htdocs\myfiles\Easy123\master\login.php on line 10
this username not used
First of all, make sure your database connection is correctly set up. The error you're getting clearly says that your $conn variable isn't a valid resource.
Also, use prepared statements and parameterized queries. Do not use PHP variables within your query string, it's not secure at all. Use instead PDO or MySQLi
Using PDO:
$stmt = $pdo->prepare('SELECT easy123 FROM users WHERE email = :email');
$stmt->execute(array('email' => $email));
foreach ($stmt as $row) {
// do something with $row
}
Using MySQLi:
$stmt = $dbConnection->prepare('SELECT easy123 FROM users WHERE email = ?');
$stmt->bind_param('s', $email);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
Your $query seems to be wrong. Try this:
$query = mysql_query("SELECT easy123 FROM users WHERE email='$email'", $conn);
Make sure $conn is properly defined aswell.

Email is already in database, returns as if it isn't

Here is some background information on what I'm trying to do here. I'm try to create a registration form for my website (successful so far until this point). Data can be entered into the DB. The only thing I'm trying to do now is prevent duplicate email/usernames from being entered into the db. Through much stackoverflow research, I have found and tested the following code:
$query = "SELECT COUNT(*) AS num_rows FROM users WHERE email = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s", $email);
if ($stmt->execute()) {
return $stmt->num_rows;
}
What I then do is following:
if(user_exists($user_email) > 0) {
echo "Email already exists!";
}
But is passes by this if statement as if the email does exist in the database!
The email I'm trying to enter, for my tests is testemail#testemailweb.com which is already in the database! Would someone possibly point out where I have messed up in my code? Is there a silly mistake that I could have possibly done when trying to perform this?
The fix for your particular problem here is by not using COUNT(*) as mentioned by John and not depend on mysqli_stmt->num_rows by using a buffered result set:
$query = "SELECT * FROM users WHERE email = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s", $email);
return $stmt->execute() && $stmt->store_result() && $stmt->num_rows > 0;
Addendum
The only thing I'm trying to do now is prevent duplicate email/usernames from being entered into the db
You will want to use table constraints to prevent this (not just from the app, but anything else that can access the database). This has the added benefit of guarding against race conditions.
ALTER TABLE users ADD UNIQUE(email);
This will raise an error if you attempt to insert a row with an email value that already exists. You can check for this error on the application side and do whatever you want with it.
Your query will always return 1 row. COUNT(*) will return a result set even if only to report no rows match your query. As a result user_exists() always returns 1.
Change your query to:
$query = "SELECT * FROM users WHERE email = ?";
Now if no rows match your query $stmt->num_rows will be 0 so user_exists() will return 0.
change:
if ($stmt->execute()) {
return $stmt->num_rows;
}
What I then do is following:
if(user_exists($user_email) > 0) {
echo "Email already exists!";
}
to
$j=0;
if ($stmt->execute()) {
$j= $stmt->num_rows;
} else {
echo "Email already exists!";
}

How to judge whether the SQL update statement to delete success [duplicate]

This question already has answers here:
How to test if a MySQL query was successful in modifying database table data?
(5 answers)
Closed 1 year ago.
I use the code to update data in mysql.But it always echo "sucess " whatever $id equal to any integer.
$id=isset($_GET['id'])?$_GET['id']+0:0;
$sql="update user set age=50 where id=".$id;
$result=mysql_query($sql,$con);
if($result)
echo "update sucess<br />";
else
echo "update failed";
You should use mysql_affected_rows() instead.
So that an you'll know that it made changes you want.
Obligatory note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Here's what it will look like in using mysqli:
if(isset($_GET['id'])) {
$con = new mysqli('localhost', 'username', 'password', 'database_name');
$id = $_GET['id'];
$sql = 'UPDATE user SET age = 50 WHERE id = ?';
$update = $con->prepare($sql);
$update->bind_param('i', $id);
$update->execute();
if($update->affected_rows > 0) {
echo 'updated';
} else {
echo 'nothing';
}
}

Categories