SQL database not updating data in PHP [duplicate] - php

This question already has answers here:
How to view query error in PDO PHP
(5 answers)
Closed 2 years ago.
I'm trying to update some data from my database but nothing I've tried/found has been of any success to me. There are no errors or anything, literally nothing happens. The page reloads but it does not store anything into the database. How can I fix this problem?
The code:
function AddToBook() {
$get_post_id = filter_var(htmlentities($_GET['pid']), FILTER_SANITIZE_NUMBER_INT);
$book_id = filter_var(htmlentities($_GET['bid']), FILTER_SANITIZE_NUMBER_INT);
$get_episodes = filter_var(htmlentities($_GET['ep']), FILTER_SANITIZE_NUMBER_INT);
$episode = $get_episodes + 1;
// Insert book data into wpost
$odb = new PDO("mysql:host=localhost;dbname=test", 'root', '');
$updatePostRecord = "UPDATE wpost SET book_id=:book_id, episode_number=:episode WHERE id=:get_post_id";
$UpdatePost = $odb->prepare($updatePostRecord);
$UpdatePost->bindParam(':book_id',$book_id,PDO::PARAM_INT);
$UpdatePost->bindParam(':episode',$episode,PDO::PARAM_INT);
$UpdatePost->bindParam(':get_post_id',$get_post_id,PDO::PARAM_INT);
$UpdatePost->execute();
// Insert post data into books
$updateBookRecord = "UPDATE books SET episodes='$episode' WHERE id='$book_id'";
$UpdateBook = $conn->prepare($updateBookRecord);
$UpdateBook->execute();
}

You want to use the PDO class that you have defined there instead of $conn (that is not defined), might as well put the variables into brackets just to make sure they are interpreted correctly, if you use a string literal.
$updateBookRecord = "UPDATE books SET episodes='{$episode}' WHERE id='{$book_id}'";
$UpdateBook = $obd->prepare($updateBookRecord);
$UpdateBook->execute();
Also, as it stand right now this is not a proper prepared statement. You should use bindParam function like on the initial UpdatePost.
Here is how it would look as a proper prepared statement.
$updateBookRecord = "UPDATE books SET episodes=:episode WHERE id=:book_id";
$UpdateBook = $obd->prepare($updateBookRecord);
$UpdateBook->bindParam(':episode',$episode,PDO::PARAM_INT);
$UpdateBook->bindParam(':book_id',$book_id,PDO::PARAM_INT);
$UpdateBook->execute();

An update can successfully update 0 rows. I would triple check your WHERE clause to see if it is actually trying to match existing rows.

When you use single quotes '' with variable, php understand it as a string not variable. so you might want to change your update statement to
$updateBookRecord = "UPDATE books SET episodes = $episode WHERE id= $book_id ";
or alternatively
$updateBookRecord = "UPDATE books SET episodes = ". $episode . " WHERE id= ".$book_id;
However this is not the standard way to do things, and invite sql injections, you better use PDO or other mechanism to make it more secure. https://www.w3schools.com/sql/sql_injection.asp

Related

PHP posting a variable in a variable using mysql

I need to use the number of the district to be the tail end of my variable. Example $publish_page_ADD THE DISTRICT NUMBER
I am grabbing the $district_num from my url which I've verified with echo
Here is what I've tried
$district_num = $_REQUEST['district_num']; // from url and works
$publish_page_.''.$district_num = $district_var['publish_page_'.$district_num.'']; //this does not work
$publish_page_.''.$district_num = addslashes($_POST['publish_page_'.$district_num.'']); //this does not work
$sql = "UPDATE districts SET
publish_page_$district_num = '$publish_page_$district_num' //this does not work and throws error "can not find publish_page_ in field list
WHERE district_num ='$district_num'"; //this works when the above code is removed
Follow up on corrected code... Thank You #cale_b and #Bill Karwin
$district_num = (int) $_REQUEST['district_num'];
$$publish_page = "publish_page_{$district_num}";
$$publish_page = $district_var[ "publish_page_{$district_num}"];
if (isset($_POST['submitok'])):
$$publish_page = addslashes($_POST[$publish_page]);
$sql = "UPDATE districts SET
publish_page_{$district_num} = '$publish_page'
WHERE district_num ='$district_num'";
If you want to learn about PHP's variable variables, it's in the manual (I linked to it). But you actually don't need it in your case.
Be careful about SQL injection. Your code is vulnerable to it.
Since you're using input to form a SQL column name, you can't use SQL query parameters to solve it. But you can cast the input to an integer, which will protect against SQL injection in this case.
$district_num = (int) $_REQUEST['district_num'];
$publish_page_col = "publish_page_{$district_num}";
The above is safe because the (int) casting makes sure the num variable is only numeric. It isn't possible for it to contain any characters like ' or \ that could cause an SQL injection vulnerability.
For the other dynamic values, use query parameters.
$publish_page_value = $_REQUEST["publish_page_4{$district_num}"];
$sql = "UPDATE districts SET
`$publish_page_col` = ?
WHERE district_num = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([ $publish_page_value, $district_num ]);
As #cale_b comments below, you should understand that in PHP, variables can be expanded inside double-quoted strings. See http://php.net/manual/en/language.types.string.php#language.types.string.parsing for details on that.

Q: PostGreSQL How to Pass POST information in a SQL command more efficiently

I have a page that brings up a users information and the fields can be modified and updated through a form. Except I'm having some issues with having my form update the database. When I change the update query by hardcoding it works perfectly fine. Except when I pass the value through POST it doesn't work at all.
if (isset($_POST['new']))
{
$result1 = pg_query($db,
"UPDATE supplies.user SET
id = '$_POST[id_updated]',
name = '$_POST[name_updated]',
department = '$_POST[department_updated]',
email = '$_POST[email_updated]',
access = '$_POST[access_updated]'
where id = '$_POST[id_updated]'");
if (!$result1)
{
echo "Update failed!!";
} else
{
echo "Update successful;";
}
I did a vardump as an example early to see the values coming through and got the appropriate values but I'm surprised that I get an error that the update fails since technically the values are the same just not being hardcoded..
UPDATE supplies.user SET name = 'Drake Bell', department = 'bobdole',
email = 'blah#blah.com', access = 'N' where id = 1
I also based the form on this link here for guidance since I couldn't find much about PostGres Online
Guide
Try dumping the query after the interpolation should have happened and see what query you're sending to postgres.
Better yet, use a prepared statement and you don't have to do variable interpolation at all!
Do not EVER use data coming from external sources to build an SQL query without proper escaping and/or checking. You're opening the door to SQL injections.
You should use PDO, or at the very least pg_query_params instead of pg_query (did you not see the big red box in the manual page of pg_query?):
$result1 = pg_query($db,
"UPDATE supplies.user SET
id = $1,
name = $2,
department = $3,
email = $4,
access = $5
WHERE id = $6",
array(
$_POST[id_updated],
$_POST[name_updated],
$_POST[department_updated],
$_POST[email_updated],
$_POST[access_updated],
$_POST[id_updated]));
Also, when something goes wrong, log the error (pg_last_error()).
By the way, UPDATE whatever SET id = some_id WHERE id = some_id is either not really useful or not what you want to do.

how to update data in php mysql?

Let's say I want to update a message row without deleting the previous message. For example: row message has the current value "hello", now I want to add "hi" without replacing the word "hello". So the result should be "hello hi".
I've tried the code below but it won't work:
$text="hi";
$sql = "UPDATE class SET message= message+'$text' WHERE id=2";
or
$sql = "UPDATE class SET message= 'message'.'$text' WHERE id=2";
sorry, im not really good at english. thanks for the help
you can do use the mysql's concat() function to append data to a field:
$sql = "update class set message = concat(ifnull(message,"")," ".'$text') where id=2";
You may also want to consider a space before appending the new content!
Well, you should first of all you should really learn about SQL injection (and how to prevent it, including Prepared Statements).
You can do this in SQL using the CONCAT() function:
$sql = "UPDATE class SET message = CONCAT(message, '$text') WHERE id=2";
Try CONCAT instead, in your mysql query.
$text = "hi";
$myQuery = "UPDATE class SET message= CONCAT(message,'".$text."') WHERE id=2";
You should use the CONCAT function which is used to concatenate strings.
Here since you are using the content of a php variable, it is good to escape the php variable from mysql query like '".$text."';
Have a look at the CONCAT() Function of MySql:
$sql = "UPDATE class SET message=CONCAT(message, '".$text."') WHERE id=2";
should do the trick.
You could try this:
$sql = "UPDATE class SET message=CONCAT(message, '$text') WHERE id='2'";
However, be aware that this is vulnerable to SQL Injections

Updating MySQL DB with PHP

I'm using foreach to loop an array and update a MySQL database.
This is my code
foreach($result['getHiscore'] as $highScoreType => $highScoreValues){
$rank = $highScoreValues['rank'];
$lvl = $highScoreValues['lvl'];
$totalXp = $highScoreValues['totalxp'];
mysqli_query($con,"UPDATE Users SET Level("$highScoreType") = $lvl, Xp("$highScoreType") = $totalXp,
WHERE UserID= '1'");
}
i'm trying to conflate the word "level" with the contents of $highScoreType, the column titles in my DB are Leveloverall, Xpoverall, Levelattack, Xpattack and so on so i was planning on keeping the Level/Xp title constant and just changing the key.
This looks fine to me and when i tested the sql with pre-set values it updated fine, however using the variables doesn't update at all. I know that the variables are coming out of the array correctly as when i echo them inline with the foreach they print out in the correct format and order.
Is it my formatting thats the issue or am i doing missing something else?
If you echo the generated SQL query that should help you see any problems in the query.
It looks odd to me: UPDATE Users SET Level("$highScoreType") = $lvl
Shouldn't that just be UPDATE Users SET $highScoreType = $lvl ?
Be aware also that this sort of code is vulnerably to SQL injection attacks so always be wary of what could be in those variables.
To print the query do:
$query = "UPDATE Users SET Level("$highScoreType") = $lvl, Xp("$highScoreType") = $totalXp, WHERE UserID= '1'"
echo $query
mysqli_query($con, $query)

SQL Table not updating in PHP

I'm trying to create an update function in PHP but the records don't seem to be changing as per the update. I've created a JSON object to hold the values being passed over to this file and according to the Firebug Lite console I've running these values are outputted just fine so it's prob something wrong with the sql side. Can anyone spot a problem? I'd appreciate the help!
<?php
$var1 = $_REQUEST['action']; // We dont need action for this tutorial, but in a complex code you need a way to determine ajax action nature
$jsonObject = json_decode($_REQUEST['outputJSON']); // Decode JSON object into readable PHP object
$name = $jsonObject->{'name'}; // Get name from object
$desc = $jsonObject->{'desc'}; // Get desc from object
$did = $jsonObject->{'did'};// Get id object
mysql_connect("localhost","root",""); // Conect to mysql, first parameter is location, second is mysql username and a third one is a mysql password
#mysql_select_db("findadeal") or die( "Unable to select database"); // Connect to database called test
$query = "UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}";
$add = mysql_query($query);
$num = mysql_num_rows($add);
if($num != 0) {
echo "true";
} else {
echo "false";
}
?>
I believe you are misusing the curly braces. The single quote should go on the outside of them.:
"UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}"
Becomes
"UPDATE deal SET dname = '{$name}', desc='{$desc}' WHERE dealid = '{$did}'"
On a side note, using any mysql_* functions isn't really good security-wise. I would recommend looking into php's mysqli or pdo extensions.
You need to escape reserved words in MySQL like desc with backticks
UPDATE deal
SET dname = {'$name'}, `desc`= {'$desc'} ....
^----^--------------------------here
you need to use mysql_affected_rows() after update not mysql_num_rows

Categories