can not delete database row using foreach loop - php/mysql - php

I trying to delete some data from three tables,
1:- ailments
2:- jnctn_ailments_symptoms
3:- symptoms
I tried to delete the Link first from Junction Table, Then Delete The Ailment (vise versa too) and then final check the symptoms for any other link with another ailment, if not delete the symptom from symptom table.
but I am failing at on step in foreach loop, I am checking the occurrences for symptoms beside the ailment deleted. everything is fine but when it comes to deleting the symptom I get mysql error " 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 '' at line 1".
I the ids for the symptoms are retrieved successfully but not delete query not working, somehow.
please see the following code and let me know where I am mistaken.
if(isset($_GET['del']))
{
$delID = $_GET['del'];
$originalSymptoms="";
$symptomO[] = array();
echo $delID;
$symp = "SELECT symptomID FROM symptoms
INNER JOIN jnctn_ailments_symptoms
ON jnctn_ailments_symptoms.FK_symptomID= symptoms.symptomID
INNER JOIN ailments
ON ailments.ailmentID = jnctn_ailments_symptoms.FK_ailmentID
WHERE ailments.ailmentID IN ('".$delID."')";
mysql_select_db($dbName);
$sympRes = mysql_query($symp,$con) or die(mysql_error());
while($symprow = mysql_fetch_assoc($sympRes))
{
if(empty($originalSymptoms))
{
$originalSymptoms = $symprow['symptomID'];
}
else
{
$originalSymptoms = $originalSymptoms.",".$symprow['symptomID'];
}
}
echo $originalSymptoms;
$newSymptoms = explode("," , $originalSymptoms);
foreach($newSymptoms as $symptom)
{
$originalSymptomsArray[] = $symptom;
}
echo count($originalSymptomsArray);
$delAilment = "DELETE FROM ailments WHERE ailmentID='$delID'";
$delAilmentResult = mysql_query($delAilment,$con) or die(mysql_error());
$delLink = "DELETE FROM jnctn_ailments_symptoms WHERE FK_ailmentID ='$delID'";
$delLinkResult = mysql_query($delLink,$con) or die(mysql_error());
foreach($originalSymptomsArray as $symptom)
{
echo $symptom."<br>";
$sql2 = "SELECT * FROM jnctn_ailments_symptoms WHERE FK_symptomID=".$symptom;
$result2 = mysql_query($sql2,$con);
$count = mysql_num_rows($result2);
if(!$result2 || $result2 != 0)
{
echo mysql_error();
$delSymptom = false;
}
else
{
$delSymptom = true;
}
if($delSymptom)
{
$sqlDel = "DELETE FROM symptoms WHERE symptomID ='$symptom'";
$delResult = mysql_query($sqlDel,$con)or die(mysql_error());
if(!$delResult)
{
echo mysql_error();
}
else
{
echo "Symptoms Deleted!";
}
}
}
I have tried FK_symptomID='$symotom'"; , concatenation etc, nothing worked.

Try to concatenate all your queries mentioned as follows,
$sqlDel = "DELETE FROM symptoms WHERE symptomID ='".$symptom."'";

somehow following code worked
foreach($originalSymptomsArray as $symptom)
{
$sql2 = "SELECT `ID`, `FK_ailmentID`, `FK_symptomID` FROM `jnctn_ailments_symptoms` WHERE `FK_symptomID`='".$symptom."'";
$result2 = mysql_query($sql2,$con);
$count = mysql_num_rows($result2);
if($count>0)
{
echo mysql_error();
$delSymptom = 0;
}
else
{
$delSymptom = 1;
}
if($delSymptom==1)
{
$sqlDel = "DELETE FROM symptoms WHERE symptomID ='".$symptom."'";
$delResult = mysql_query($sqlDel,$con)or die(mysql_error());
if(!$delResult)
{
echo mysql_error();
}
}
}
thank you for concatenation suggestion, and thank you everybody.

Related

Group By Not working - only displaying 1st entry

I have over 40'000 entries and each is assigned to a "list_name"
I am basically trying to get just the list_name value echo'd out
$groupq = mysqli_query($dbc, "SELECT * FROM `products-full` GROUP BY `list_name`");
$groupr = mysqli_fetch_assoc($groupq);
do {
echo $groupr['list_name'];
} while($groupr = mysqli_fetch_assoc($groupq));
however its only displaying 1 entry then no more ..
https://imgur.com/a/3rnXGet
Try this.
$groupq = mysqli_query($dbc, "SELECT * FROM `products-full` GROUP BY `list_name`");
while($groupr = mysqli_fetch_assoc($groupq)){
echo $groupr['list_name'];
}
$database = "sample" //replace your database name here
$conn=new mysqli("localhost","root","",$database); // here username is root and password is null , change it according to yours
if($conn->connect_error)
{
echo $conn->connect_error;
die("sorry database connection failed");
}
$sql = "SELECT * FROM products-full GROUP BY list_name";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row['list_name'];
}
}
thats it
try this
$groupq = mysqli_query($dbc, "SELECT list_name, count(*) FROM `products-full` GROUP BY
`list_name`");
while($groupr = mysqli_fetch_assoc($groupq)) {
echo $groupr['list_name'];
}

Check empty rows query

In fact I am working on a small PHP script but I am facing a problem right now.The problem is that i want to check if my query return records this is my mysqli query:
$sql = "select * from specs where btitleid=$id and phoneid=$aydi"
$check = $conn->query($sql)
while($row = $check->fetch_assoc()) {$tocheck = $row['content'];}
I don't want to check the number of rows of this query to see if it is null.I want to check if all $row['content'] are empty.
How about this:
$sql = "select * from specs where btitleid=$id and phoneid=$aydi";
$check = $conn->query($sql);
$contentAllEmpty = true;
while ($row = $check->fetch_assoc()) {
if (strlen($row['content']) > 0) {
$contentAllEmpty = false;
}
}
if ($contentAllEmpty) {
//do something
}
use ==
while ($row = $check->fetch_assoc()) {
if ($row['content'] == '') {
... code here
}
}
To get back only records where the content column is not empty -
$sql = "SELECT * FROM `specs` WHERE `btitleid` = $id AND `phoneid` = $aydi AND (`content` IS NOT NULL OR `content` != '') ";

php doesn't pass through any of the if statement and goes directly to the else statement

can someone tell me please whats wrong with this, i think i got everything right but my return value pops out everything which is my command for the last else command the if statements doesn't seem to work...
<?php
$con=mysqli_connect("localhost","root","password","d_database");
if (mysqli_connect_errno($con)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$images = array();
if(isset($_GET['mydata']) )
$mydata = $_GET['mydata'];
if(isset($_GET['category']) )
$category = $_GET['category'];
if($category == 'Users'){
$result = mysqli_query($con,"SELECT id, dish_name, dish_image, user_username FROM recipes WHERE user_username = '$mydata'");
}else if ($category == 'Recipes'){
$result = mysqli_query($con,"SELECT id, dish_name, dish_image, user_username FROM recipes WHERE dish_name = '$mydata'");
}else if ($category == 'Ingredients'){
$result = mysqli_query($con,"SELECT id, dish_name, dish_image, user_username FROM recipes WHERE user_username = '$mydata'");
}else{
$result = mysqli_query($con,"SELECT id, dish_name, dish_image, user_username FROM recipes");
}
while($row = mysqli_fetch_assoc($result)){
$images[] = $row;
}
echo "{images:".json_encode($images)."}";
mysqli_close($con);
?>
i was using a POST method im my forms
so thats why it was wrong... :(((
if(isset($_POST['mydata']) )
$mydata = $_POST['mydata'];
if(isset($_POST['category']) )
$category = $_POST['category'];
fix my problem

PHP Mysql select

I'm trying to select some rows from my database, and generate specific HTML where my selection finds something and other HTML when it does not.
This is my code. The problem is that it always finds no matches:
$pos = 0;
$con = mysqli_connect('localhost', 'user', 'pass', 'database');
if (mysqli_connect_error()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT * FROM table1 where user = 'user'")
or die("Error: ".mysqli_error($con));
while ($row = mysqli_fetch_array($result)) {
$result2 = mysqli_query($con,"SELECT * FROM table2 where id = '"
.$row['id']."'") or die("Error: ".mysqli_error($con));
$dbpos = $row['pos'];
while ($row2 = mysqli_fetch_array($result2)) {
if ($dbpos == $pos) {
echo 'found<br/>';
} else {
echo 'empty<br/>';
}
$pos++;
}
}
mysqli_close($con);
I always get empty. What am I doing wrong?
Try making your query something like
Select * from table1
inner join table2
on table1.id=table2.id
Where table1.user='user'
This will do what you want in 1 query
If you get 1 result print found. If you get 0 then print empty
If you just want to determine if your query has an empty result or how many result was found, you can use mysqli_num_rows and remove your second while loop ($result2).
$noofrows=mysqli_num_rows($result2);
if($noofrows==0){
echo "Empty<br>";
}
else {
echo "There are ".$noofrows." record/s found.";
}
Try this. SQL joins can be very efficient depending on how your tables are structured.
//Query the DB for all of the rows in table2 where the table2 id column value
// is equal to the value of the id column value in table1
$query = "SELECT table2.*
FROM table1
INNER JOIN table2
ON table1.id = table2.id
WHERE table1.user = 'user'";
$result = mysqli_query($con, $query)or die(mysqli_error());
If you're expecting to return more than one row, the following might come in handy
$count = mysql_num_rows($result);
$i = 0;
while($row = mysqli_fetch_array($result)) {
$dbpos[$i] = $row['pos'];
$i++;
}
for($i=0;$i<$count;$i++) {
if($dbpos[$i] == $pos) {
echo 'found<br/>';
} else {
echo 'empty<br/>';
}
}
If not, then simply do this
while($row = mysqli_fetch_array($result)) {
$dbpos = $row['pos'];
}
if($dbpos == $pos) {
echo 'found<br/>';
} else {
echo 'empty<br/>';
}
More info about SQL joins here.

PHP-MYSQL Cannot delete on mysqli_multi_query

I have two querys that have to delete rows on different tables when a checkbox is checked. The problem is that only executes one of the querys and ignores the other one.
Here's the code:
if(isset($_POST["che".$i.""])){
$query4 = "DELETE FROM gastos WHERE id_dedicaciondos = $idded AND id_usuario=$idu;";
$query4 .= "DELETE FROM dedicacio WHERE id_dedicacion = $idded AND id_usuario=$idu;" ;
if(mysqli_multi_query($connexio,$query4)){
do{
if ($result = mysqli_store_result($connexio)) {
mysqli_free_result($result);
}
}while(mysqli_next_result($connexio) && mysqli_more_results($connexio));
}
}
Only deletes the rows from the second query... If I change the order of the querys the result is exactly the same, only deletes from the query "delete from dedicacio".
What can I do?
Thanks in advance
UPDATE
I've tried the next:
if(isset($_POST["che".$i.""])){
$query4 = "DELETE FROM gastos WHERE id_dedicaciondos = ".$idded.";";
$query5 = "DELETE FROM dedicacio WHERE id_dedicacion = ".$idded.";";
if(mysqli_query($connexio,$query4)){
echo "YES!";
}
if(mysqli_query($connexio,$query5)){
echo "YES2!";
}
}
It shows "YES!" and "YES2!" But the query don't delete anything on the "gastos" table :(
UPDATE
I solved by myself adding a "ON DELETE CASCADE" to the id_dedicaciondos that references id_dedicacions.
TRy to use this code:
if ($mysqli->multi_query($query4)) {
do {
if ($result = $mysqli->store_result()) {
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
Just tested this and it works fine:
<?php
$mysqli = new mysqli("localhost", "user", "pass", "testdb");
$query4 = "DELETE FROM test_table1 WHERE num = 0;";
$query4 .= "DELETE FROM test_table2 WHERE num = 0;";
$mysqli->multi_query($query4);
while ($mysqli->next_result()) {;} // flush queries
$mysqli->close();
?>

Categories