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();
?>
Related
When Inserting data into SQL it inserts two into rows, and I don't know why.
most probably of the if statement I added after the results you can find it as my comment:
// id_no update
And I used the select query two times to fetch the id and make it an auto-increment thing.
my table:
<?PHP
$query = "SELECT id_no FROM db_name ORDER BY id_no DESC";
$result = mysqli_query($con,$query);
$row = mysqli_fetch_array($result);
$lastid = $row['id_no'];
if(empty($lastid))
{
$number = "SX000001";
}
else
{
$idd = str_replace("SX", "", $lastid);
$id = str_pad($idd + 1, 6, 0, STR_PAD_LEFT);
$number = 'SX'.$id;
}
?>
<?PHP
if(isset($_POST['add_id']))
{
$id_no = mysqli_real_escape_string($con,$_POST['id_no']);
$sql="INSERT INTO `db_name`(`id_no`) VALUES ('$id_no')";
$result=mysqli_query($con,$sql);
// id_no update
if(mysqli_query($con,$sql))
{
$query = "SELECT id_no FROM db_name ORDER BY id_no DESC";
$result = mysqli_query($con,$query);
$row = mysqli_fetch_array($result);
$lastid = $row['id_no'];
if(empty($lastid))
{
$number = "SX000001";
}
else
{
$idd = str_replace("SX", "", $lastid);
$id = str_pad($idd + 1, 6, 0, STR_PAD_LEFT);
$number = 'SX'.$id;
}
}
else
{
echo "Record Faileddd";
}
if($result)
{
$success="Post has been added successfully";
} else
{
$error="Something went wrong!";
}
$id_no = '';
}
?>
You should check if $resultĀ is truthy to see if the insertion succeded (without running another query):
$id_no = mysqli_real_escape_string($con,$_POST['id_no']);
$sql="INSERT INTO `db_name`(`id_no`) VALUES ('$id_no')";
$result=mysqli_query($con,$sql);
// id_no update
if($result)
{
...
}
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.
I've been trying to execute a multiple query, so I've searched for a better approach on how to do this and I've read this mysqli_multi_query in php.
I tried it on my own to see the results, but it keeps on giving me error. Here's the code:
$studid = $_GET['stud_id'];
$classcode = $_GET['class'];
$conn = new MySQLi($host, $username, $password, $dbname) or die('Can not connect to database');
$sql = "SELECT * FROM tbl_students WHERE stud_id = '".$studid."'";
$sql.= "SELECT * FROM tbl_classes WHERE class_code = '".$classcode."'";
if (mysqli_multi_query($conn, $sql)) {
do {
/* store first result set */
if ($result = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_row($result)) {
$studname = $row[3].", ".$row[1];
}
mysqli_free_result($result);
}
/* print divider */
if (mysqli_more_results($conn)) {
printf("-----------------\n");
$studname = $row['fname'];
}
} while (mysqli_more_results($conn));
}else{ echo "error";}
$conn->close();
With the code above, it will just print error from the else statement I set. I also tried changing the second query to $sql .= "SELECT * FROM tbl_classes WHERE class_code = '".$classcode."'"; and also tried putting semicolon after the first query to tell the SQL that I'm done with the first query since I'm putting 2 strings together, but still no luck.
try this
$studid = $_GET['stud_id'];
$classcode = $_GET['class'];
$conn = new MySQLi($host, $username, $password, $dbname) or die('Can not connect to database');
$sql = "SELECT * FROM tbl_students WHERE stud_id = '$studid';";
$sql.= "SELECT * FROM tbl_classes WHERE class_code = '$classcode'";
if ($conn->multi_query($sql)) {
do {
/* store first result set */
if ($result = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_row($result)) {
$studname = $row[3].", ".$row[1];
}
mysqli_free_result($result);
}
/* print divider */
if (mysqli_more_results($conn)) {
printf("-----------------\n");
$studname = $row['fname'];
}
} while (mysqli_more_results($conn));
}else{ echo "error";}
$conn->close();
Make one query instead of two :
"SELECT ts.*, tc.*
FROM tbl_students as ts, tbl_classes as tc
WHERE ts.stud_id = '$studid'
AND tc.class_code = '$classcode'"
Note : If you get redundant data then use group by.
I hava weired problem here with mysql database and php.
In the php, it gets the table names and then loops through the tables. Takes the rows and then send the variables to a function. I am using for loops to do this.
The problem is that I have 7 tables. If table 2 and 3 contain rows then it loops through 2 and does everything correctly. and it does not give table does not exists error for table 1. but for table 3-7 it gives all as table not exists.
but if I remove rows in table 2 then it loops through 3 and works correctly, and gives no error for 1 and 2. but for table 4-7 it gives table not exists err.
Basically it only loops through one table with rows and gives errors for all following tables. I don't understand is that a connection problem to mysql or something else.
Below is the snippet of my code:
<?php
$hostname_localhost ="localhost";
$username_localhost ="xxxxxxx";
$password_localhost ="xxxxxxxxx";
$database_xxxxxxxxxx ="xxxxxxxxx";
$database_yyyyyyyyyyy ="yyyyyyyyyy";
$database_zzzzz = "zzzzz";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
$get_all_tables = mysql_query("SHOW TABLES FROM xxxxxxxxx");
$table_names = array();
while($row = mysql_fetch_array($get_all_tables, MYSQL_NUM)) {
array_push($table_names,$row[0]);
}
mysql_select_db($database_xxxxxxx, $localhost);
for ($i=0; $i<sizeof($table_names); $i++){
$table = trim($table_names[$i]);
$get_tag = mysql_query("SELECT * FROM $table");
if ($get_tag){
while($get_tag_infos = mysql_fetch_array($get_tag)){
$similarity = $get_tag_infos['similarity'];
//........... and many other variables
if ($similarity == 20){
get20(many variables);
}
if ($similarity == 40){
get40(many variables);
}
if ($similarity == 60){
get60(many varibales);
}
if ($similarity == 80){
get80(many variables);
}
if ($similarity == 100){
get100(many variables);
}
}
}
else{
echo '</br> error! </br>'.mysql_error().mysql_errno();
}
}
function get20(many variables){
// performs a insert function to mysql
}
function get40(many variables){
// performs a insert function to mysql
}
function get60(many variables){
// performs a insert function to mysql
}
function get80(many variables){
// performs a insert function to mysql
}
function get100(many variables){
// performs a insert function to mysql
}
?>
The problem is connection with database. after first table find your connection with has been changed by inner connection. So use different variables for connections. I am setting a code which is running perfectly. I have tested.
<?php
//conection:
$link = mysqli_connect("localhost","root","pass","test") or die("Error " . mysqli_error($link));
//consultation:
$query = "show tables" or die("Error in the consult.." . mysqli_error($link));
//execute the query.
$result = mysqli_query($link, $query);
//display information:
while($row = mysqli_fetch_array($result)) {
echo $row["Tables_in_test"] . "<br>";
$link2 = mysqli_connect("localhost","root","pass","test") or die("Error " . mysqli_error($link));
$query2 = "select * from ".$row['Tables_in_test'] or die("Error in the consult.." . mysqli_error($link2));
$result2 = mysqli_query($link2, $query2);
while($row2 = mysqli_fetch_array($result2)) {
echo "<pre>";
print_r($row2);
echo "</pre>";
}
}
?>
$sql = "UPDATE reservations SET status = '$this->status',remaining_time ='$this->remain',cost = '$this->cost' WHERE id = '$this->id'";
This code is not working although it's correct
I am using object oriented php.
$this->id is a variable passed by link from another page.
When I run the code it tells me it was successful but that there are zero affected rows.
The one line above is part of the following code:
<?php
class edit {
private $status;
private $remain;
private $cost;
private $id;
public function edit_data() {
$this->status = strtoupper(strip_tags($_POST['status']));
$this->remain = strip_tags($_POST['remain']);
$this->cost = strip_tags($_POST['cost']);
$submit = $_POST['submit'];
$this->id = $_GET['edit'];
$con = mysql_connect("localhost","root","")
or die("Failed to connect to the server: " . mysql_error());
mysql_select_db("Users")
or die("Failed to connect to the database: " . mysql_error());
if($submit) {
if($this->status and $this->remain and $this->cost) {
$sql = "UPDATE reservations SET status = '".$this->status."',remaining_time ='".$this->remain."',cost = '".$this->cost."' WHERE id = '".$this->id."'";
$query = mysql_query($sql,$con);
if(!$query) {
echo("Could not update data: " . mysql_error());
}
echo "<h4>Customer reservation data has been updated successfully.</h4>";
echo "Number of affected rows: " . mysql_affected_rows();
}
else {
echo "Please fill in all fields.";
}
}
mysql_close($con);
}
}
$edit = new edit();
echo $edit->edit_data();
?>
Are you sure about your concatenation?
$sql = "UPDATE reservations SET status = '$this->status',remaining_time ='$this->remain',cost = '$this->cost' WHERE id = '$this->id'";
Print $sql to see the value.
If your database is already updated, you will receive 0 affected lines.
I am not totally sure but try this,
"UPDATE reservations SET status = '".$this->status."',remaining_time ='".$this->remain."',cost = '".$this->cost."' WHERE id = '".$this->id."'";
It seems that your table doesn't contain a value which satisfies where condition.
You can check this by executing a simple query.
$sql = "select * from reservations where id='$this->id'";