I have a table where I store all the machine details, I need to delete all data and drop all tables of a specific user.
I'm trying to DROP tables based on the result from Select query, but it's not working as it is inside WHILE of SELECT query. Kindly help me with this.
$sql="SELECT M_ID FROM machine_details WHERE Username='".$inname."'";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_assoc($result))
{
$delmid=$row['M_ID'];
$delsta=$delmid."_status";
$delpar=$delmid."_parameter";
$sql1="DROP TABLE IF EXISTS $delpar, $delsta";
if(!mysqli_query($conn,$sql1))
{
echo "Error in drop".mysqli_error($conn);
}
else
{
$sql2="DELETE FROM machine_details WHERE M_ID=".$delmid;
if(!mysqli_query($conn,$sql2))
{
echo "Error in machine delete".mysqli_error($conn);
}
}
I'm not getting any errors from PHP or MariaDB, but the code doesn't DROP the table(It exists in phpmyadmin).
Any alternate or more efficient methods are also welcome.
UPDATE : The above code works perfectly fine now, kindly see the edit logs for better understanding about the issue I faced.
ID is int type! Dont place it in quotes. Right method is:
$sql2="DELETE FROM machine_details WHERE M_ID=".$delmid;
Try with Following Code to Delete.
For Delete you can use this code.
<?php
//delete.php
include("connection.php");
if(isset($_POST["_id"]))
{
$query = "DELETE FROM app WHERE _id = '".$_POST["_id"]."'";
if(mysqli_query($connection, $query))
{
echo 'Data Deleted';
}
}
?>
Note: Don't Delete any user data from the table, because if you need any history or detail report you can use this, for this you can put one flag.
Just remove the backquotes(`)
With its use M_ID is being converted to String type. Which should not happen... Because the primary key is int in your case
DELETE FROM machine_details WHERE M_ID=".$delmid;
Related
I know that is impossible to alter multiple tables at once, so I'm building my own PHP script that will do the job for me.
Here, I got all the tables that I want to alter:
<?php
include('conf/conn.php');
$result = mysqli_query($conn, "SHOW TABLES FROM queue LIKE '%room_%'");
while($table = mysqli_fetch_array($result)) {
echo($table[0] . "<br>");
}
?>
Now, I want to create a loop that executes a MySQL query for each table and echo a status every time each query is executed. Something like this:
<?php
foreach ($table[0] as $tableToAlter) {
$result = mysqli_query('ALTER TABLE $tableToAlter AUTO_INCREMENT = 1001');
if (!$result) {
echo 'Alter failded.';
} else {
echo 'Alter successful'
}
}
?>
As you can see, I'm a newbie in PHP and I am stuck in this last part. I don't know if I need to make an array to string conversion before the loop. If someone can please tell me how to make this works in the right way I will really appreciate. Thanks.
As suggested in the comments, you could call your query within the while loop using the variable $table[0].
<?php
include('conf/conn.php');
$result = mysqli_query($conn, "SHOW TABLES FROM queue LIKE '%room_%'");
while($table = mysqli_fetch_array($result)) {
echo("Altering {$table[0]}<br>");
if (!mysqli_query("ALTER TABLE {$table[0]} AUTO_INCREMENT = 1001");) {
echo 'Alter failded.';
} else {
echo 'Alter successful'
}
echo "<br>";
}
?>
As a side note, seeing as we are injecting unknown input into our query I would suggest in general using prepared statements, an example of which can be found here: How can I prevent SQL injection in PHP? (top answer)
I know this has been asked a lot but I can't find no other method that does not relate to num_rows I basically want to see if a record a exist in the database in a if else statement and in other words I don't mind using it but for personal complicated reasons I need to stay away from that because it conflicts on other things I want to add down the road. So this is my code example is there another way to do this with out using mysqli_num_rows?
<?php
$servername='localhost';
$username='angel';
$password='1234';
$db_name='test';
$connect= new mysqli($servername,$username,$password,$db_name);
$query="SELECT*FROM members WHERE first_name='bob'";
$result= $connect->query($query);
if($result->num_rows >0){
echo 'Exist';
}
else{
echo 'Does not exist';
}
?>
just to fill in the options pool
$query = "SELECT id FROM members WHERE first_name='bob'";
then check you get an id returned; assuming the table has an id column, if not just use another one
You could issue a separate query where all you do is count the results:
$getCount = "SELECT COUNT(*) AS `MemberCount` FROM members WHERE first_name='bob'";
Then use the results to determine your program's path.
I am trying to code a user system. I am having an issue with the activation part. I can select and insert data to my table but now I am trying to create an update statement and got stuck.
<?PHP
include "db_settings.php";
$stmt = $dbcon->prepare("UPDATE 'Kullanicilar' SET 'Aktivasyon' = ? WHERE 'KullaniciID'=?");
// execute the query
$stmt->execute(array('1','5'));
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
?>
And I am getting error as:
"0 records UPDATED successfully".
This is my table; http://i.imgur.com/PL2eD80.png
I have tried by changing my 'Aktivasyon' type int to char but it also does not work.
EDIT:
I am trying to make this a function;
function dataUpdate($tableName, $updateRow, $updateValue, $conditonRow, $conditionValue)
{
include "db_settings.php";
$q = $dbcon->prepare("UPDATE $tableName SET $updateRow= ? WHERE $conditonRow= ?");
$q->execute(array($updateValue,$conditionValue));
}
I also try this :
...
$q = $dbcon->prepare("UPDATE `$tableName` SET `$updateRow`= ? WHERE `$conditonRow`= ?");
...
How can I make this statement work?
You are using wrong quotes. You are basically saying "update this table, set this string to something when the string KullaniciID equals the string 5" which of course never is true.
You should use backticks ` if you want to specify column names. Then your query would work. Usually you don't even need those, but for some reason MySQL world is always adding them.
So to clarify, this is a string: 'KullaniciID' and this is a column name: `KullaniciID`.
Also you should not send integers as strings. It causes extra conversions or even errors with more strict databases.
I am trying to delete a specific entry in my MYSQL Database.
Database: PhotoID, IDCount, UserID.
This is my code for deleting a photo depending on the ID.
function delete($IdPhoto) {
$result = query("DELETE from photos WHERE IdPhoto='%d'", $IdPhoto);
if (!$result['error']) {
// if no error occured, print out the JSON data of the
// fetched photo data
print json_encode($result);
} else {
//there was an error, print out to the iPhone app
errorJson('Photo stream is broken');
}
}
This is paired with an iOS Application that grabs the current photos ID at all times. When a button is pressed, the delete function in the API will trigger. This doesn't seem to work though.
The following query works (specific ID):
$result = query("DELETE from photos WHERE IdPhoto=10");
Any help would be appreciated. The goal is to delete the photo depending on the $IdPhoto we grab in the iOS Application.
Try this:
$result = query("DELETE from photos WHERE IdPhoto={$IdPhoto}");
did you tried this :
$result = mysql_query("DELETE from photos WHERE IdPhoto='$IdPhoto' ");
you should use mysql_query
This
..IdPhoto='%d'
should be
..IdPhoto=%d
Since a int value shouldn't be surrounded by quotes
The "=" will only compare two int values or double values. Make sure you are comparing the type int. Thus your delete function should pass an int, otherwise you might need a function like getIntvalue() to extract the int value.
I have a strange mysql-thing going on here, it is about the following code:
$res = mysql_query("SELECT * FROM users WHERE group='".$group."'");
if (mysql_num_rows($res)==1) {
$row = mysql_fetch_assoc($res);
$uid = $row['uid'];
$user_update = mysql_query("UPDATE fe_users SET group = 5 WHERE group='".$group."'");
return 'ok';
} else {
return 'not ok';
}
I am checking, if there is a user with the group = $group. If so, the group is updated to 5 and after that the string "ok" is returned, if no user with group=$group exists, as you can see the string "not ok" is returned.
This should be very easy, but the problem now is, that if there is a user with group=$group, the update is done correctly, but instead of returning "ok", php returns "not ok", as if the change from the update is been taken into account for the above executed select retroactively. I dont understand this. Any help would be really appreciated.
Thanx in advance,
Jayden
I think 'group' is a reserved keyword that you have used as a field name, change it or use like
$res = mysql_query("SELECT * FROM users WHERE `group`='".$group."'");
and
$user_update = mysql_query("UPDATE fe_users SET `group` = 5 WHERE `group`='".$group."'");
and you can use count($res)==1 instead of mysql_num_rows($res)==1 if it is a problem.
Reference: Mysql Reserved keywords.
I am not sure if this has any merit but try using this style in your SELECT and UPDATE commands: WHERE group='$group', without using string joins. Other than that I can't seem to see why you are getting an update and not being returned "ok".
You are checking if mysql_num_rows($res)==1, so you'll return ok if there is exactly one user on that group. If there are two or more users, it will return not ok. Probably not what you want, right? I think you should check if mysql_num_rows($res)>=1.
You might consider modifying the placement of your brackets, and changing your num_rows check, like so:
$res = mysqli_query("SELECT uid FROM users WHERE `group` ='".$group."'");
if (mysqli_num_rows($res)>0) {//there was a result
while($row = mysqli_fetch_assoc($res)){
// grab the user id from the row
$uid = $row['uid'];
// and update their record
$user_update = mysqli_query("UPDATE fe_users SET `group` = 5 WHERE `group`='".$group."'");
if(mysqli_num_rows($user_update)==1){
return 'ok, updated user';
} else {
// database error
return 'not ok, unable to update user record';
}
}//end while row
}else{
return 'No results were found for this group.';
}
By selecting just the column you want, you reduce the query's overhead. By comparing the initial result to 0 instead of 1, you allow for groups with many members. By wrapping the update function in a while loop, you can loop through all the returned results, and update records for each one. By moving the test that returns 'ok'/'not ok' to check for success on the update operation, you're able to isolate database errors. The final else statement tells you if no update operation was performed because there are no members of the group.
BTW, for future-compatible code, I recommend using mysqli, as the "mysql_query" family of PHP functions are officially deprecated. See http://www.php.net/manual/en/mysqli.query.php for a quick start, it's largely the same thing.