Update query not working in PHP and Mysql - php

I have made an update page which fetches record from a table, shows all the details on html form where user can change/Edit the values and submit. Next page fetches those values using $_POST and Update the table.
$new_id = $_POST['c_id'];
$new_name = $_POST['c_name'];
$table_name = "tcompany";
$sqlStatement = "UPDATE $table_name SET 'name'=$new_name WHERE 'id'= $new_id";
if($result_1 = mysql_query($sqlStatement))
{
header('Location: edit_company.php');
}
else {
echo "". mysql_error();
}
I am getting error :
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''name'=HARDWARE Exporters WHERE 'id'= 69' at line 1
I am not considering security issues related to injection. Using this code for personal use.

Don't use apostrophe (') for column names and use it instead to your variables.
$sqlStatement = "UPDATE ".$table_name." SET name='$new_name' WHERE id='$new_id'";
You should also sanitize the values you are binding to your query. Use *_real_escape_string.
$new_id = mysql_real_escape_string($_POST["c_id"]);
And mysql_* API is already deprecated and you should consider using mysqli prepared statement instead.
If you want an example of prepared statement, using the code you have given, you can refer below. No need to sanitize each values before using them to your query.
/* ESTABLISH FIRST YOUR CONNECTION */
$con = new mysqli("YourHost","Username","Password","Database"); /* REPLACE NECESSARY DATA */
if($stmt = $con->prepare("UPDATE ? SET name = ? WHERE id = ?")){ /* CHECK IF STATEMENT IS TRUE */
$stmt->bind_param("ssi",$table_name,$_POST["c_name"],$_POST["c_id"]); /* BIND VALUES TO YOUR QUERY */
$stmt->execute(); /* EXECUTE THE QUERY */
$stmt->close();
} /* END OF PREPARED STATEMENT */

The problem is that variable $new_name contains spaces. So you should quote the use of variables in the statement, like this:
$sqlStatement = "UPDATE $table_name SET 'name'='$new_name' WHERE 'id'= '$new_id'";

Related

Get last inserted ID in prepared statement

I need to get the last inserted ID for each insert operation and put it into array, I am trying to see what is the correct way of doing it.
Following this post Which is correct way to get last inserted id in mysqli prepared statements procedural style?
I have tried to apply it to my code but I am still not getting the right response.
if($data->edit_flag == 'ADDED')
{
$rowdata[0] = $data->location_name;
$rowdata[1] = 0;
$rowdata[2] = $data->store_id;
$query = "INSERT IGNORE INTO store_locations (location_name,total_items, store_id) VALUES (?,?,?)";
$statement = $conn->prepare($query);
$statement->execute($rowdata);
$id = mysqli_stmt_insert_id($statement);
echo "inserted id: " . $id;
}
I then realised that I am using a PDO connection so obviously mysqli functions wont work. I went ahead and tried the following
$id = $conn->lastInsertId();
echo "insert id: " . $id;
but the response is still empty? What am I doing incorrectly? For the lastInsertId(), should I be using $conn or $statement from here:
$statement = $conn->prepare($query);
$statement->execute($rowdata);
You are using lastInsertId() correctly according to the PDO:lastInsertId() documentation
$statement = $conn->prepare($query);
$statement->execute($rowdata);
$id = $conn->lastInsertId();
Some potential reasons why it is not working:
Is this code within a TRANSACTION? If so, you need to COMMIT the transaction after the execute and before the lastInsertId()
Since you INSERT IGNORE there is the potential that the INSERT statement is generating an error and not inserting a row so lastInsertId() could potentially be empty.
Hope this helps!
If you are using pdo,
$stmt = $db->prepare("...");
$stmt->execute();
$lastInsId = $db->lastInsertId();

Using PHP variable in SQL query

I'm having some trouble using a variable declared in PHP with an SQL query. I have used the resources at How to include a PHP variable inside a MySQL insert statement but have had no luck with them. I realize this is prone to SQL injection and if someone wants to show me how to protect against that, I will gladly implement that. (I think by using mysql_real_escape_string but that may be deprecated?)
<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'hospital_name' AND value = '$q'";
$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
echo $row['value'];
}
?>
I have tried switching '$q' with $q and that doesn't work. If I substitute the hospital name directly into the query, the SQL query and PHP output code works so I know that's not the problem unless for some reason it uses different logic with a variable when connecting to the database and executing the query.
Thank you in advance.
Edit: I'll go ahead and post more of my actual code instead of just the problem areas since unfortunately none of the answers provided have worked. I am trying to print out a "Case ID" that is the primary key tied to a patient. I am using a REDCap clinical database and their table structure is a little different than normal relational databases. My code is as follows:
<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'case_id' AND record in (SELECT distinct record FROM database.table WHERE field_name = 'hospital_name' AND value = '$q')";
$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
echo $row['value'];
}
?>
I have tried substituting $q with '$q' and '".$q."' and none of those print out the case_id that I need. I also tried using the mysqli_stmt_* functions but they printed nothing but blank as well. Our server uses PHP version 5.3.3 if that is helpful.
Thanks again.
Do it like so
<?php
$q = 'mercy_west';
$query = "SELECT col1,col2,col3,col4 FROM database.table WHERE field_name = 'hospital_name' AND value = ?";
if($stmt = $db->query($query)){
$stmt->bind_param("s",$q); // s is for string, i for integer, number of these must match your ? marks in query. Then variable you're binding is the $q, Must match number of ? as well
$stmt->execute();
$stmt->bind_result($col1,$col2,$col3,$col4); // Can initialize these above with $col1 = "", but these bind what you're selecting. If you select 5 times, must have 5 variables, and they go in in order. select id,name, bind_result($id,name)
$stmt->store_result();
while($stmt->fetch()){ // fetch the results
echo $col1;
}
$stmt->close();
}
?>
Yes mysql_real_escape_string() is deprecated.
One solution, as hinted by answers like this one in that post you included a link to, is to use prepared statements. MySQLi and PDO both support binding parameters with prepared statements.
To continue using the mysqli_* functions, use:
mysqli_prepare() to get a prepared statement
mysqli_stmt_bind_param() to bind the parameter (e.g. for the WHERE condition value='$q')
mysqli_stmt_execute() to execute the statement
mysqli_stmt_bind_result() to send the output to a variable.
<?php
$q = 'Hospital_Name';
$query = "SELECT value FROM database.table WHERE field_name = 'hospital_name' AND value = ?";
$statement = mysqli_prepare($conn, $query);
//Bind parameter for $q; substituted for first ? in $query
//first parameter: 's' -> string
mysqli_stmt_bind_param($statement, 's', $q);
//execute the statement
mysqli_stmt_execute($statement);
//bind an output variable
mysqli_stmt_bind_result($stmt, $value);
while ( mysqli_stmt_fetch($stmt)) {
echo $value; //print the value from each returned row
}
If you consider using PDO, look at bindparam(). You will need to determine the parameters for the PDO constructor but then can use it to get prepared statements with the prepare() method.

Query not inserting data

trying to submit data from a form but does not seem to be working. Can't spot any problems?
//Include connect file to make a connection to test_cars database
include("prototypeconnect.php");
$proId = $_POST["id"];
$proCode = $_POST["code"];
$proDescr = $_POST["descr"];
$proManu = $_POST["manu"];
$proCPU = $_POST["cpu"];
$proWPU = $_POST["wpu"];
$proBarCode = $_POST["barcode"];
$proIngredients = $_POST["ingredients"];
$proAllergens = $_POST["allergenscon"];
$proMayAllergens = $_POST["allergensmay"];
//Insert users data in database
$sql = "INSERT INTO prototype.Simplex_List (id, code, descr, manu, cpu, wpu, barcode, ingredients, allergenscon, allergensmay)
VALUES ('$proId' , '$proCode', '$proDescr' , '$proManu' , '$proCPU' , '$proWPU' , '$proBarCode' , '$proIngredients' , '$proAllergens' , '$proMayAllergens')";
//Run the insert query
mysql_query($sql)
First and foremost, please do not use mysql_*** functions and please use prepared statements with
PDO http://php.net/manual/en/pdo.prepare.php
or mysqli http://php.net/manual/en/mysqli.quickstart.prepared-statements.php instead. Prepared statements help protect you against sql injection attempts by disconnecting the user submitted data from the query to the database.
You may want to try using mysql_real_escape_string http://php.net/manual/en/function.mysql-real-escape-string.php to ensure no stray " or ' is breaking your query.
$proId = mysql_real_escape_string($_POST["id"]);
$proCode = mysql_real_escape_string($_POST["code"]);
$proDescr = mysql_real_escape_string($_POST["descr"]);
$proManu = mysql_real_escape_string($_POST["manu"]);
$proCPU = mysql_real_escape_string($_POST["cpu"]);
$proWPU = mysql_real_escape_string($_POST["wpu"]);
$proBarCode = mysql_real_escape_string($_POST["barcode"]);
$proIngredients = mysql_real_escape_string($_POST["ingredients"]);
$proAllergens = mysql_real_escape_string($_POST["allergenscon"]);
$proMayAllergens = mysql_real_escape_string($_POST["allergensmay"]);
Additionally ensure your form is being submitted by calling var_dump($_POST) to validate the data
You can also see if the query is erroring by using mysql_error http://php.net/manual/en/function.mysql-error.php
if (!mysql_query($sql)) {
echo mysql_error();
}
advices about PDO, prepared statements were done.
1) Do you have a database and connection to it?
Look at your prototypeconnect.php and find database name there. check that its name and password is similar that u have.
2) Do you have a table named prototype.Simplex_List in your database?
a) IF YOU HAVE:
check if your mysql version >= 5.1.6
http://dev.mysql.com/doc/refman/5.1/en/identifiers.html
b) IF YOU HAVE BUT ITS NAME is Simplex_List:
b-1) if your database name IS NOT prototype:
replace your
$sql = "INSERT INTO prototype.Simplex_List
with
$sql = "INSERT INTO Simplex_List
b-2) if your database name IS prototype:
you should escape your $_POST data with mysql_real_escape_string as #fyrye said.
c) IF YOU HAVE NOT:
you should create it
3) Check your table structure
does it have all theese fields id, code, descr, manu, cpu, wpu, barcode, ingredients, allergenscon, allergensmay?
if you have there PRIMARY or UNIQUE keys you should be sure you are not inserting duplicate data on them
but anyway replace your
$sql = "INSERT INTO
with
$sql = "INSERT IGNORE INTO
PS: its not possible to help you without any error messages from your side

Passing PHP variable to SQL query

$user = mysql_real_escape_string($_POST["userlogin"]);
mysql_connect("uritomyhost","myusername","password");
mysql_select_db('mydatabase');
mysql_query('UPDATE table SET field = field + ($userlogin)');
Is this the right way of getting userlogin from the post request and then inserting it to my SQL query?
Stop using outdated functions and use PDO instead.
$stmt = PDO::prepare('UPDATE table SET field = field + :field');
$stmt->execute(array('field' => $_POST["userlogin"]));
Read some information about PDO.
In short: it escapes your data for you, is quite consistent across databases and generally just easier.
you should use mysql_real_scape_string() just after connecting to database ...
so change your code to this :
mysql_connect("uritomyhost","myusername","password");
mysql_select_db('mydatabase');
$userlogin = mysql_real_escape_string($_POST["userlogin"]);
mysql_query("UPDATE table SET field = '$userlogin'");
Try like this.
$user = mysql_real_escape_string($_POST["userlogin"]);
mysql_connect("uritomyhost","myusername","password");
mysql_select_db('mydatabase');
mysql_query("UPDATE table SET field = value where user='$user'");
Try this
mysql_query("UPDATE table SET field = field + ('$user')");
However,
You might be updating all the fields in your table because you have no where in your UPDATE clause
Shouldn't it rather be
mysql_query("UPDATE table SET field = field WHERE user= '$user'");
I think you want to INSERT instead of using Update. Why field = field + ($userlogin)? This will concatenate the values. And one more thing please use PDO or MYSQLI
Example of using PDO extension:
<?php
$stmt = $dbh->prepare("INSERT INTO tanlename (field) VALUES (?)");
$stmt->bindParam(1, $user);
$stmt->execute();
?>
Use mysql_real_escape_string() after mysql connection and
Use double quotes
mysql_query("UPDATE table SET field = field + ({$userlogin})");
Use mysqli_query for you queries(notice the i) and use prepared statements. Using prepared statements is more secure than using straight queries and including the variable in the query string. Moreover, mysql will be deprecated soon. Example :
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$city = "Amersfoort";
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>

not updating the sql database

i wrote the following code,but its not updating the database,,its a part of a script and it cease to work..cant find a way around it .. need suggestions
<?php
$link = mysql_connect('xxxxxxxx');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xxx", $link);
$usernames='aneeshxx';
echo $usernames;
$update = "INSERT sanjana SET $name ='$usernames'";
mysql_query($update, $link);
$update1 = "INSERT INTO sanjana (name)VALUES ($usernames)";
mysql_query($update1, $link);
?>
$update = "INSERT sanjana SET $name ='$usernames'";
this probably is meant as an UPDATE statement, so for an update it should be
$update = "UPDATE sanjana set name = '$usernames'";
I put name and not $name due to your second query and not seeing $name being defined anywhere. Be aware that this will change the value in the column name of every row in the sanjana table to the value of $usernames, normally a statement such as this gets limited by conditions, e.g. WHERE userid = 33
$update1 = "INSERT INTO sanjana (name) VALUES ($usernames)";
for an INSERT statement it needs to have the values quoted so
$update1 = "INSERT INTO sanjana (name) VALUES ('$usernames')";
Be wary that this way of putting variables directly into your query string makes you vulnerable to SQL injection, to combat this please use the PDO or mysqli extensions, they both protect you from injection by providing you with prepared statements ; plain old mysql_* is not recommended for use anymore.
using pdo you'd use prepared statements like this
<?php
// we got $usernames from wherever you define it
$pdo = new PDO('mysql:dbname=mydb;host=localhost','username','password');
// to insert
$statement = $pdo->prepare('INSERT INTO `sanjana` (name) VALUES (:name)');
// the following replaces :name with $usernames in a safe manner, defeating sql injection
$statement->bindParam(':name',$usernames);
$statement->execute(); // it is done
// to update
$statement = $pdo->prepare('UPDATE `sanjan` SET `name` = :name');
$statement->bindParam(':name',$usernames);
$statement->execute(); // it is done
so as you can see protecting your code from malicious input is not hard and it even makes your SQL statements a lot easier to read. Did you notice that you didn't even need to quote your values in the SQL statement anymore? Prepared statements take care of that for you! One less way to have an error in your code.
Please do read up on it, it will save you headaches. PDO even has the advantage that it's database independent, making it easier to use another database with existing code.
The right update sql clause is like so:
UPDATE table
SET column = expression;
OR
UPDATE table
SET column = expression
WHERE predicates;
SQL: UPDATE Statement
Your query should be like this:
$update = "UPDATE sanjana SET $name ='$usernames'";
mysql_query($update, $link);
Of course you need to specify a row to update (id), other wise, the whole table will set column $name to $usernames.
UPDATE:
Because you are inserting a data in empty table, you should first execute $update1 query then execute $update query. UPDATE clause will make no change/insert on empty table.
Problem 1: use the correct "insert into" (create new record) vs. "update" (modify existing record)
Problem 2: It's good practice to create your SQL string before you call mysql_query(), so you can print it out for debugging
Problem 3: It's also good practice to detect errors
EXAMPLE:
<?php
$link = mysql_connect('xxxxxxxx')
or die('Could not connect: ' . mysql_error());
mysql_select_db("xxx", $link);
$usernames='aneeshxx';
$sql = "INSERT INTO sanjana (name) VALUES ('" . $usernames + ")";
echo "sql: " . $sql . "...<br/>\n";
mysql_query($sql, $link)
or die(mysql_error());
You have INSERT keyword for your update SQL, this should be changed to UPDATE:
$update = "UPDATE sanjana SET $name ='$usernames'";

Categories