Delete function is not working [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am doing a system with php code,But delete function with SQL is not working.I don't know why it happens.
Below is my code:
function deleteEmployee($params)
{
$tid = $_SESSION['tmid'];
$data = array();
//print_R($_POST);die;
$sql = "delete from `cusinfo` WHERE TICKET_ID='".$params["id"]."' AND AGENT_CODE_STAFF_ID IN (SELECT id FROM `users` where tm_groupid = '$tid')";
echo $result = mysqli_query($this->conn, $sql) or die("error to delete employee data");
}

The problem probably is in the line echo $result = mysqli_query($this->conn, $sql) or die("error to delete employee data");
As I said in one comment, replacing the die string with mysqli_error($this->conn) should display an error.
However after some testing I found that assigning a variable in a echo might give strange results, i test echo $test = "hello" or die("test"); and found that neither hello nor test was displayed on the screen, but 1 was displayed, which probably was the boolean true.
A better way to see if the query was executed could be:
//other code that stayed the same
$statement = mysqli_prepare($this->conn, "delete from `cusinfo` WHERE TICKET_ID=? AND AGENT_CODE_STAFF_ID IN (SELECT id FROM `users` where tm_groupid = ?)");
$statement = mysqli_stmt_bind_param($this->conn, $params['id'], $tid); //
$sql = msyqli_stmt_execute($statement); // returns either true or false
if ($sql === true) {
echo "Successfull"; // executing successfull code
}
else {
var_dump(mysqli_stmt_error_list($statement)); // handling error
die;
}
This will handle some sql errors in a way that is expected(they are 'dumped and died').
Using prepared statements the correct way will mean that most sql injections are able to be stopped, and with a DELETE query, you want to make sure that sql injections are stopped.
Note: I am no expert on sql injections
Note 2: I would have used PDO for prepared statements though, it seems to me to be much more logical to work with

echo $result = mysqli_query($this->conn, $sql) or die("error to delete employee data");
In above line you are execution query and echo it. But if it is not executed you are echo your own message. This will prevent you from actual error message. And if the row that you are going to delete from TICKET_ID not exsist you cannot see it, you only see your message "error to delete employee data".
To solve this:
echo mysqli_error($this->conn);
This will give you connection error.
Or:
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($result) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
Many many function have to handle these errors. stackoverflow question, php manual and this.

Related

MYSQL loop update row value separately [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i have the following php:
<?php
$connection=mysqli_connect("host","user","pass","db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($connection,"SELECT ID FROM tbname");
while($row = mysqli_fetch_array($result))
{
mysqli_query($connection,"UPDATE tbname SET amount= (amount+ 1) WHERE ID='$row[ID]' ");
}
mysqli_close($connection);
echo 'OK'; ?>
I want to 'corelate' the pressing of a button to update the associated row value from the table but when i use this code i get all my values updated. Can anyone help me ?
This assumes that your ajax request is passing an 'id' parameter. Note that this code is open to SQL injection attacks. I am assuming that you know how to properly sanitize your inputs and parameterize your queries to protect yourself. If you don't, Jay's answer includes some good links that you should check.
<?php
if(!empty($_POST["id"]))
{
$id = $_POST["id"];
$connection=mysqli_connect("host","user","pass","db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
mysqli_query($connection,"UPDATE tbname SET amount= (amount+ 1) WHERE ID = '" . $id . "'");
mysqli_close($connection);
echo 'OK';
}
else
{
echo 'NO ID PASSED';
}
?>
You have to properly identify the variable in the array and concatenate the variable in the query:
mysqli_query($connection,"UPDATE tbname SET amount = amount+ 1 WHERE ID='" . $row['ID']. "' ");
you also do not need the parentheses around the calculation in the SET clause.
Since you're selecting all of the rows in your table and then looping through all of the rows and changing the value, which is not what you want, you have to select with a filter:
SELECT ID FROM tbname WHERE *some condition is met*
Once you do that you'll be able to update a subset of your records as you desire.
Since you're using MySQLi you should learn about prepared statements for MySQLi to guard yourself from potential SQL Injection Attacks.
in addition you should employ error checking, such as or die(mysqli_error()) to your connection and queries. If not you'll have to look in your error logs to fish out any problems that you could have with these.

Cannot select inserted data [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I made a new table , everything worked.
CREATE TABLE IF NOT EXISTS logdata (
email varchar(30),
password varchar(20),
username varchar(15),)
Inserted the id auto increment code
,and some data :
INSERT INTO logdata(email,password,username,id) VALUES('test#test.org','testtest1','test',' ')
Everything worked here. When I try to output the data i dont get any results (except "ERROR"). I have no idea why.
<?php
error_reporting(E_ALL);
// here is where I set the connection , everything is working here
if(mysqli_connect_errno()){
echo "Could not connect to the database <br /><br />";
echo mysqli_connect_error();
exit();
}
$dostuff="SELECT * FROM logdata";
$query = mysqli_query($db_conn, $dostuff);
if($query == TRUE) {
echo "Succes!";
}
else{
echo "ERROR ";
echo mysqli_error($db_conn);
}
?>
In order to query something in your database, you have to provide a query to it. Your query variable is an empty string!!
$dostuff="";
It should have some SQL statements, like e.g:
$dostuff="SELECT * FROM logdata";
Or whatever.
UPDATE
I believe that using === to test the result will fail because the mysqli_query returns a mysql_result object, according to the docs:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
So if its succeful it won't be === TURE for your SELECT statement and it will have no error. Your query is fine, just try this:
if ($query = mysqli_query($db_conn, $dostuff)) {
echo "Success!";
}
else {
echo "ERROR ";
echo mysqli_error($db_conn);
}
It should works.

Simple PHP code for using multiple foreign keys [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to code an order process. I have 3 different tables (orders, product, users) in a single database (dbphesemaas).
What I've tried so far doesn't work:
<?php
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('dbphesemaas');
$username=$_POST["username"];
$area=$_POST["area"];
$product=$_POST["product"];
$address=$_POST["address"];
$dol_quantity=$_POST["quantity"];
$query="INSERT INTO orders (id, product_id, address, quantity) VALUES ('$id', '$id2', '$address', '$dol_quantity')";
mysql_close();
?>
Can someone make this code work, the id is a foreign key from users, while the product_id is a foreign key of product?
1. Error handling
You just connect and execute the query.
Well yeah nope - how are you making sure that everything worked?
Let's start off with error handling.
<?php
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('dbphesemaas');
?>
Is the connection working? Did the database get selected successfully?
You can use the if module to check if it worked.
<?php
// IF $link = mysql_connect('localhost', 'root', '') did not work (note the ! in front of it)
if(!$link = mysql_connect('localhost', 'root', '')){
die('Could not connect to localhost'); // The message displayed. die() will prevent the rest of the script from executing.
}
// IF database "dbphesemaas" did not get selected succesfully (note the ! in front of it)
if(!mysql_select_db('dbphesemaas', $link)){
die('Could not select the database "dbphesemaas"'); // The message displayed. die() will prevent the rest of the script from executing.
}
?>
Now we have the connection working. If something goes wrong, the script will stop being executed and throw a custom error.
2. Unnecessary variables
$username=$_POST["username"];
$area=$_POST["area"];
$product=$_POST["product"];
$address=$_POST["address"];
$dol_quantity=$_POST["quantity"];
Now is my question, why? There is nothing wrong with just using them inside the query. The only reason why you only would make variables is if the old variable is very long (so the chance of typo's are bigger) and/or if the code is too messy in your opinion. Since there is no problem in this code to use the $_POST variable, we're going to scratch this piece of code.
3. The actual query
$query="INSERT INTO orders (id, product_id, address, quantity) VALUES ('$id', '$id2', '$address', '$dol_quantity')";
There are a few problems here:
You wrote the query, but you aren't executing it.
You are using variables ($id, $id2 etc) inside quotes. In the wrong scenario, it's gonna insert $id in the database instead of the actual value.
Once again, no error handling.
No untainting at all. The user can add on into your query and alter the query, making a possible leak and the chance of being hacked bigger. We're going to prevent this with mysql_real_escape_string: http://php.net/manual/en/function.mysql-real-escape-string.php
Looks kinda messy, but that's just a visual problem.
Let's fix these problems:
$query="
INSERT INTO
orders
(
id,
product_id,
address,
quantity
)
VALUES
(
'". mysql_real_escape_string($_POST['id']) ."',
'". mysql_real_escape_string($_POST['id2']) ."',
'". mysql_real_escape_string($_POST['adress']) ."',
'". mysql_real_escape_string($_POST['quantity']) ."'
)
";
if(mysql_query($query)){
echo 'Succesfully executed the query.';
}
else
{
echo 'Query not executed - MySQL error. <br>';
echo '<pre>'. mysql_error() .'</pre>';
}
Using '". (random php code) ."' allows php code to be executed within a string. For example:
$variable = 'This is text '. strtoupper('this is capitalized since strtoupper makes this capital. note that this is inside the string.') .' and this is once again lowercase.';
4. Keep this for the future
The way I wrote these codes are useful for the future. Keep the use tabs every time you open/add a new bracket ({).
Further info - the default mysql_* functions are going to be deprecated as of PHP 5.5 - Use MySQLi in the future, it's the improved version. Info: http://www.php.net/manual/en/book.mysqli.php
5. For your actual problem
One mysql_query can only execute one query. You can do this:
$queries = array();
$errors = array();
$queries[] = 'INSERT INTO ... '; // using $variable[] will add another entry to the $variable array.
$queries[] = 'INSERT INTO ... ';
$queries[] = 'UPDATE bla SET ...';
foreach($queries as $query){
// Foreach will seperate the entries in an array
// IF mysql query failed
if(!mysql_query($query)){
$errors[] = mysql_error(); // We'll add the errors to an array aswell.
}
}
// Check if there are entries in the $failures array.
if(count($errors) > 0){
echo 'We had some MySQL errors.';
echo '<ul>';
foreach($errors as $failure){
echo '<li>'. $failure .'</li>';
}
echo '</ul>';
}
else
{
echo 'No errors - MySQL queries executed succesfully.';
}
Hope this helps you on your way.

MYSQL & PHP News System [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have this news system but I can't figure out how to do it like this: news.php?id=1 then it will output the news id 1. Please help.
I have this so far:
<?php
include_once('includes/config.php');
if($id != "") {
$id = mysql_real_escape_string($id);
$sql = mysql_query("SELECT * FROM news WHERE id = '$id'");
}
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)){
if(isset($_GET['id']));
echo $res['body'];
}
?>
It connects to the database (details are stored in the config).
the parameters after the ? in the URL are GET items. Use this:
<?php
if (isset($_GET['id'])) {
$id = $_GET['id'];
// Rest of your code
}
<?php
include_once('includes/config.php');
// see if the id is set in the URL (news.php?id=)
if(isset($_GET['id'])) {
// get the ID from the URL
// to make it safer: strip any tags (if it's a number we could cast it to an integer)
$id = strip_tags($_GET['id']);
// don't use SELECT *, select only the fields you need
$sql = mysql_query("SELECT body FROM news WHERE id=".mysql_real_escape_string($id));
while($row = mysql_fetch_assoc($sql)) {
echo $res['body'];
}
} else {
echo 'please select an article';
}
I would recommend you get away from using the mysql functions and use mysqli instead, as mysql is depreciated and you'll have to learn mysqli or PDO anyway.
Edit: updated code per comments
Firstly lets dissect your current code, to see where your going wrong.
<?php
include_once('includes/config.php');
/*
$id is not set anywhere before its used so this if statement will not fire,
if you are attempting to get this $id from a url parameter then you need
to set it first from $_GET['id'] global
*/
if($id != "") {
$id = mysql_real_escape_string($id);
$sql = mysql_query("SELECT * FROM news WHERE id = '$id'");
}
/*
This piece of code will fire but where is $sql set?
The mysql_query() function expects a string containing your sql query
so the subsequent lines of code will fail because of this
*/
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)){
//this block is in the wrong place
if(isset($_GET['id']));
echo $res['body'];
}
?>
The idea is to get the user input E.G the $_GET['id'] from the url first, check the value is what your looking for, and then build your query.
As the mysql_* functions are deprecated I will show you an example using PDO. Though you can use mysqli, BUT you must always use prepared query's whenever user values come into contact with your database. This is to stop nasty/accidental sql injections.
<?php
// make the connection to the database using PDO
try {
$db = new PDO('mysql:host=127.0.0.1;dbname=the_awsome_db', 'yourusername', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->exec("SET CHARACTER SET utf8");
} catch(PDOException $e) {
exit('Sorry there is a problem with the database connection :' . $e->getMessage());
}
// sanitize user input - expecting an int
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
if (is_numeric($id)) {
// now lets query the database with the param id from the user
// prepare the query, using a placeholder
$stmt = $db->prepare('SELECT body,
some_other_column
FROM news
WHERE id = :placeholder_id');
// bind the placeholder with the value from the user
$stmt->bindParam(':placeholder_id', $id);
// execute the prepared query
$stmt->execute();
// fetch the result
$result = $stmt->fetch(PDO::FETCH_ASSOC);
// result not empty - display
if (!empty($result)) {
// display your result, use print_r($result) to view the whole result set if unsure
echo $result['body'];
} else {
// no matching id found in the db, do something
echo 'No results found';
}
} else {
// do something as user input is not a number
exit(header('Location: ./index.php'));
}
?>
Hope it helps, if your unsure of getting parameters from the user you may need to look up some more tutorials and get the hang of that first before dabbling with databases and all that good stuff.

How to get notified when a PHP/SQL query is notworking or invalid?

I am facing a problem. So I thought I should post my question here. I want to know that if my query is invalid how can I code the query so that the PHP controller notify me about the query error. Here is my PHP query code.
//assuming that the link $link to sql db has been already made
$Result = mysqli_query($link, 'SELECT * FROM books-table');
Is it possible to get notified whenever the query is wrong? please help
There is a simple way to do it. You can add an if condition to your code and use mysqli_error function to notify you about the invalid queries. Also you should save the query in a variable if you want to echo it easily so that you can also see the query. Here is your code with changes:
$yourquery = 'SELECT * FROM books-table';
$Result = mysqli_query($link, $yourquery);
if(!$Result)
{
echo 'There is an error in your query. Error='. mysqli_error($link);//to display error
echo '</br> the query is: '. $yourquery; //to display the query
}
Hope it will help you.
To capture if the query generates an error, you can code it like this:
/* OO-style */
if (!$link->query('SELECT * FROM books-table')) {
echo "Error: ".$link->error;
}
/* procedural style */
if (!mysqli_query($link, 'SELECT * FROM books-table')) {
echo "Error: ".mysqli_error($link);
}
(see the description of mysqli-query here in the php manual)
You can use something as simple as:
<?php
$query = "SELECT XXname FROM customer_table ";
$res = $mysqli->query($query);
if (!$mysqli->error) {
printf("Errormessage: %s\n", $mysqli->error);
}
?>
Courtesy - http://php.net/manual/en/mysqli.error.php
if(mysql_query("SOME_QUERY"))
{
//working do some action
}
else
{
//not working do some action
}

Categories