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.
Related
This question already has answers here:
delete using where and or
(4 answers)
Closed 4 years ago.
i've gone through most of the questions similar to this but none addressed my problem.
i have table with four columns : id,username,title and date. i want to delete the entire row(s) associated with a specific username when the user clicks a button (anchor tag). pls, how do i achieve this? heres the code i tried.
php
<?php
session_start();
$uname = $_SESSION['username'];
$dbconn = mysqli_connect('localhost','root','','notesdb');
if(!$dbconn){
die("Connection failed:". mysqli_connect_error($dbconn));
}
if($stmt = $dbconn->prepare("DELETE * FROM notes_log where username = ? ")){
$stmt->bind_param("s",$uname);
$stmt->execute();
$stmt->close();
}else{
echo "ERROR: could not prepare SQL statement.";
}
mysqli_close();
// redirect user after delete is successful
header("Location: index.php");
?>
HTML
Delete all
The above code redirected the page but nothing was deleted.
Get rid of the * in the query. The syntax is just:
DELETE FROM notes_log where username = ?
See DELETE Syntax.
In a multi-table DELETE you need to put the table names after DELETE, but a single-table DELETE should have nothing there.
And when an SQL operation fails, you should print the SQL error message, not just could not prepare SQL statement, e.g.
echo "ERROR: could not prepare SQL statement: " . $dbconn->error;
Edit: mysqli_close() requires a database connection as its only argument.
Ref: http://php.net/manual/en/mysqli.close.php
You will need to use mysqli_close($dbconn).
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 need get Data form mySql and echo it . but show to me error ! please help me . I am amator . please check my code. (get Data form mySql and echo it - PHP)
my error in $result1=mysqli_query($link,$query1);
my PHP file :
<?php
$post_data=#$_POST['myjson'];
$post_data=json_decode($post_data,true);
$command=$post_data['command'];
$server="localhost";
$user="user";
$pass="pass";
$db="db";
$link=mysqli_connect($server,$user,$pass,$db);
mysqli_set_charset($link,"utf8");
if ($command=="get_contact") {
$id=$post_data['id'];
$query="select * from ad where id=$id";
$result=mysqli_query($link,$query);
$row=mysqli_fetch_assoc($result);
$num=mysqli_num_rows($result);
if ($num == 1) {
$query1="select * from user where id=$row['user_id']";
$result1=mysqli_query($link,$query1);
$row1=mysqli_fetch_assoc($result1);
$num1=mysqli_num_rows($result1);
if ($num1 == 1) {
$specifications=array("mobile"=>$row1["mobile"], "email"=>$row1["email"]);
echo "<b>".json_encode($specifications)."</b>";
} else {
echo "<b>Not Found</b>";
}
} else {
echo "<b>Not Found</b>";
}
exit();
}
?>
If you expect just one result of each query, you can get the same results with just one query instead of the two you have:
$query = "select user.* from user, ad where ad.id=$id and user.id = ad.user_id";
Also, you should use prepared statements to avoid sql injection instead of writing vars inside the sql queries.
Besides that, give more info in the error messages because now you don't know which error is returning.
I feel like this should be really simple and I understand the basics of how multiplying figures in MYSQL as well as PHP works but for some reason no matter what route I try I haven't had any luck even after checking forums and videos.
I want this to be executed to store the end result in MYSQL so I do not need to echo the result as many tutorials show.. The one variable I'm needing to select is in one database table and the other variable is in another table.. I'm also posting one of the variables that is needed to be multiplied prior to the result being executed so if it is easier to multiply the posted variable with the one already in the database rather than after it's been updated into the other database table that works too but I haven't had any luck with either.
Any help would be very much appreciated!!
I apologize in advance if this question was already answered or if it's super simple, after nothing working for three days I figured I'd try asking on here.
I'm thinking the end result should look something like this..
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
include('session.php');
$quantity = $_POST['quantity'];
$item = $_POST['item'];
$sql2 = "SELECT Price FROM items WHERE item='$item'";
$res = mysql_query($sql2);
$sql = "UPDATE ordered_items SET oi_total = ('$res' * '$quantity') WHERE oi_name='$item' AND oi_employee='$login_session'";
if (mysqli_query($conn, $sql)) {
header('Refresh: 4; URL=http://websitehere.com');
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
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.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Error: INSERT INTO reservations (GameID,Name,Numberofdays,ReservationID,Startdate)VALUES (5,'jp', 4, ,'2016-03-23')
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''2016-03-23')' at line 30 results
The code bellow does insert the information that is inputted from a form even though the SQL query is correct . I have tested and changed the code many times and have discussed and reviewed it with my peers .
Bellow is the code for it :
<div id="content">
<?php
//variables needed to connect to the database
$user_name = "root";
$password = "";
$database = "game_library";
$host_name ="localhost";
// Create connection
$con=mysqli_connect($host_name,$user_name,$password,$database) or die("Error ");
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
//link the search term to the html page
$GameID=$_POST['GameID'];
$Name=$_POST['Name'];
$Numberofdays=$_POST['Numberofdays'];
$Startdate=$_POST['Startdate'];
//sql query to add the data from the form elements to the sql database
//The reservationID is auto incremented so requires a space
$qry_reserve = "INSERT INTO reservations
(GameID,Name,Numberofdays,ReservationID,Startdate)VALUES ($GameID,'$Name',
$Numberofdays, ,'$Startdate')";
//Runs the query if the database if connection succesful
if ($con->query($qry_reserve) === TRUE) {
echo '<br/>';
echo $Name. ' has been added successfully</h2>';
echo '<hr>';
} else {
echo "Error: " . $qry_reserve . "<br>" . $con->error;
}
//show added data & all records to prove they have been added. You don't have to do this
$qry_show_table = "SELECT * FROM reservations WHERE GameID='$GameID' ";
$result = mysqli_query($con, $qry_show_table);
if (mysqli_num_rows($result) > 0) { // checks if there are more than zero rows returned.
// output data of each row
while($row = mysqli_fetch_assoc($result)) //puts all the results into an associative array that we can loop through
{
echo '<br/>';
echo 'Name: '.$row['Name'];
echo '<br/> GameID: '.$row['GameID'];
echo '<br/> Startdate: '.$row['Startdate'];
echo '<br/> Numberofdays: '.$row['Numberofdays'];
echo '<br/>';
echo '<hr>';
}
} else {
echo "0 results";
}
$con->close();
?>
Leave out the parentheses:
INSERT INTO reservations
VALUES ($GameID, '$Name', $Numberofdays, ??,' $Startdate')
---------------------------------------------^ something needs to go here
Or, better yet, list the columns:
INSERT INTO reservations(col1, col2, col3, col4, col5)
VALUES ($GameID, '$Name', $Numberofdays, ??, '$Startdate')
---------------------------------------------^ something needs to go here
Note that you have two commas with no value in between. Perhaps this is a typo, perhaps you intend NULL or DEFAULT or something else.
You won't need the parenthesis and also you have a extra comma:
$qry_reserve = "INSERT INTO reservations VALUES ($GameID,'$Name',$Numberofdays,'$Startdate'";
More information at http://www.w3schools.com/sql/sql_insert.asp.