MYSQL DELETE multiple row doesnt work - php

This is delete.php
<?php
if(isset($_GET['id']) && !empty($_GET['id']))
{
$id = $_GET['id'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "DELETE FROM table WHERE memberid IN ('".$id."' )";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully" ;
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
}
?>
this is home.php
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "select memberid from table group by memberid having count(*) > 5";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Member ID: " . $row["memberid"]. " | <a href='javascript:void(0);' onClick='deleteId(".$row["memberid"].")'>reset</a><br>";
}
} else {
echo "0 results";
}
$conn->close();
<script>
function deleteId(id)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
alert(xmlhttp.responseText);
}
};
xmlhttp.open("GET", "delete.php?id=" +id, true);
xmlhttp.send();
//window.location.reload();
}
</script>
I'm trying to delete multiple row in a table by onclick from home.php unfortunately it doesnt work at all.
in the table row recorded many same memberid, so i'm trying to call by memberid and delete all of them in 1click
I'm new in php and mysql.
Thanks for the help.

$sql = "DELETE FROM table WHERE c ='$id'";

Try this:
$idArr = explode(",", $id);
$idStr = implode("','", $idArr);
$sql = "DELETE FROM table WHERE c IN ('$idStr' )";
Also, in your client side code,
Make sure that the id in deleteId() is alerting 012345 instead of 12345. Otherwise, convert the integer to string before calling deleteId().

You are sending in one id, so no need for using IN(), normal id = ? will delete all rows with that id. But you need to use bind parameters to stop someone from sending in something like 1 or 1=1 to delete all the rows in your table, don't trust the input even if it is sent from your javascript

Related

I am trying to run a query that takes value from one table and uses it as condition to fetch value or execute action on another table

I am trying to take the value of the topay column where torecieve equals to current session user id and use it to perform operation on the user table.
But it throws a syntax error
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "bazze2";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$merge = "SELECT topay FROM merge WHERE torecieve=$_SESSION[id]";
$sql = "UPDATE user SET topay2='10000000' WHERE 'id'=$merge";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
Use a prepared query, and use a join.
$sql = "UPDATE user AS u
JOIN merge AS m ON u.id = m.topay
SET u.topay2 = '10000000'
WHERE m.toreceive = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $_SESSION['id']);
if ($stmt->execute()) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $stmt->error;
}

Accessing two tables within same statement?

I'm trying to create an upvote system where, after checking to see if you're logged in and after getting your userid, it checks if the table has your userid with the postid already in it and if it does then it means it was already upvoted. I just want to know what's wrong in my code, this is being used for learning, I don't need any complex thing.
Code:
if (isset($_GET['upvote'])) {
if ($_SESSION["loggedin"] == true) {
$upvoteid = $_GET["upvote"];
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id FROM users WHERE username=".$_SESSION["loggedinusername"];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$userid = $row["id"];
}
$sql2 = "SELECT userid, postid FROM upvotedposts WHERE userid='".$userid."' AND postid='".$upvoteid."'";
$result2 = $conn->query($sql);
if (!$result2->numrows > 0) {
$sql = "UPDATE posts SET upvotes = upvotes + 1 WHERE id = ".$upvoteid;
if ($conn->query($sql) === TRUE) {
echo "Sucessfully upvoted";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
} else {
echo "Failed;
}
$conn->close();
}
}
When I do click the upvote button, it simply does nothing. The issue here is that as far as I know it looks like it would work but I may be forgetting something that I am unaware of or incorrectly using something.
You are missing a closing "
echo "Failed;
should be:
echo "Failed";

Executing php code by clicking a link

Good people i am stuck with an issue that i know has been discussed here before. I am displaying mysql data as a link and want to load more data from the database when a user clicks the link, I looked at all the previous questions and answers but i can't sort this one out. Here is how far i have managed to drag myself:
index.php:
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT topic FROM steps";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$topic = isset($_get['topic']);
$id = isset($_get['id']);
echo ''.$row['topic'].'<br/>';
}
}
$conn->close();
?>
moreinfo.php:
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = isset($_get['id']);
$sql = "SELECT * FROM steps WHERE id='$id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$topic = isset($_get['topic']);
echo "Description: " . $row['topic'] . "<br />";
}
}
else{
echo "123";
}
$conn->close();
?>
This doesn't give me any error, just that the hyperlinks on this line
echo ''.$row['topic'].'<br/>';
on index.php does not append an id ($id) to the hyperlink so that moreinfo.php can execute correctly.
I rily pray i'm making some sense here...
Use $_GET['id'] insted of $_get['id']
Correct usege of isset is looks like this
$id = isset($_GET['id'])?$_GET['id']:false
Always check if parameter which you will use next was really passed
$id = isset($_GET['id'])?$_GET['id']:false;
if(!$id)
die('id was not passed');
And last, you were overwriting variables from db with data from GET which should be on first page (probably copy and past )
$topic = isset($_get['topic']);
$id = isset($_get['id']);
here is your fixed code:
index.php
<?php
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: ".$conn->connect_error);
}
$sql = "SELECT * FROM steps";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
echo ''.$row['topic'].'<br/>';
}
}
$conn->close();
?>
moreinfo.php
<?php
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: ".$conn->connect_error);
}
$id = isset($_GET['id'])?$_GET['id']:false;
if(!$id)
die('id was not passed');
$sql = "SELECT * FROM steps WHERE id='$id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$topic = isset($_get['topic']);
echo "Description: ".$row['topic']."<br />";
}
} else {
echo "123";
}
$conn->close();
?>
sql table create statement
CREATE TABLE `steps` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`topic` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
Ok first thing first you are overwriting your id in this line
$id = isset($_get['id']);
so when you try to use it it holds bool value (true or false) instead of actual $id. And you do it in both of your files.

PHP if SteamID is equal to the MYSQL Row

It will not work. I'm trying like below.
if (($row["steamid"]) == $steamprofile['steamid']){
Below is full code snippet.
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$eh = $steamprofile[steamid];
$sql = "SELECT steamid FROM Main";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if (($row["steamid"]) == $steamprofile['steamid']){
echo "SteamID Is Equal and Created!";
}
}
} else {
echo "Nope?";
}
$conn->close();
?>
Ive tried various methods.
// Create connection
$conn = new mysqli("localhost", "root", "", "stackoverflow");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//assume 1
$steamprofile['steamid']=1;
// changes here single quote
$eh = $steamprofile['steamid'];
$sql = "SELECT steamid FROM Main";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
if (($row["steamid"]) == $steamprofile['steamid']){
echo "SteamID Is Equal and Created!";
}
}
} else {
echo "Nope?";
}
$conn->close();
?>
output is
SteamID Is Equal and Created!
Mysql Database------------
CREATE TABLE IF NOT EXISTS main (
steamid int(11) NOT NULL,
name varchar(500) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
--
-- Dumping data for table main
INSERT INTO main (steamid, name) VALUES
(1, 'test1'),
(2, 'test2');
I think your
$eh = $steamprofile[steamid];
should be changed to
$eh = $steamprofile['steamid'];
The comment by:
try echo $row["steamid"]) ."==". $steamprofile['steamid']; so you can print and check that. – Hardy Mathew
Worked. Thanks.

If variable is in db then stop- if variable is not- then enter it

i have been trying to get this script done for a while now - im kind of new to php and mysql but i have been trying to get this to check the db for the username and then if the username exists - stop checking the db and if it doesn't exists add it to the db.
here is my code:
//input from application
$test = "wheelsmanx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT mainusername FROM CCCpro_test";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row["mainusername"] === $test) {
echo "User Name Already In Use.";
}if($row["mainusername"] !== $test){
echo "this statement";
[code that inserts into db i can do this part myself]
}
}
$conn->close();
} else {
echo "0 results";
}
$conn->close();
The problem with your code is that you do the INSERT of the new name inside an if statement that has confirmed the existence of that user already. In addition I think you messed up your SELECT statement by selecting all the users.
Look into INSERT ON DUPLICATE for a better way to do it, or revise your code as below.
$sql = "SELECT mainusername FROM CCCpro_test WHERE mainusername = $test";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "User Name Already In Use.";
}
else{ //no rows selected therefore the user doesn't exist
[code that inserts into db i can do this part myself]
}
$conn->close();
PLEASE READ I have somewhere to go so I am being lazy so I did not bind the $test variable therefore DO NOT copy and paste this code without updating it to bind the $test variable. Please read this post about PDO and variable binding to prevent SQL injection.
here is my full working code if anyone needs it - it uses the post method - from an html form .... in case some one needs to hack it to pieces for something else
well guys i appreciate all of your help :D but i have found an answer or a way around it i suppose- i thought of it all night and day on how i could make it work and i came up with this
$servername = "127.0.0.1";
$username = "TESTUSER";
$password = "TESTPASS";
$dbname = "TESTDB";
$testusername = $_POST['mainusername'];
$testpassword = $_POST['mainpassword'];
//input from application
$test = $_POST['mainusername'];
$test2 = "0";
//Count switch
$countswitch = "0";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql1 = "INSERT INTO CCCpro_test ( mainusername, mainpassword ) VALUES ('$testusername','$testpassword' )";
$sql = "SELECT mainusername FROM CCCpro_test";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row["mainusername"] === $test) {
echo "Im Sorry Username Already In Use";
$countswitch ++;
}
}
if($countswitch == $test2){
echo "User Name Registered";
$db_handle = mysql_connect($servername, $username, $password);
$db_found = mysql_select_db($dbname, $db_handle);
if ($db_found) {
$result1 = mysql_query($sql1);
mysql_close($db_handle);
}
}
if ($countswitch == 3){
echo "this";
}
} else {
echo "0 results";
}
$conn->close();

Categories