Delete from sql statement - php

I have a script which is supposed to delete a post from a database, however when the query is executed it does not delete anything. This is the query string.
$query = "DELETE post FROM kaoscraft_posts WHERE post_id = $postid"
What is wrong with the statement?
Yes, all variables are set and yes I have tested with an exact post_id
If you need more information, please just comment and tell me, don't be rude about it.

From the MySQL manual:
For the single-table syntax, the DELETE statement deletes rows from tbl_name and returns a count of the number of deleted rows.
So you can't delete the post only, you need to delete whole row.
$query = "DELETE FROM kaoscraft_posts WHERE post_id = $postid"
If you want to clear the post only, you can do it by UPDATE statement.

Delete query structure should be like this:
DELETE FROM table_name WHERE condition ;
You can not delete a column value in your table. you need to delete whole record of a row. If you wanted to delete single row then you need to update this row.
try this:
$query = "DELETE FROM kaoscraft_posts WHERE post_id = $postid";

You have an extra 'word' in your statement... it should be
$query = "DELETE FROM kaoscraft_posts WHERE post_id = $postid"

Please look on the below syntax,you come to know your mistake
DELETE FROM table_name WHERE column_name = some_value;

Related

Use mysql_insert_id in single query

Ok, don't know if this is simple in practice as it is in theory but I want to know.
I have a single INSERT query were by in that query, i want to extract the AUTO_INCREMENT value then reuse it in the same query.
For example
//values to be inserted in database table
$a_name = $mysqli->real_escape_string($_POST['a_name']);
$details = $mysqli->real_escape_string($_POST['details']);
$display_type = $mysqli->real_escape_string($_POST['display_type']);
$getId = mysqli_insert_id();
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO articles (a_name,details,display_type,date_posted) VALUES('$a_name','$details','$display_type$getId',CURRENT_TIMESTAMP)");
Apparently, am getting a blank value(I know because the mysqli_insert_id() is before the query, but I've tried all i could but nothing has come out as i want. Can some please help me on how to achive this
From my knoweldge this cant be done. Because no query has been run, MySQL is unable to return the ID of said query.
You could use a classic approach, pull the id of the previous record and add 1 to it, this is not a great solution as if a record is deleted, the auto increment value and the last value +1 may differ.
Run multiple queries and then use the insert_id (MySQLi is different to what you are using, you are best using $db->lastInsertId(); as mentioned in the comments.
Run a query before hand and store it as a variable;
SELECT auto_increment FROM INFORMATION_SCHEMA.TABLES WHERE table_name = 'tablename'
I strongly recommend Option 2, it is simply the cleanest and most reliable method for what you are looking to achieve.
It seems the value required for $display_type is :$display_type + (max(id) + 1).
In order to get the max_id you'll have to do this query before :
$sql = "SELECT id FROM articles ORDER BY id DESC LIMIT 1";
$result = mysqli->query($sql);
$maxid = $result->fetch_array(MYSQLI_NUM);
// $maxid[0] will contains the value desired
// Remove the mysqli_insert_id() call - Swap $getid by ($maxid[0] + 1)
// and u're good to go
N.B. update the name of ur primary key in the query $sql.
EDIT :
Assuming the weakness of the query and the quick resarch i did.
Try to replace $sql by (don't forget to Update DatabaseName & TableName values) :
$sql = SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName'
AND TABLE_NAME = 'TableName';
That Should do it . More info on the link below :
Stackoverflow : get auto-inc value
I don't think this can be done. You'll have to first insert the row, then update display_type, in two separate queries.
Thanks guys for your opinions, out of final copy, paste, edit and fix; here is the final working code(solution)
`
//values to be inserted in database table
$a_name = $mysqli->real_escape_string($_POST['a_name']);
$details = $mysqli->real_escape_string($_POST['details']);
$display_type = $mysqli->real_escape_string($_POST['display_type']);
//Select AUTO_INCREMENT VALUE
$sql = "SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'chisel_bk'
AND TABLE_NAME = 'articles'";
$result = $mysqli->query($sql);
$maxid = $result->fetch_array(MYSQLI_NUM);
$getId = $maxid[0];
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO articles (a_name,details,display_type,date_posted) VALUES('$a_name','$details','$display_type$getId',CURRENT_TIMESTAMP)");
This happens to do the magic!!!
`

how to get mysql id of number of effect row

I perform the mysql query to check if any number of row effected on the user input data with the help of mysql_num_rows($query). Only one row will effect always as I made some rows are unique. If one row effect, I want to get the ID of that Row. I means the auto increment ID of the same row.
The same row contains many fields, its better if I come to know how to get the entry of other fields.
Thanks stack for your solutions.
Have you tried SELECT id FROM table WHERE value=condition? If you query that you will get the id of the row that matches your condition. Replace id with the identifactor row, table with your table name, value and condition with your conditions.
$query = "SELECT id FROM table WHERE value=condition";
$result = mysql_query($query);
if ($row = mysql_fetch_row($result)) {
//$row contains valid information.
}
Btw: donĀ“t use mysql_* anymore, its deprecated, look at PDO or mysqli_*
$query = "SELECT mysql_id
FROM table";
$stmt = $db->prepare($query);
$stmt->execute();
$id = $stmt->fetchColumn();
You'll probably have to add a "WHERE" clause to your query statement and then pass the values into in array using a prepared statement.
just use mysql_insert_id();
this function after executing the insert query.
$query = "INSERT INTO test (value) VALUES ('test')";
mysql_query( $query );
$lastInsertId=mysql_insert_id();
echo $lastInsertId;

Can't access row with 'fieldName' using MAX() in PHP MYSQL

I have small PHP script which has
$query = "SELECT MAX(id) FROM `dbs`";
//query run
$row = mysql_fetch_array($result);
$val = $row[0];
Which runs fine, but I want to understand why i can't access the row with the fieldname, like if i have this
$query = "SELECT id FROM `dbs`";
i am able to use the folowing
$val = $row['id'];
but whenever i use this MAX() function, i have to change to
$val = $row[0];
to access the values
I have no clue about this. Any help would be appreciated. Thankss
You need to give it an alias:
<?php
$query = "SELECT MAX(id) AS `id` FROM `dbs`";
//query run
$row = mysql_fetch_array($result);
$val = $row['id'];
Edit:
To explain this it's probably best to show an example of a different query:
SELECT MAX(`id`) AS `maxId`, `id` FROM `dbs`
Using the above it will return as many rows are in the table, with 2 columns - id and maxId (although maxId will be the same in each row due to the nature of the function).
Without giving it an alias MYSQL doesn't know what to call it, so it won't have an associative name given to it when you return the results.
Hope that helps to explain it.
SELECT MAX(id) AS myFieldNameForMaxValue
FROM `dbs`
and then
$row = mysql_fetch_array($result);
$val = $row['myFieldNameForMaxValue'];
If you run this query on mysql commandline you'll see that the field name returned by mysql is MAX(id). Try running on phpmyadmin and you'll see the same. So if you try $row['MAX(id)'] it'll work. When using a mysql function, it gets added to the name, so use an alias, like other said here, and you're good to go: SELECT MAX(id) AS id FROM dbs. Also, never forget to use the ` chars, just in case you have some columns/tables with reserved names, likefrom`.

Incorrect usage of UPDATE and ORDER BY

I have written some code to update certain rows of a table with a decreasing sequence of numbers. To select the correct rows I have to JOIN two tables. The last row in the table needs to have a value of 0, the second last -1 and so on. To achieve this I use ORDER BY DESC. Unfortunately my code brings up the following error:
Incorrect usage of UPDATE and ORDER BY
My reading suggests that I can't use UPDATE, JOIN and ORDER BY together. I've read that maybe subqueries might help? I don't really have any idea how to change my code to do this. Perhaps someone could post a modified version that will work?
while($row = mysql_fetch_array( $result )) {
$products_id = $row['products_id'];
$products_stock_attributes = $row['products_stock_attributes'];
mysql_query("SET #i = 0");
$result2 = mysql_query("UPDATE orders_products op, orders ord
SET op.stock_when_purchased = (#i:=(#i - op.products_quantity))
WHERE op.orders_id = ord.orders_id
AND op.products_id = '$products_id'
AND op.products_stock_attributes = '$products_stock_attributes'
AND op.stock_when_purchased < 0
AND ord.orders_status = 2
ORDER BY orders_products_id DESC")
or die(mysql_error());
}
Just remove your ORDER BY in your UPDATE statement, then put it in your SELECT statement.
sample:
$query = "SELECT ........ ORDER BY ..."
$result = mysql_query($query);
while(....){.... }
UPDATE statement wont accept ORDER BY clause.
You could use a SELECT call to loop through the rows, and include your WHERE and ORDER BY statements there, and then within your while($row = mysql_fetch_assoc($query)){ loop you'd have your UPDATE table SET key = 'value' WHERE id = '{$row['id']}' statement.
Sure, this would require executing mysql_query() a lot, but it'll still run pretty fast, just not at the same speed a single query would.
Why do you need an order by in an update. I think you could just remove it and you update will update everything that respect your where statement.
EDIT: And maybe you could call a stored proc to simplify your code

assign delete for each row using sql query dynamically not specifying the row NAME or ID

I want to assign delete for each row using sql query but not specifying the row NAME or ID, e.g.: $sql = "DELETE FROM $table WHERE Description1 = 'Description 10'";
...must be dynamically maybe via row ID to delete correct row at any given time?
Please let me know if you want me to eloborate more about the question above, thanks in advance
If you want to delete all rows within one table just do the following:
DELETE FROM $table
Be careful! All rows will be deleted.
If you want to set the description for every row to an empty string just do:
UPDATE $table SET (Description1 = '')
Put checkboxes on each row with the ID of the relevant row as the value, and have these posted as an array when you click on the delete button. Then you can simply implode the array you get in PHP and use it in your delete statement as follows (you probably want to add some sanity checks on the posted data though):
$sql = 'DELETE FROM table WHERE ID IN(' . implode(',', $array) . ')';

Categories