how to update data in php mysql? - php

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

Related

SQL database not updating data in PHP [duplicate]

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

Why does this UPDATE query not update my table?

I am trying to code a user system. I am having an issue with the activation part. I can select and insert data to my table but now I am trying to create an update statement and got stuck.
<?PHP
include "db_settings.php";
$stmt = $dbcon->prepare("UPDATE 'Kullanicilar' SET 'Aktivasyon' = ? WHERE 'KullaniciID'=?");
// execute the query
$stmt->execute(array('1','5'));
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
?>
And I am getting error as:
"0 records UPDATED successfully".
This is my table; http://i.imgur.com/PL2eD80.png
I have tried by changing my 'Aktivasyon' type int to char but it also does not work.
EDIT:
I am trying to make this a function;
function dataUpdate($tableName, $updateRow, $updateValue, $conditonRow, $conditionValue)
{
include "db_settings.php";
$q = $dbcon->prepare("UPDATE $tableName SET $updateRow= ? WHERE $conditonRow= ?");
$q->execute(array($updateValue,$conditionValue));
}
I also try this :
...
$q = $dbcon->prepare("UPDATE `$tableName` SET `$updateRow`= ? WHERE `$conditonRow`= ?");
...
How can I make this statement work?
You are using wrong quotes. You are basically saying "update this table, set this string to something when the string KullaniciID equals the string 5" which of course never is true.
You should use backticks ` if you want to specify column names. Then your query would work. Usually you don't even need those, but for some reason MySQL world is always adding them.
So to clarify, this is a string: 'KullaniciID' and this is a column name: `KullaniciID`.
Also you should not send integers as strings. It causes extra conversions or even errors with more strict databases.

php insert data from fetch array to other table on version 5.4

I have moved to IIS 8 in PHP 5.4. I am trying to collect data from a table and insert them to a different one, i know my code is correct, but seems to be not working, probably because of the php version, can anyone help me?
here's my code
$query = odbc_exec($conn, "SELECT * FROM member");
while($rows = odbc_fetch_array($query)) {
$querystring = "INSERT INTO oldusers (username, password, regdate) VALUES ('$rows['userid']', '$rows['passwd']', '$rows['registdate']')";
$query2 = odbc_exec($conn, $querystring);
odbc_free_result($query2);
//echo $rows['userid']." ".$rows['passwd']." ".$rows['registdate']."<br>";
}
thanks in advance.
instead trying to insert one by one record, better to insert like below:
INSERT INTO oldusers (username, password, regdate) SELECT userid,passwd,registdate FROM member
for more information :http://dev.mysql.com/doc/refman/5.5/en/insert-select.html
You're placing $rows['passwd'] inside of a double-quoted string. Instead you should do:
$str = "some sql $rows[passwd] rest of sql"; // notice the absence of single quotes
or:
$str = "some sql {$rows['passwd']} rest of sql";
or (I think this way is most readable):
$str = 'some sql' . $rows[passwd] . ' rest of sql';
If your column contains text you'll need to add surrounding single quotes where necessary.
Having said all that, you should instead use parameterized queries (if your database supports it) as it's safer (from SQL injection). If that's unavailable you will at the very least need to escape the data before concatenating it to the string.

Can not use POST variable in PHP insert query

In my PHP file I do the following
<?php
if(isset($_POST['submit'])){
$con = mysqli_connect(bla);
$query = "insert into users (name,username,password) values($_POST['name'],$_POST['username'],$_POST['password'])";
}
Now, even if if condition is not satisfied, that is when submit is not done, I get error. But when I comment my $query = ... line, there is no error. What is happening?
You need to put '". around your variables, like this:
$query = "insert into users (name,username,password) values('".$_POST['name']."','".$_POST['username']."','".$_POST['password']."')";
place any $_POST['...'] between {}
Like '{$_POST['password']}','...
put this code At the end for display Errors:
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
exit();
}
When you interpolate an array variable into a string, there are two ways to write it: either put curly braces around the variable, or leave out the quotes in the index:
$query = "insert into users (name,username,password)
values('{$_POST['name']}', {'$_POST['username']}', {'$_POST['password']'})";
You also need quotes in the query itself, for correct SQL syntax.
Consider putting your post values into local variables first and then enter the local variables as the values of the insert query. ex:
$name = $_POST['name'];
$query= INSERT INTO users(name)VALUES("$name")

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