I want to update information. when I use the below in code is not working what is wrong in my code:
if(isset($_POST['submit'])){
$sql = "UPDATE `food`.`food_item`
SET `food_name` = '$_POST[food_name]',
`food_price` = '$_POST[food_price]',
`food_cat` = '$_POST[food_category]'
WHERE `food_item`.`id` ='$_POST[id]';";
$result = mysql_query($sql) or die("query not");
header("Location: product_info.php") ;
}
If you have a form input like,
<input type="text" name="product_name" />
You should get the value by,
$_POST['product_name'];
Is your form method is POST for GET?
If your method type is POST, you should get it like $_POST['input_name']
If your method type is GET, you should get it like $_GET['input_name']
Does all your input name you mentioned in html matches in php code?
Eg : If you have a form with input type,
<input type="text" name="product_name" />
Then, in php code, you should get it with what you entered in name attribute
$_POST['product_name'] OR $_GET['product_name']
Not something like,
$_POST['prod_name'] OR $_GET['prod_name']
Try this,
if(isset($_POST['submit'])
{
$food_name = $_POST['food_name'];
$food_price = $_POST['food_price'];
$food_cat = $_POST['food_category'];
$id = $_POST['id'];
// do not directly input the form data to sql, filter it by a special function mysqli_real_escape_string
// eg : $food_price = mysqli_real_escape_string($db, $_POST['food_price']);
// before executing the query, try to echo the each form input and sql query for clear picture.
$sql = "UPDATE `food`.`food_item` SET `food_name` = '$food_name',`food_price` = '$food_price',`food_cat` = '$food_cat' WHERE `food_item`.`id` ='$id'";
$result = mysqli_query($db, $sql);
if($result)
{
//header("Location: product_info.php") ;
echo "success";
}
else
{
echo "fail";
}
}
else
{
echo "form not submitted";
// use header to redirect to old page again
}
WARNING :
mysql is deprecated. Use mysqli or PDO.
Note :
$db is a database connection variable. You need to setup like
$db = mysqli_connect("localhost","username","password","database_name");
Look it's not mysql_connect, its mysqli_connect. Replace the db value according to your needs.
You can try following code to find the error.
echo mysql_error(); exit;
after following code.
$result = mysql_query($sql)
In order to access the array variables inside double quoted string, either do by enclosing them in curly brackets or put it outside the double quotes and append as a string. Here you try adding curly brackets like this:
if(isset($_POST['submit'])){
$sql = "UPDATE `food`.`food_item`
SET `food_name` = '{$_POST['food_name']}',
`food_price` = '{$_POST['food_price']}',
`food_cat` = '{$_POST['food_category']}'
WHERE `food_item`.`id` ='{$_POST['id']}';";
$result = mysql_query($sql) or die("query not");
header("Location: product_info.php") ;
}
Just echo $sql; Check what are the actual values in the query. Copy & run it in MYSQL query.
I think that you applied back ticks () on field names food_name . Remove back ticks & replace it with single quote ( ' )
Related
im trying to add data to my database but this code seems to just add blank data. Any solutions would be much appreciated. Thanks in advance.
<?php
session_start();
include 'dbh.php';
$start = $_POST['starttime'];
$finish = $_POST['finishtime'];
$dat = $_POST['date'];
$id = $_POST['userid'];
$sql = "INSERT INTO shift (shiftStart, shiftFinish, shiftDate)
VALUES ('$start', '$finish', '$dat')";
$result = mysqli_query($conn, $sql);
if ($result->affected_rows){
$row=$result->fetch_assoc();
echo'<pre>',print_r($row),'</pre>';
}else{
echo"didnt work";
}
//header("Location: index.php");
?>
$sql = "INSERT INTO shift (shiftStart, shiftFinish, shiftDate)
VALUES (".$start.", ".$finish.", ".$dat.")";
$result = mysqli_query($conn, $sql);
Try the above if any are string values you will need to add quotation marks around them single one ('".$start."').
First of all, use var_dump() to check all $_POST variables - do they have values?
If the method of your form is "get" you should use $_GET.
Step 2. After finding the (probably missing) variables please change you SQL query, otherwise you will have big risk of injection.
You should use prepared statements everywhere dealing with database. Check manual - http://php.net/manual/ru/mysqli.quickstart.prepared-statements.php .
And, by the way, you missing execute () function in your code.
I am trying to insert rating in database and calling average of that given rating from database
<?PHP
$connection = mysqli_connect("localhost", "akdnaklnd", "lfnlfns","faknfns");
$game = $_POST['game'];
$post_rating = $_POST['rating'];
$find_data = mysqli_query( "SELECT * FROM rates WHERE game='$game'");
while($row = mysqli_fetch_assoc($find_data)){
$id=$row['id'];
$current_rating = $row['rating'];
$current_hits=$row['hits'];
}
$new_hits = $current_hits + 1;
$update_hits= mysqli_query("UPDATE rates SET hits = '$new_hits' WHERE id='$id'");
$pre_rating= $current_rating + $post_rating;
$new_rating = $pre_rating / $new_hits;
$update_rating = mysqli_query("UPDATE rates SET rating ='$new_rating' WHERE id='$id'");
header("location : average.php");
?>
try to debug it by removing all the MySQL stuffs from code and keep redirection code with no space ie .
header("location:average.php");
if it works then there must be an error on your MySQL query. try adding error check after execution each MySQL query operations. Hope that will help you finding the breakpoint where your execution terminates before redirection statement.
Add $connection param to mysqli_query like this:
$find_data = mysqli_query($connection, "SELECT * FROM rates WHERE game='$game'");
Delete space symbol after "location" before colon: header("location: average.php");
Firstly you need not to select data you can directly write your update query like this.
Please make sure you pass variable instead of string for better practise use double and single quotes and dott too.
Most important pass connection variable.
$update_hits= mysqli_query($connection,"UPDATE rates SET hits = hits+1 WHERE id='".$id."'");
Try echo $update_hits if it give one then query successful else there is issue.
For that you can use error log
if (!$result) {
$errorQuery = $update_hits;
throw new Exception(mysqli_error($connection));
$errorMessage = mysqli_real_escape_string($connection,$e->getMessage());
echo $errorMessage;
exit();
}
else{
echo "Success";
}
<?php
require ("db/db.php");
$c_id = ($_POST['c_id']);
$c_title = ($_POST['c_title']);
$c_content = ($_POST['c_content']);
// echo place
$sql = mysql_query("UPDATE content
SET c_id = $c_id, c_title = $c_title, c_content = $c_content
WHERE c_id = $c_id");
header("location: index.php");
?>
This is my code.
when the header goes to the index, nothig has changed in the fields that are presented here.
i tried to echo the variables at the "echo place" and they all returned correct,
so i know that they are POSTed to the page.
i guess the error are in the SQL UPDATE statement, but PHP does not return any error to me,
it just goes directly to the index.php.
when i try to run the SQL in phpmyadmin, whith value 1 instead of the variable, it changes all the fields to 1, so there it works.
1) You should use mysql_real_escape_string()
2) why your are updating the id of a table? you also need to change your query
3) use quotes in your php variable
Try like this:
require ("db/db.php");
$c_id = mysql_real_escape_string($_POST['c_id']);
$c_title = mysql_real_escape_string($_POST['c_title']);
$c_content = mysql_real_escape_string($_POST['c_content']);
// echo place
$sql = mysql_query("UPDATE content
SET c_title = '$c_title', c_content = '$c_content'
WHERE c_id = $c_id limit 1") or die(mysql_error());
header("location: index.php");
You should switch to mysqli or PDO since mysql_* are outdated and will be removed.
Just to be sure, try this code (As I don't know the variables content, I put all of those with "'"
$sql = <<<SQL
UPDATE content
SET c_id='{$c_id}', c_title='{$c_title'}, c_content='{$c_content}'
WHERE c_id='{$c_id}'
SQL;
$query = mysql_query($sql);
var_dump($query);
And if the $query returns true, put the header('Location: index.php"); again
I have this code which permits me to pass a variable to another page, but the problem is i cannot seem to get that variable using the link. We have tried before, this same method and has worked.. could you please check it?
Thanks..
The link:
$sql="SELECT * FROM pianificazione";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
?>
<?php echo $row['job'] ?>
<?php echo '</br><br />'; }
?>
The page after the link:
include('menu.php');
$id=$_GET['job_id'];
$sql="SELECT * FROM attivita WHERE job_id='$id'";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
?>
<?php echo $row['attivita_da_promuovere'] ?>-<?php echo $row['attivita_tip_merc'] ?>-<?php echo $row['attivita_da_svolgere'] ?>-<?php echo $row['attivita_tip_personale'] ?>
You should be using:
$id = $_GET['id'];
You're also open to SQL injections... Either parse it as an INT:
$id = (int) $_GET['id'];
... or use prepared statements with PDO (instead of the default mysql functions that you're using, which are no longer recommended).
You're passing it as:
lista_attivita.php?&id=<?php echo $row['job_id'] ; ?>
And then looking for it as:
$id=$_GET['job_id'];
You should use:
$id=$_GET['id'];
In the URL that you're passing to the "page after link" you're setting "?id=xxx" as the parameter however in your script, your looking for "job_id".
Change the parameter to ?job_id= in your first script.
Two things.
1) FUNCTIONALITY
$id=$_GET['job_id'];
should be
$id=$_GET['id'];
since your link passes the variable id, not job_id:
lista_attivita.php?&**id**=<?php echo $row['job_id']
2) SECURITY
Never, NEVER insert user-input data directly into a SQL query. You are asking for headaches or worse. The $id on your receiving page should be validated and escaped prior to doing any lookup. If you expect a number, do something like this on the receiving page:
if (!is_numeric($_GET['id']))
{
// throw error
}
It's not a bad idea to query your DB for valid codes, put those in an array, then check that array to see if the passed value is found. This prevents user entered data from reaching your DB.
Something like this:
$q = "SELECT DISTINCT(id) FROM my_table WHERE display=1 ORDER BY id ASC";
$res = mysqli_query($dbx,$q);
while (list($_id) = mysqli_fetch_array)
{
$arr_valid_id[] = $_id;
}
Then,
if (in_array($_GET[id],$arr_valid_id[])
{
// do stuff
} else {
// throw error
}
<?php
include"include/connection.php";
$checkusername=mysql_query("SELECT * FROM employer WHERE eusername='$username'");
if (mysql_num_rows($checkusername)==1)
{
echo "username already exist";
}
else
{
$query = "insert into employer(efname,elname,egender,eemail,eusername,epwd,eadd,ephone,ecity,ecountry) values ('".$_POST['first_name']."','".$_POST['last_name']."','".$_POST['gender']."','".$_POST['email']."','".$_POST['username']."','".$_POST['password']."','".$_POST['address']."','".$_POST['phone']."','".$_POST['city']."','".$_POST['country']."')";
$result = mysql_query($query) or die (mysql_error());
echo " Thanks for registration";
}
?>
This is my code for inserting registration form data into a database. This code adds the data but also gives a parse error, but does not give the error if the username already exists.
Notice: Undefined variable: username in C:\Program Files\EasyPHP5.3.0\www\register_hirer2.php on line 6
Thanks for registration
line 6 is:
$checkusername=mysql_query("SELECT * FROM employer WHERE eusername='$username'");
Well, your $username is undefined indeed.
Most probably you want to use $_POST['username'].
And of course this obligatory XKCD comic:
If the "data source" is an html form (supposedly using method="post") you have to use $_POST['username'] when register_globals is set to off (which is the default since ...ages). see http://docs.php.net/security.globals
Also have a read of http://php.net/manual/en/security.database.sql-injection.php
<?php
include"include/connection.php";
$query = "SELECT
*
FROM
employer
WHERE
eusername='". mysql_real_escape_string($username). "'
";
$checkusername=mysql_query($query) or die(mysql_error());
if (mysql_num_rows($checkusername)==1)
{
echo "username already exist";
}
else
{
$query = "INSERT INTO employer(efname,elname,egender,eemail,eusername,epwd,eadd,ephone,ecity,ecountry) values (". same mysql_real_escape_string() thing here for each parameter .")";
$result = mysql_query($query) or die (mysql_error());
echo " Thanks for registration";
}
?>
You can also use prepared statements. This way you don't need/can't forget using an escaping function.
edit and btw: you don't need the SELECT before the INSERT in order to make the username unique. Actually it will make things even harder since now you have to deal with race conditions. You'd have to lock the table between those two queries.
If you add an unique index for the username in your table MySQL will not allow the insertion of a doublet but instead return a specific error code which your script can fetch and handle without the need of dealing with race conditions.
define('ER_DUP_ENTRY', 1062);
$mysql = mysql_connect('..', '..', '..');
mysql_select_db('..', $mysql) or die(mysql_error($mysql));
$fields = array(
'efname'=>'first_name',
'elname'=>'last_name',
'egender'=>'gender',
'eemail'=>'email',
'eusername'=>'username',
'epwd'=>'password',
'eadd'=>'address',
'ephone'=>'phone',
'ecity'=>'city',
'ecountry'=>'country'
);
$sqlparams = array();
foreach($fields as $sql=>$form) {
if ( !isset($_POST[$form]) ) {
die('missing post parameter '. $form);
}
$sqlparams[$sql] = "'".mysql_real_escape_string($_POST[$form], $mysql)."'";
}
$query = '
INSERT INTO
employer
'. join(', ', array_keys($sqlparams)) .'
VALUES
('.join(',', $sqlparams).')
';
// table:employer has been defined with "unique key idxName (eusername)"
$result = mysql_query($query, $mysql);
if ( false!==$result ) {
echo " Thanks for registration";
}
else if ( ER_DUP_ENTRY===mysql_errno($mysql) ) {
echo 'username already exists';
}
else {
echo 'an error occurred';
}
That is because you do not define $username anywhere. It looks as though you want to use $_POST['username']
mysql_query("SELECT * FROM employer WHERE eusername='{$_POST['username']}'");
Also, your code is vulnerable to a SQL Injection
You never define $usernameanywhere, so it gives that error because you are trying to use a variable that it doesn't have a value for.
This is most likely because you've not defined the '$username' variable. I presume that you're relying on this being populated from the incoming GET/POST data (most likely via the depreciated register_globals) which is bad practice.
As such, you'll need to either populate $username via $_POST or $_GET.
More importantly, you should update the insert query to escape the incoming 'untrusted' data using mysql_real_escape_string (e.g.: mysql_real_escape_string($_POST['username']), etc.)
As #Yacoby said your code is vulnerable to an SQL Injection to prevent it you can use mysqli or PDO , if you would like to use mysqli use the following code:
<?php
include"include/connection.php";
$query = "SELECT
*
FROM
employer
WHERE
eusername='". mysql_real_escape_string($username). "'
";
$checkusername=mysql_query($query) or die(mysql_error());
if (mysql_num_rows($checkusername)==1)
{
echo "username already exist";
}
else
{
$query = $conn->prepare("INSERT INTO employer(efname,elname,egender,eemail,eusername,epwd,eadd,ephone,ecity,ecountry)) values ( ? , ? , ? , ? , ? , ? , ? , ? , ? , ?)"; // preparing the insert
$query->bind_param("ssssssssss" , $variable1 , $variable2 , $variable3 , $variable4 , $variable5 , $variable6 , $variable7 , $variable8 , $variable9 , $variable10); // binding parameters
$query->execute(); // sending the parameter values
$query->close(); // closing the query
$conn->close(); // closing the connection
if ($query) { // checking if the query has been executed with no errors
echo " Thanks for registration";
}
}
?>
BE SURE TO CHANGE THE $conn AND variables to whatever you want!