Priya Priya - 3 years ago 168
MySQL Question

select and delete row mysqli query

I want find that any row is available with provided parameter and want delete if there any such row with mysqli query. I am not PHP developer and trying to make simple API for my android application. I have written simple API like below but I have confusion in

$query= mysqli_query($conn,"DELETE FROM tbl_fav WHERE fav_id=");


My API is like below

<?php
header('Content-Type: application/json; Charset=UTF-8');
include("dbconnection.php");
$userid= $_GET['userid'];
$quoteid= $_GET['quoteid'];


$query= mysqli_query($conn,"SELECT fav_id FROM tbl_fav WHERE user_id='".$userid."' AND fav_qu_id= '".$quoteid."'");

if(mysqli_num_rows($query) > 0){

$query= mysqli_query($conn,"DELETE FROM tbl_fav WHERE fav_id=");
$response="deleted";

}
else{

$response= "no_data";

}
echo json_encode($response);
?>


Let me know how can I delete row that I get in result of first query.
Thanks

Answer Source

You need to fetch the data from your first query and then use it in your second query. Fetch with mysqli_fetch_array():

$query= mysqli_query($conn,"SELECT fav_id FROM tbl_fav  WHERE  user_id='".$userid."' AND fav_qu_id= '".$quoteid."'");

if(mysqli_num_rows($query) > 0){

    $row=mysqli_fetch_array($query, MYSQLI_ASSOC); // fetch the data
    $query= mysqli_query($conn,"DELETE FROM tbl_fav WHERE fav_id= $row['fav_id']");
    $response="deleted";

} else {

    $response= "no_data";

}

echo json_encode($response);

Once you have fetched the data you can use it in the subsequent query.

Warning!

Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download