This question already has an answer here:
PHP PDO how to run a multiple query request?
(1 answer)
Closed 3 years ago.
I am trying to delete records from tables matching users ID while i delete the user. but somehow it deletes records only from the cv table.
what i am trying is
if($_GET['deluser'] !='1'){
$qr = "delete from members where member_id IN(".$_GET['deluser'].")";
$qr = "delete from company where caller_id IN(".$_GET['deluser'].")";
$qr = "delete from cv where agent_id IN(".$_GET['deluser'].")";
$st = $db->prepare($qr);
$st->execute();
header('Location: users.php?action=DELETED');
exit;
what could i be doing wrong?
In your case you overwrite the value in $qr every time so you need to execute it, everyone of them separately,
you need also to fix the SQL injection problem so you can fix it
by using bind your data in the execute method or by using bindParam
first, you need to add ? with the same number of input you want to pass
you can check how it work here in this answer
$in = str_repeat('?,', count(explode(',', $_GET['deluser'])) - 1) . '?';
$qr = "delete from members where member_id IN($in)";
$st = $db->prepare($qr);
$st->execute(explode(',', $_GET['deluser']));
$qr = "delete from company where caller_id IN($in)";
$st = $db->prepare($qr);
$st->execute(explode(',', $_GET['deluser']));
$qr = "delete from cv where agent_id IN($in)";
$st = $db->prepare($qr);
$st->execute(explode(',', $_GET['deluser']));
You can read more about BindParam and Execute in the docs
Related
This question already has answers here:
PDO multiple queries
(1 answer)
PDO Transaction statement with insert and fetch output error
(1 answer)
Closed 1 year ago.
$sql = "INSERT INTO book (bookname) values('kkkkkkkkk');
SET #bookid = LAST_INSERT_ID();
INSERT INTO paper (papername) values('hhhhhhh');
SET #paperid = LAST_INSERT_ID();
UPDATE author SET bookid = #bookid, paperid = #paperid WHERE id = 11;
SELECT #bookid as bookid, #paperid as paperid FROM DUAL;"
$stmt = $pdoConnect->prepare($sql);
$stmt->execute();
$numofnewParn =$stmt->rowCount();
if($numofnewParn>0){
$newParentDt = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($newParentDt);
}
I have set of inserts with LAST_INSERT_ID assigned to respective parameters.
Later, updating a table with the parameters.
until $stmt->execute(); is not problem.
My question is can I continue the query by adding SELECT and fetch the data like $stmt->fetch(PDO::FETCH_ASSOC)?
or does it not make sense? if so, is there any source?
because above code does not print out.
You need to use PDOStatement::nextRowset see here to move onto the next queries result in your multi statement... however a cleaner setup would be to break this down into single statement queries and use PHP variables to save your bookid and paperid values:
<?php
$sql = "INSERT INTO book (bookname) values('kkkkkkkkk');"
$stmt = $pdoConnect->prepare($sql);
$stmt->execute();
$bookid = $pdoConnect->lastInsertId();
$sql = "INSERT INTO paper (papername) values('hhhhhhh');"
$stmt = $pdoConnect->prepare($sql);
$stmt->execute();
$paperID = $pdoConnect->lastInsertId();
$sql = "UPDATE author SET bookid = $bookid, paperid = $paperid WHERE id = 11;"
$stmt = $pdoConnect->prepare($sql);
$stmt->execute();
This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
So I'm building a website and i need to access a table which holds the information about products
I'm using to navigate to the page
<a href="productDetails.php?table=FeaturedProducts&id=1" >
then in products details page I'm using this to run the php query
<?php
require "connection.php";
$table = $_GET["table"];
$id = $_GET["id"];
$sql = "select * from '.$table.' where ID = '.$id.'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
$pname= $row['Product_name'];
?>
this doesn't seem to work please tell me how i can do this.
You made mistake in your concatenation of string. Take a look to your code here :
$sql = "select * from '.$table.' where ID = '.$id.'";
You try to concatanate the $table and $id variable. (we agree it's a SQL Injection problem).
But PHP will interpret the string result like this : select * from '.FeaturedProducts.' where ID = '.1.'
So you have the ' are not necessary in your code for the table name, and it's add point to your values. Because MySQL does to give you error message.
So your correct code will be (and make modification for use prepare statement to avoid SQL Injection) :
$sql = "select * from $table where ID = '$id'";
I created a matching game and stored it score in the database. So every time a user finishes the game, his score is updated in the database replacing the old score.The problem is, I wanted to add the new score with the old score and save it in a new column. I tried something like the below code:
if(isset($_POST['gamescore'])){
$username=$_SESSION['username'];
$fetch = "SELECT * FROM users WHERE username='$username'";
$fetchid =mysqli_query($db, $fetch);
while ($row=mysqli_fetch_array($fetchid)){
$id = $row['id'];
$username=$row['username'];
$gamescore= $_POST['gamescore'];
$updatescore= "UPDATE users SET score='$gamescore' WHERE id = '$id'";
mysqli_query($db, $updatescore);
$addscore= "SELECT sum(score='$gamescore') AS sum_score FROM users WHERE id='$id'";
mysqli_query($db,$addscore);
$finalscore="UPDATE sum_score SET sum_score = sum(score='$gamescore') WHERE id='$id'";
mysqli_query($db,$finalscore);
}
}
when I run the above code, score column gets updated by the new score, each time the player finishes the game but the sum of the old score and new score is not happening, I would appreciate if someone could help me with this problem.
The database table has columns "username", "id" , "password", "score" and "sum_score".
You can do everything in your code with one query. As has been mentioned in the comments, you should use prepared statements to protect yourself from SQL injection. Try something like this:
if (isset($_POST['gamescore'])) {
$sql = "UPDATE users
SET score = ?,
sum_score = sum_score + ?
WHERE username = ?";
$stmt = $db->prepare($sql);
$stmt->bind_param("iis", $_POST['gamescore'], $_POST['gamescore'], $_SESSION['username'])l
$stmt->execute();
}
The portion that is trying to delete duplicate entries in the database seems incorrect. So I suppose I am asking what would be the correct way to do that in this example. I am not totally new to PHP , but this is beyond me. If you could please tell me what is wrong and how to fix that would be greatly appreciated.
Now on to what I am trying to accomplish. I have a multidimensional array filled with values that is generated by a function. What I am trying to do is if there is a value in the array that already exists in the database delete it. Code:
enter code here
if(is_array($items)){
$values = array();
foreach($items as $row => $value){
$rsn = mysqli_real_escape_string($connect, $value[0]);
$rank = mysqli_real_escape_string($connect, $value[1]);
$values[] = "('', '$rsn', '$rank', '')";
$sql = "SELECT id FROM users WHERE rsn = :rsn";
$query = $conn->prepare($sql);
$query->execute(array(":rsn" => $value[0]));
$results = $query->rowCount();
while($deleted = $query->fetch(PDO::FETCH_ASSOC)){
$sql = "DELETE FROM users WHERE id = :id";
$query = $conn->prepare($sql);
foreach($deleted as $delete){
$query->execute(array(':id' => $delete));
}
}
}
//user_exists_delete($conn, $rsn);
$sql = "INSERT INTO users(id, rsn, rank, points) VALUES ";
$sql .= implode(', ', $values);
if(!empty($rank)&& !empty($rsn)){
if(mysqli_query($connect, $sql)){
echo "success";
}else{
die(mysqli_error($connect));
}
}
}
EDIT: I have got it partially working now, just need it to delete all dupes instead of only one. I edited code to reflect changes.
There are a couple problems, if you didn't strip much of your original code and if you don't need to do more than just what you shown why not just send a delete instruction to your database instead of checking validity first?
You have
//Retrieve ID according to rsn.
$sql = "SELECT id FROM users WHERE rsn = :rsn ";
//Then retrieve rsn using rsn??? Useless
$sql = "SELECT rsn FROM users WHERE rsn = :rsn ";
//Then delete using ID, retrieved by rsn.
$sql = "DELETE FROM users WHERE id = :id";
All those could simply be done with a delete using rsn...
$sql = "DELETE FROM users WHERE rsn = :rsn";
The row won't be deleted if there are no rows to delete, you don't need to check in advance. If you need to do stuff after, then you might need to fetch information before, but if not, you can use that while still checking the affected rows to see if something got deleted.
Now, we could even simplify the script by using only one query instead of one per user... We could get all rsn in an array and then pass it to the DELETE.
$sql = "DELETE FROM users WHERE rsn in :rsn";
//Sorry not exactly sure how to do that in PDO, been a while.
I fixed it I just omitted the WHERE clause in the delete statement so all records are being deleted before that insert gets ran again.
I need help finishing this statement. It is frustrating that two of the PHP phone books here gloss over PDO's almost all together.
All I need to do is check the database for a username that is already taken.
Here is the start of the statement.
$sql = " SELECT * FROM users WHERE userid = '$userid'";
$result = $dbh->query($sql);
What parts do I need to add to write my 'if' statement?
Something like this:
$sql = " SELECT * FROM users WHERE userid = '$userid'";
$result = $dbh->query($sql);
$row = $result->fetch();
if ($row)
echo 'Userid is taken';
I'm not sure about your question because you're asking about username but selecting userid... did you mean to select on username?