In my websites admin page, i can delete products from the webshop, with this php code below. (Ajax calls this php file).
My question is, that do i need to select and check the num rows, or drop that, and just keep and run the delete queries?
<?php
include_once("../../files/connect.php");
if($_POST)
{
$id = mysqli_real_escape_string($kapcs, $_POST['id']);
$check = mysqli_query($kapcs, "SELECT termek_id, termek_thumb, termek_big FROM termek WHERE termek_id='$id' LIMIT 1");
if(mysqli_num_rows($check) > 0 )
{
/*Galéria törlése, ha van*/
$check_gallery = mysqli_query($kapcs, "SELECT * FROM gallery WHERE gallery_termek_id = '$id'");
if(mysqli_num_rows($check_gallery) > 0 )
{
while($gall = mysqli_fetch_assoc($check_gallery))
{
$DestinationDirectory = "../../images/gallery/";
if(file_exists($DestinationDirectory.$gall['gallery_thumb']))
{
unlink($DestinationDirectory . $gall['gallery_thumb']);
}
if(file_exists($DestinationDirectory.$gall['gallery_big']))
{
unlink($DestinationDirectory . $gall['gallery_big']);
}
mysqli_query($kapcs, "DELETE FROM gallery WHERE gallery_termek_id = '$id'") or die(mysqli_error($kapcs));
}
}
/* Címkék törlése, ha van */
$check_cimke = mysqli_query($kapcs, "SELECT termek_cimke_termek_id FROM termek_cimke WHERE termek_cimke_termek_id = '$id'");
if(mysqli_num_rows($check_cimke) > 0 )
{
mysqli_query($kapcs, "DELETE FROM termek_cimke WHERE termek_cimke_termek_id = '$id'");
}
mysqli_query($kapcs, "DELETE FROM hir_termek_kapcsolo WHERE hir_termek_kapcs_termek = '$id' ") or die("Delete error 2 - " . mysqli_error($kapcs));
$del = mysqli_query($kapcs, "DELETE FROM termek WHERE termek_id = '$id'");
if($del)
{
echo 'Delete ok';
}
else
{
echo 'Delete error;
}
}
else
{
echo 'Nincs ilyen azonosítójú termék.';
}
}
?>
You do not need to select anything before deleting any rows. Just use the same condition as you would selecting the rows.
Run the delete query, and you can check the number of affected rows to see if anything was deleted or not, and if so, how many rows. This function returns and integer with the number of deleted rows for a DELETE query.
mysqli_query($kapcs, "DELETE FROM hir_termek_kapcsolo WHERE hir_termek_kapcs_termek = '$id' ") or die("Delete error 2 - " . mysqli_error($kapcs));
echo mysqli_affected_rows($kapcs)." rows deleted";
http://php.net/manual/en/mysqli.affected-rows.php
WARNING
You're already using an API that supports prepared statements with bounded variable input, you should utilize parameterized queries with placeholders (prepared statements) to protect your database against SQL-injection!
Get started with mysqli::prepare() and mysqli_stmt::bind_param().
You do not need to select before you delete.
If no rows match the conditions, then the delete will not delete any rows.
Related
I am trying to increment a receipt number and add that new receipt number in the mysql database.
Here is my code that i have written:
<?php
require 'config.php';
$sql = "SELECT * FROM receipts ORDER BY id";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$date = date("ymdhs");
$row2 = $row['id'];
$recnum = $date.'-00'.($row2+);
echo $recnum ;
$sql = "UPDATE receipts SET recnum='$recnum' WHERE id='$row2'";
if ($conn->query($sql) === TRUE) {
echo "updated";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
The order is not specified in your select query. Thus, you get no guarantees from your RDBMS that your data will come back in a certain order - or even in a consistent order - unless you query your data with an ORDER BY clause.
If you want to rely on this order, you must specify your desired order using ORDER BY.
"$row2+" wont increment $row2, use (++$row2) - plus plus should be before the variable- instead.
I have managed to debug my code.
here is the working code.
<?php
require 'config.php';
$sql = "SELECT * FROM receipts ORDER BY id DESC LIMIT 1";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$date = date("ymdhs");
$row2 = $row['id'];
$recnum = $date.'-00'.$row2;
echo $recnum ;
$sql = "UPDATE receipts SET recnum='$recnum' WHERE id='$row2'";
if ($conn->query($sql) === TRUE) {
echo "";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
I have two databases and i have one table "TabelaX" in database "Servidor1" with out data and other database "Servidor2" with one table "TabelaY". And i want do one select in table "TabelaY" and with her data do one Update in table "TabelaX" which is in another database. I already made some code but it is not working correctly.
<?php
$conn= mysqli_connect('localhost','root',null,'Servidor2') or die
(mysqli_connect_error());
if (!$conn) {
die("Falha de conexao: ". mysqli_connect_error());
}
$ID = $_POST['ID'];
$sql = "SELECT * FROM TabelaY WHERE ID = $ID";
$result = mysqli_query($conn, $sql);
mysqli_select_db($conn,"Servidor1");
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$row1 = $row["ID"];
$row2 = $row["Data"];
}
} else {
echo "0 results";
}
$sql = "INSERT INTO Servidor1.TabelaX (ID, Data)
SELECT ID, Data
FROM Servidor3.TabelaW
WHERE ID = $ID;";
$sql = "UPDATE Servidor1.TabelaX SELECT ID, Data FROM
Servidor3.TabelaW SET Data = $row2 WHERE $row1 = $ID;";
if (mysqli_multi_query($conn, $sql)) {
echo "Dados Inseridos";
} if (mysqli_multi_query($conn, $sql)) {
echo "Dados Atualizados";
}
mysqli_close($conn);
I have no idea what your query is trying to do, because you assign to $sql twice without ever executing the first query, but if you're asking how to update a row in tableX based on data from tableY, then:
UPDATE Servidor1.TabelaX as x, Servidor2.TabelaY as y
SET x.Data = y.Data
WHERE x.id = y.id
AND x.id = $someIdForWhichYouWantToUpdate
Also, do not do this:
$ID = $_POST['ID'];
$sql = "SELECT * FROM TabelaY WHERE ID = $ID";
Imagine what happens when the user posts 1; DROP DATABASE Servidor1 into the form. This is called SQL injection and your code is full of vulnerabilities to it.
I am joining two table and I want to update all the rows.
<?php
include("connection/mysqlconnect.php");
$sql=" SELECT course.duration, course.id, students.ID
FROM course, students
where course.id=course_id and course.duration = '2'";
$result = $conn->query($sql);
$count=mysqli_num_rows($result);
if($count>=1)
{
while($row = mysqli_fetch_array($result)) {
$id = $row['ID'];
$stat = 'Active';
$year = '2nd Year';
$Graduated = 'Graduated';
$sql1 = "UPDATE students SET Year='$Graduated', Status='non-Active'
WHERE ID = '$id' and (status='$stat' and Year='$year')";
echo "$id</br>";
}
}
?>
I tried the Select Statement above in "Run SQL query" and it query the result i want. and I want to update all of the query, but I cant. I tried Putting echo under the update and it echo the ID's I need to update, but my update statement is not executing.
Instead of selecting all students then updating one by one, you can actually to this in one shot by joining both tables and updating it.
UPDATE students s
INNER JOIN course c ON c.id = s.course_id
SET s.Year = '$Graduated',
s.Status = 'non-Active'
WHERE c.duration = '2'
AND s.status = '$stat'
AND s.Year = '$year'
It must also be taken into consideration that the query above is vulnerable with sql injection. This article below will guide you how to prevent from it.
How to prevent SQL injection in PHP?
The issue with the first query is that there are two columns with the same name; ID. So referencing the ID from the row generates an error. Use alias to fix it as shown below. For a better performance use an inner join instead. You also forgot to run the update query again your database.
<?php
include("connection/mysqlconnect.php");
$sql=" SELECT course.duration, course.id as cID, students.ID as sID
FROM course JOIN students ON course.id=course_id
where course.duration = '2'";
$result = $conn->query($sql);
$count=mysqli_num_rows($result);
if($count>=1)
{
while($row = mysqli_fetch_array($result)) {
$id = $row['sID'];
$stat = 'Active';
$year = '2nd Year';
$Graduated = 'Graduated';
echo "Student ID to be updated: $id<br/>";
$sql1 = "UPDATE students SET Year='$Graduated', Status='non-Active'
WHERE ID = '$id' and (status='$stat' and Year='$year')";
//you have to execute the query for the update to be done.
if ($conn->query($sql1) === TRUE) {
echo "Record updated successfully ";
} else {
echo "Error updating record: " . $conn->error;
}
}
}
$conn->close();
?>
I have a mysql 'udate' query with 'where' condition checks '$mobile' with table
column_field 'Mobile', if the value from 'textfield' to the 'where'
condition is not matching with table column_field (Then the updation will
not occur on table row).
If the 'where' condition does NOT match on the table column_field
'Mobile'='$mobile' , how can i print "Error Message" on php code.
<?php
$sql ="update mytable set total_amount = total_amount + '$total_amt',
remaning_points = earned_points - redeemed_points where Mobile = '$mobile'";
$result = query($sql);
if (!$result)
{
echo "USER NOT EXISTING";
exit;
}
else
{
echo "UPDATED";
}
?>
You can easily do it as per answers or comments here, but the ideal way to do such things is to check for existence of the record, before you perform insert/update anything in database.
$query = 'select * from table where mobile="' . $mobile . '"';
$result = mysqli_query($con,$query);
if ($result->num_rows > 0) {
$query = 'update mytable set total_amount = total_amount + ' . $total_amt . ',
remaning_points = earned_points - redeemed_points where Mobile = "' . $mobile . '"';
$result = mysqli_query($con,$query);
}
else {
echo "No record matched";
}
You can send this message to the other page by using Session or GET. This will your code will ensure ACID properties of Database. It should perform the check before performing Data Manipulation Language (DML) Statements.
Have you seen the mysql function mysql_affected_rows()?
It returns how many rows/entrys were affected by your update query. If this functions returns zero (0) then it "failed" (the user does not exist).
My site is successfully inserting date from values the user has entered, however, when it comes to getting data from the database I have a problem.
Here's my code:
$sql = "SELECT cost FROM settings LIMIT 1";
if ($conn->query($sql) === TRUE)
{
$cost = $sql;
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
I'm just getting an error (Error: SELECT cost FROM settings LIMIT 1) and I'm unsure how to identify the problem. Everything looks correct from my point of view, obviously it's not.
Try this code. This code works only if you have properly connected to DB.
$sql = "SELECT `cost` FROM `settings` LIMIT 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["cost"];
}
} else {
echo "0 results";
}
Try using backtics,
$sql = "SELECT `cost` FROM `settings` LIMIT 1";
And also,
if ($sql->num_rows > 0) {
.....
Actually the error is in.
if ($conn->query($sql) === TRUE)
{
}
$conn->query($sql) will not return TRUE for SELECT QUERY ,it will return a result object. So the condition becomes false and you are getting the else part printed.