I'm making an Android app that connects to a database online and lets the user edit the database from the application, I'm new to PHP and MySql but from my research I think I should be using an UPDATE statement, I've written the code below to register new users on the site from a tutorial, but I'd like to change the INSERT statement to an UPDATE statement so that instead of registering a new user, the App updates existing data that I have entered in PHPMYADMIN, could someone show me how to do this? Also, if you require the code for the app mention it in the comments and I'll add it to the question, I don't want to post too much unneccessary code. Thanks in advance.
<?php
require "conn.php";
$patient_name = $_POST["patient_name"];
$check_in_date = $_POST["check_in_date"];
$room_number = $_POST["room_number"];
$bed_number = $_POST["bed_number"];
$notes = $_POST["notes"];
$mysql_qry = "insert into patients(patient_name, check_in_date, room_number, bed_number, notes) values ('$patient_name', '$check_in_date', '$room_number', '$bed_number', '$notes')";
if($conn->query($mysql_qry) === TRUE) {
echo "Insert successful";
}
else{
echo "Error: " . $mysql_qry . "<br>" . $conn->error;
}
$conn->close();
?>
EDIT
The fixed code is below, it now updates records already in the database rather than adding new data.
<?php
require "conn.php";
$patient_name = $_POST["patient_name"];
$check_in_date = $_POST["check_in_date"];
$room_number = $_POST["room_number"];
$bed_number = $_POST["bed_number"];
$notes = $_POST["notes"];
$mysql_qry = "UPDATE patients SET notes='$notes' WHERE patient_name='$patient_name'";
if($conn->query($mysql_qry) === TRUE) {
echo "Insert successful";
}
else{
echo "Error: " . $mysql_qry . "<br>" . $conn->error;
}
$conn->close();
?>
first of all this PHP code is vulnerable to sql injection you should, no need to update your code to use either mysqli prepared statement or PDO prepared statement
secondly the easiest way I know you accomplish your goal would make a unique constraint on some columns and then use a mysql feature ON DUPLICATE UPDATE
for this example I'll assume that the unique fields determining an update instead of an insert are patient_name, check_in_date, room_number, and bed_number (in case john smith was in the same room as john smith in seprate beds) the query to update the table would be like this
ALTER TABLE `patients` ADD UNIQUE `unique_index`(`patient_name`, `check_in_date`, `room_number`, `bed_number`);
so now to address the sql injection bit and the query, I'll update the example to use mysqli statement and will assume patient_name and notes are strings (varchar/nvarchar), room_number and bed_number are integers, and check_in_date is a date
Edit My original answer had a syntax error in the query and also passing variables to the prepared statement below is the updated answer
$mysqliConn = new mysqli("localhost", "my_user", "my_password", "mydatabase");
$stmt = $mysqliConn->prepare("insert into patients
(patient_name, check_in_date, room_number, bed_number, notes)
values (?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE notes=values(notes)");
$patient_name = $_POST["patient_name"];
$check_in_date = $_POST["check_in_date"];
$room_number = $_POST["room_number"];
$bed_number = $_POST["bed_number"];
$notes = $_POST["notes"];
mysqli_stmt_bind_param($stmt, "sdiis",
$patient_name, $check_in_date, $room_number, $bed_number, $notes);
hope this helps
Edit
Regarding the unique key, a unique key means that all fields in the unique key have to be unique when combined so for the example above
if record 1 is
patient_name, check_in_date, room_number, bed_number, notes
'john smith', '3/1/2017' , 413 , 2 , 'patient is sick'
and record two is
'jane doe' , '3/1/2017' , 413 , 2 , 'patient has wound'
these two records will note be duplicates with the above constraint but if you do need to change the constraint you can do the following
DROP the Constraint
ALTER TABLE `patients` DROP INDEX `unique_index`;
Then recreate the constraint like this
ALTER TABLE `patients` ADD UNIQUE `unique_index`(`patient_name`, `check_in_date`, `room_number`);
also if you named your constraint something other than unique_index you can find the key_name by running the following
SHOW INDEX FROM `patients`;
the name will be in the key_name column
additionally you may want to alter the last line of the query to be this in your php if you change the unique constraint so you can change bed number
ON DUPLICATE KEY UPDATE bed_number=values(bed_number), notes=values(notes)
You can also use REPLACE INTO, then you don't have to change the SQL statement. Let MySQL do the work for you.
https://dev.mysql.com/doc/refman/5.7/en/replace.html
<?php
require "conn.php";
$patient_name = $_POST["patient_name"];
$check_in_date = $_POST["check_in_date"];
$room_number = $_POST["room_number"];
$bed_number = $_POST["bed_number"];
$notes = $_POST["notes"];
$mysql_qry = "REPLACE INTO patients(patient_name, check_in_date, room_number, bed_number, notes) VALUES ('$patient_name', '$check_in_date', '$room_number', '$bed_number', '$notes')";
if($conn->query($mysql_qry) === TRUE) {
echo "Insert successful";
}
else{
echo "Error: " . $mysql_qry . "<br>" . $conn->error;
}
$conn->close();
Also, you should really take a look at using PDO with prepared statements and parameters.
https://secure.php.net/manual/en/pdo.prepare.php
Actually I was looking for a small function that converts an INSERT MySQL query to an UPDATE query. So maybe other people were looking for the same and I think this is what the original poster was looking for aswell... I couldnt find any so I made this simple function which works for my needs, ofcourse you will have to make sure your original query is safe from MySQL injection.
It will convert
INSERT INTO aaa (bbb, ccc) VALUES ('111', '222')
to
UPDATE aaa SET ccc='222' WHERE bbb='111'
Use the 2nd variable ($iColumn) to identify the WHERE statement.
function convertInsertToUpdate($sQuery, $iColumn = 1) {
$sNewQuery = "";
$iPos = strpos($sQuery, ' (');
$sTmpTable = substr($sQuery, 0, $iPos);
$iPos = strpos($sTmpTable, 'INSERT INTO ');
$sTmpTable = substr($sTmpTable, $iPos+12);
$iPos = strpos($sQuery, ') VALUES (');
$sTmpValues = substr($sQuery, $iPos+10);
$iPos = strrpos($sTmpValues, ')');
$sTmpValues = substr($sTmpValues, 0, $iPos);
$iPos = strpos($sQuery, '(');
$sTmpColumns = substr($sQuery, $iPos+1);
$iPos = strpos($sTmpColumns, ') VALUES (');
$sTmpColumns = substr($sTmpColumns, 0, $iPos);
$aColumns = explode(', ', $sTmpColumns);
$aValues = explode(', ', $sTmpValues);
if (count($aColumns)>0 && count($aColumns) == count($aValues) && $iColumn < (count($aValues)+1)) {
$sNewQuery = "UPDATE ".$sTmpTable." SET";
$sTmpWhere = "";
$bNotFirst = false;
$iX = 0;
while ($iX<count($aColumns)) {
if ($iColumn == ($iX+1)) {
$sTmpWhere = " WHERE ". $aColumns[$iX]."=".$aValues[$iX];
$iX++;
continue;
}
if ($bNotFirst) {
$sNewQuery .= ",";
}
$sNewQuery .= " ".$aColumns[$iX]."=".$aValues[$iX];
$bNotFirst = true;
$iX++;
}
$sNewQuery .= $sTmpWhere;
}
return $sNewQuery;
}
Related
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
Im trying to take input from a form, then check table (user) if that name exsits and I need to grab the uid colum.
Input (username / MSG) > Check for username > if so get uid > else add user(This I got) > take uid and use when i INSERT the msg into its table (message)
Table structure:
user: uid (Unique) | name
Heres where in at PHP whise:
<?php
$name = $_GET["name"];
$message = $_GET["message"];
$checkn = "SELECT 1 FROM user WHERE name = $name";
$sql = "INSERT INTO user (uid, name) VALUES ('','$name')";
$msg = "INSERT INTO message (uid, message) VALUES ('$uid','$message')";
$uid = "SELECT uid FROM user WHERE name = $name";
$result = $conn->query($checkn);
if ($conn->query($checkn) === TRUE) {
echo "Checkn TRUE";
}else {
echo "<br> SHEEET" . $checkn . $conn->error;
}
$conn->close();?>
I erased the bulk to start over and get this fixed so once I can get this portion done I have the add if user doesn't exist. Thank you.
I think You are writing the query wrong, when using PHP you should write the query inside ' if it contains variable. " won't parse the variable value.
Replace :
$checkn = "SELECT 1 FROM user WHERE name = $name";
With:
$checkn = 'SELECT 1 FROM user WHERE name = $name';
And it should work. Do the same with other queries too. Use ' instead of "
Hope it helps.
Just from the top of my head
<?php
$name = $_GET["name"];
$message = $_GET["message"];
$checkn = sprintf('SELECT 1 FROM `user` WHERE `name` = \'%s\'', $name);
$sql = sprintf('INSERT INTO `user` (`uid`, `name`) VALUES (\'\',\'%s\')', $name);
$msg = sprintf('INSERT INTO `message` (`uid`, `message`) VALUES (\'%s\',\'%s\')', $uid, $message);
$uid = sprintf('SELECT `uid` FROM `user` WHERE `name` = \'%s\'', $name);
$result = $conn->query($checkn);
if ($conn->query($checkn) == TRUE) {
echo "Checkn TRUE";
} else {
echo "<br> SHEEET" . $checkn . $conn->error;
}
$conn->close();
?>
for some reason i have sometimes had problems when i did not put ` around table names.
I have also separated the variable interpolation so it makes it easier to secure it for sql injection (i did not secure it).
You used triple === this means its strict but mysql would pass 1 back which when using strict is not true.
Hope it helps
I'm having a problem with inserting info into the database. Strangely the update query works but not the insert query. I don't get any error either when submitting, it goes through correctly and echo account saved but nothing is inserted. What am i missing or doing wrong. please assist
if(isset($_POST['Submitaccount'])){
$allowedusers = $_POST['users'];
$accountid = trim($_POST['accountid']);
if(!$_POST['copyperms']) $_POST['copyperms']='N';
if(!$_POST['allusers']) $_POST['allusers']='N';
if(!$_POST['enabled']) $_POST['enabled']='N';
if(!$_POST['servertime']) $_POST['servertime']='N';
if(!$_POST['delremovals']) $_POST['delremovals']='N';
unset($_POST['Submitaccount']);
unset($_POST['accountid']);
unset($_POST['users']);
$notmust = array("email" , "skip" , "comments" , "firstmod");
foreach($_POST as $key=>$val){
if(!trim($val) && !in_array($key , $notmust)) {
$err = 1;
$empty = "$key";
break;
}
$qpart .= "`$key` = '".mysql_escape_string($val)."' , " ;
}
if($qpart) $qpart = substr($qpart , 0 , -2);
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
}
}
if(!$err){
if(!$accountid){
$q = "INSERT into accounts SET $qpart ";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}
This is because the INSERT command has different syntax:
INSERT into accounts SET $qpart "
is not usual, you can write it like this:
INSERT into accounts (column names) VALUES your values"
13.2.5 INSERT Syntax
You have double if(!$err){. Do you want both (!$err) into one? If the first (!$err) is for indicator for the second to insert, function SELECT can not be placed above the function INSERT indirectly.
try this:
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
// if(!$err){ again ...
if(!$accountid){
$q = "INSERT into accounts SET (column1) VALUES ($var1)";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}
else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}
}
else{
//other code to handle if ($err)
}
Note: I would prefer using PDO to handle database, it's so simple scripting, besides, it's no longer supported
You have to understand that mysql functions have become deprecated. Either using mysqli or pdo would be the better option, but if you absolutely have to use mysql as a solution i would suggest not posting the form to itself, rather post to another php file as you will have less problems.In my environment it seems to work well as an interim solution while we are rewriting everything to use mysqli.If it a go and let me know.
I am trying to store data in two tables, using two different queries.
one of them is working fine but other one is not saving anything . These two queries are part of full page script. The frist queries in both the cases are part of the scripts and working fine.
the 2nd queries are written by me to make another records of user clicks.
Table structure for actcontest .. table name is actcontest not act_contest, this was copy/paste mistake here:[corrected]
userid varchar(50)
type varchar(50)
points int(10)
date date
Case 1:
The working query:
$sql = $Db1->query('Insert into ptcwalllogs (userid, user_earned)
values ('.$credituser.','.$rate.')');
Problem with the query:
$sqlact = $Db1->query('Insert into actcontest (userid, type, points, date)
values ('$username','ptcwall',6,now())');
Case 2:
working query:
$Db1->query("INSERT INTO `likesasapaddon` (user_id, page_id,date)
VALUES('{$thismemberinfo[userid]}', '{$get['pageid']}',NOW())");
Problem with the query:
$Db1->query("INSERT INTO `actcontest` (userid, type, points, date)
VALUES ('$username','facebook',6,now())");
in both the cases I want to store values in same table.
Below is the script file for case 1:
This is postback from one the providers.
<?php
$date1 = date('Y-m-d');
include("config.php");
include("includes/mysql.php");
$Db1 = new DB_sql;
$Db1->connect($DBHost, $DBDatabase, $DBUser, $DBPassword);
$your_pwd = ""; /* Postback Password */
$vip=getenv('REMOTE_ADDR');
$sent_pw = $_GET['pwd'];
$credited = intval($_GET['c']);
$credituser = intval($_GET['usr']);
$rate = trim($_GET['r']);
$type = intval($_GET['t']);
$allowed_ip = array('72.52.253.202');//PTCWall's IPS.
if(in_array($vip, $allowed_ip) && $sent_pw == $your_pwd)
{
if($credited == '1')
{
if($type == '1')
{
$run = $Db1->query('UPDATE user SET balance=balance+'.$rate.' WHERE userid = '.$credituser);
// This line below is used to store clicks locally
$sql = $Db1->query('Insert into ptcwalllogs (userid, user_earned) values ('.$credituser.','.$rate.')');
$sqlact = $Db1->query("Insert into actcontest (userid, type, points, date)
values ('".mysqli_real_escape_string($username)."','ptcwall',6,now())");
// $sqlact = $Db1->query('Insert into actcontest (userid, type, points, date) values ("lorry","ptcwall",6,now())');
if($run)
{
exit('ok');
} else{
exit('issue');
}
}elseif($type == '2'){
$run = $Db1->query('UPDATE user SET points=points+'.$rate.' WHERE userid = '.$credituser);
if($run)
{
exit('ok');
} else{
exit('issue');
}
}
}elseif($credited == '2')
{
if($type == '1')
{
$run = $Db1->query('UPDATE user SET balance=balance-'.$rate.' WHERE userid = '.$credituser);
if($run)
{
exit('ok');
} else{
exit('issue');
}
}elseif($type == '2'){
$run = $Db1->query('UPDATE user SET points=points-'.$rate.' WHERE userid = '.$credituser);
if($run)
{
exit('ok');
} else{
exit('issue');
}
}
}
}
else{
die();
}
//FILE 03302014
?>
After the Var dump:
saved in separate file.
daata.php
<?php
$sqlact = $Db1->query("Insert into actcontest (userid, type, points, date)
values ('".mysqli_real_escape_string($username)."','ptcwall',6,now())");
var_dump($sqlact);
echo " success asdasdasdasdasdasdasdasdas " ;
?>
error:
Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given in ./xxxx/daata.php on line 3
bool(true)
Kindly guide.
Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given in ./xxxx/daata.php on line 3 bool(true)
This warning means that you need to pass your DB connection to it, that is the second parameter it is expecting.
('".mysqli_real_escape_string($Db1, $username)."','ptcwall',6,now())")
Consult the documentation:
http://php.net/manual/en/mysqli.real-escape-string.php
$sqlact = $Db1->query("Insert into act_contest (userid, type, points, date)
values ('".mysqli_real_escape_string($Db1, $username)."','ptcwall',6,now())");
$Db1->query("INSERT INTO `actcontest` (userid, type, points, date)
VALUES ('".mysqli_real_escape_string($Db1, $username)."','facebook',6,now())");
Also, make sure that all your columns do exist in your table.
Add:
die('There was an error running the query [' . $Db1->error . ']');
This will signal an error, should there be any.
I.e.:
if($run)
{
exit('ok');
} else{
die('There was an error running the query [' . $Db1->error . ']');
}
Follow that same method for all your queries.
It's also a good thing to add error reporting to the top of your file(s) which will help during production testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
should $username or any other variables be undefined.
Here are working queries:
$sqlact = $Db1->query("Insert into act_contest (userid, type, points, date)
values ('".mysqli_real_escape_string($username)."','ptcwall',6,now())");
$Db1->query("INSERT INTO `actcontest` (userid, type, points, date)
VALUES ('".mysqli_real_escape_string($username)."','facebook',6,now())");
NB: Always use mysqli_real_escape_string (or it equivalent) for strings in SQL query. Or your application will be hacked soon with SQL injection.
Are you sure of your table name "actcontest" ? In the first case, you put an underscore in it and not in the second one.
Are you also sure of this table schema : userid, type, points and date ? Maybe you made a little typo ?
If I were you, I'll first check all of that.
I'm trying to find a person in my table and update their score. This is the code I have right now. For some reason it's not working. Instead of changing the person's score, it will just make a new row with the same name of the person.
$name = $_POST["strtolower(name)"];
$team = $_POST["team"];
$num = $_POST["number"];
$goals = $_POST["goals"];
if($query = mysqli_query("SELECT goals FROM goalscorers WHERE name=$name ", $db)){
while($row = mysqli_fetch_assoc($query)){
$origgoals = $row['goals'];
$newgoals = (int)$origgoals + (int)$goals;
mysqli_query($db, "UPDATE goalscorers SET goals=$newgoals WHERE name=$name ");
echo "<h1>Thank you for submitting your details! <br /> Add another</h1>";
}
mysqli_free_result($query);
}
else {
$query = "INSERT INTO goalscorers (name, team, num, goals) VALUES ('$name','$team','$num','$goals') ";
$result = mysqli_query($query, $db);
if (mysqli_error()) { print "Database ERROR: " . mysql_error(); }
echo "<h1>Thank you for submitting your details! <br /> Add another</h1>";
}
I'm very new to both PHP and MySQL so it's probably a basic mistake.
Also, I already am connected to the database.
Your immediate problem is that you don't have quotes around string values in your sql queries. Change
"SELECT goals FROM goalscorers WHERE name=$name "
to
"SELECT goals FROM goalscorers WHERE name = '$name'"
^ ^
and
"UPDATE goalscorers SET goals=$newgoals WHERE name=$name "
to
"UPDATE goalscorers SET goals=$newgoals WHERE name = '$name'"
^ ^
On a side note: learn and use prepared statements. Your code is vulnerable to sql injections.
UPDATE1: You can drastically simplify your code with INSERT ... ON DUPLICATE KEY UPDATE. In order for it to work properly you have to have a UNIQUE (PRIMARY KEY) index on name column.
Your insert statement then should look like
INSERT INTO goalscorers (`name`, `team`, `num`, `goals`)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE goals = goals + VALUES(goals)
Here is SQLFiddle demo
UPDATE2: Now your code with INSERT ... ON DUPLICATE KEY UPDATE and prepared statement can look like this
$name = $_POST['name'];
$team = $_POST['team'];
$num = $_POST['number'];
$goals = $_POST['goals'];
/* connect to the database*/
$db = new mysqli('localhost', 'user', 'userpwd', 'test');
/* check connection */
if ($db->connect_errno) {
die('Connection failed: ' .$db->connect_error);
}
$sql = 'INSERT INTO goalscorers (`name`, `team`, `num`, `goals`)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE goals = goals + VALUES(goals)';
/* create a prepared statement */
if ($stmt = $db->prepare($sql)) {
/* bind parameters for markers */
$stmt->bind_param("ssii", $name, $team, $num, $goals);
/* execute query */
if ($stmt->execute()) {
echo '<h1>Thank you for submitting your details! <br /> Add another</h1>';
} else {
die('Insert failed: ' .$db->error);
}
/* close statement */
$stmt->close();
} else {
die('Statement prepare failed: ' .$db->error);
}
I want to insert number of records using following script. But, only the first one gets inserted. After that, it just stops without showing any error. What is wrong with these prepared statement execution?
//$dbc = database connection //shortan here
// $mid[] = {1,2,3,4}; //sortened here.
$q5 = "INSERT INTO user_book_trn(user_id, member_id, book_id, date_read, lang_id) VALUES (?, ?, ?, now(), ?)";
$s5 = mysqli_prepare($dbc, $q5);
//Bind the variables:
mysqli_stmt_bind_param($s5, 'iiii', $user_id, $member_id, $book_id, $lang_id);
foreach($mid as $mk => $mv) { //check for each selected check box value from member list:
$q2 = "SELECT user_id, member_id, book_id FROM user_book_trn WHERE user_id = {$_SESSION['myuser']['userid']} and member_id = {$mv} and book_id= {$w}";
$r3 = mysqli_query($dbc, $q2);
if (mysqli_num_rows($r3) == 0) { //title is available for this user.
//Assign the values to variables:
$user_id = (int)$_SESSION['myuser']['userid'];
$member_id = (int)$mv;
$book_id = (int)$w;
$lang_id = (int)$_SESSION['lid'];
//just to check each iteration gets new values:
echo "user_id : $user_id \n";
echo "member_id : $member_id \n";
echo "book_id : $book_id \n";
//Execute the query:
mysqli_stmt_execute($s5);
if (mysqli_affected_rows($dbc) == 1) {
//this runs ok just for the first iteration.. Why?
echo "<p><b> The book $t is added. </b></p>";
$_SESSION['bookid'] = $book_id;
}
}
}
Don't know the exact details, but as far as I know the prepared statement is bound to a result set after execution. You need to reset it first
mysqli_stmt_reset($s);
http://php.net/mysqli-stmt.reset
Additional you should consider using useful variable names. And because you mentioned, that you cannot see any error:
mysqli_stmt_error_list($s5);
http://php.net/mysqli-stmt.error-list
http://php.net/mysqli-stmt.errno
http://php.net/mysqli-stmt.error