INSERT into sql database [closed] - php

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I've inserted into databases before but never used the 'where' feature. For some reason, it is not inserting, but dieing instead.
<?php
$member=$_SESSION['member'];
$SQL = "INSERT into members where name='$member'(money) VALUES ('100')";
mysql_query($SQL) or die("Could not insert money");
print "Money successfully inserted";
?>

This is not valid SQL:
INSERT into members where name='$member'(money) VALUES ('100')
I would assume something like this:
update `members` set `money`=100 where `name`='$member';
Rationale: (money) is a field and 100 is the value for money (since those 2 make the most sense from a INSERT INTO members (field) VALUES (value) syntax point of view).

Never die() with a fixed error message, especially when you can output the actual reason: ... or die(mysql_error()).
But yes, your problem is a syntax error. INSERT queries do NOT have a WHERE clause - where is used to filter records already in the database table. This makes no sense for a new record, because it's not IN the table to filtered in the first place.
You query should basically be just
INSERT into members (name, money) VALUES ('$member', '100')
And note that you are vulnerable to SQL injection attacks, and are using a deprecated/obsolete database interface.

If you want to change existing data, use the update command instead of insert.

You can't use WHERE clause with INSERT command
http://dev.mysql.com/doc/refman/5.0/en/insert.html
You have to do an update
<?php
$member=$_SESSION['member'];
$SQL = "UPDATE `members` SET `money`='100' WHERE `name`='$member'; ";
mysql_query($SQL) or die("Could not insert money");
print "Money successfully inserted";
?>

For inserting :
$SQL = "INSERT INTO members(money) VALUES ('100')";
MySQL INSERT Syntax does not support the WHERE clause. MySQL.com Insert Info
Are you actually trying to insert a new row, or update an existing 'member'? If update, then try:
UPDATE members SET money = 100, WHERE name='$member';

Related

Is this the correct way to update / insert records using PHP? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm writting a HTML form for newsletter subscribers. So far the form ignores duplicates entries by making the subscriber_email field unique in the mysql table and using:
"INSERT IGNORE INTO newsletter_subscriber_popup (subscriber_name, subscriber_email)
VALUES ('$subscriber_name', '$subscriber_email')";
I'm trying to improve the form so it updates the other fields when the email already exists in the table, and if the email does not exists then it inserts a new record. For that I'm doing this (so far it works but I feel it's not the proper way to do it):
//HTML form variables----------------------------------------------------//
$subscriber_name = mysql_real_escape_string($_POST['subscriber_name']);
$subscriber_email = mysql_real_escape_string($_POST['subscriber_email']);
//Try update into DB---------------------------------------------------------//
$sqlUpdate =
"UPDATE newsletter_subscriber_popup
SET subscriber_name = '$subscriber_name'
WHERE subscriber_email = '$subscriber_email'";
if(!mysql_query($sqlUpdate)){
//Insert into DB--------------------------------------------------------//
$sqlInsert =
"INSERT IGNORE INTO newsletter_subscriber_popup (subscriber_name, subscriber_email)
VALUES ('$subscriber_name', '$subscriber_email')";
if(!mysql_query($sqlInsert)){
die('Error: ' .mysql_error());
}
}
The scripts works when the subscriber_email exists and it updates the other fields but it fails when it should insert a new record.
EDIT----------------------------
ON DUPLICATED KEY UPDATE is what I was looking for. The script now updates the other fields when the subscriber_email already exists, and insert a new record when the the subscriber_email does not exists.
//HTML form variables----------------------------------------------------//
$subscriber_name = mysql_real_escape_string($_POST['subscriber_name']);
$subscriber_email = mysql_real_escape_string($_POST['subscriber_email']);
//Insert into DB--------------------------------------------------------//
$sqlName =
"INSERT IGNORE INTO newsletter_subscriber_popup (subscriber_name, subscriber_email)
VALUES ('$subscriber_name', '$subscriber_email')
ON DUPLICATE KEY UPDATE subscriber_name = '$subscriber_name'";
if(!mysql_query($sqlName)){
die('Error: ' .mysql_error());
}
Note: Thanks for all the advices about sql injection but the question wasn't about security.
INSERT .. ON DUPLICATE KEY UPDATE may be just what you are looking for. see https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
You need to have an unique constraint on subscriber_email though.
NO. It is not SQL-injection-proof. If somwone enters 'a or 1 = 1 ' as subscriber_email, he will update all of your entries. have a look on Wikipedia: SQL-Injection and PHP-Doc to prepared statements
First off, at least use sqli instead of sql. here is a good documentation on sql injection in PHP http://php.net/manual/en/security.database.sql-injection.php
Also, if you're not sure about the inputs that are coming from the user (e.g. email address), then you can use an email parser http://php.net/manual/en/ref.mailparse.php (server side). It's a good practice to validate the value on both client and server side.
Remember, more rules for the form entries means more security and thereby less sql injection vulnerability.

PHP mysql query insert where [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm trying to confirm a users email where the users verification key is the variable $verify_mod. However, I get the 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 'WHERE verification='72b4ad7ee82dd6e177f2588c168abb51user=test123'' at line 1
Here's my query:
$confirm_query = "INSERT INTO users (confirm_email) VALUES ('1') WHERE verification='$verify_mod'";
The INSERT statement doesn't go with a WHERE clause. Either you're trying to insert something, in which case you should remove the WHERE clause, or you want to modify a value, in which case you should use UPDATE .. SET.
// For an insert:
$confirm_query = "INSERT INTO users (confirm_email) VALUES ('1')";
// For an update:
$confirm_query = "UPDATE users SET confirm_email='1' WHERE verification='$verify_mod'";
Besides that, it's always a good idea to put ` characters around table and column names to reduce the risk of SQL injection. So:
// For an insert:
$confirm_query = "INSERT INTO `users` (`confirm_email`) VALUES ('1')";
// For an update:
$confirm_query = "UPDATE `users` SET `confirm_email`='1' WHERE `verification`='$verify_mod'";
Lastly, I don't know if you're using mysqli_* functions or PDO or mysql_* functions (in the latter case you should definitely change to one of the others as mysql_* is deprecated). In any of the first two cases you should use parameterized queries or prepared statements. You prepare the query and then fill in the variables ($verify_mod here). That way, the variables get escaped properly, again, to reduce the risk of SQL injection.
You are doing an insert, this sounds like it should be an update statement though (you can't do where in inserts either as it doesn't make sense to):
$confirm_query = "UPDATE users set confirm_email=1 WHERE verification='$verify_mod'"
Extending upon #CamilStaps answer, here's how you can parameterize your query using mysqli.
// For an insert: (No need to bind parameters for this one)
$confirm_query = $mysqli->prepare("INSERT INTO `users` (`confirm_email`) VALUES ('1')");
$confirm_query->execute();
// For an update:
$confirm_query = $mysqli->prepare("UPDATE `users` SET `confirm_email`='1' WHERE `verification`= ? ");
$confirm_query->bind_param('s', $verify_mod);
$confirm_query->execute();

how to check if a record exist in a database before inserting with php [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am creating a form that collects data and sends to a database using php, with a code snippet i got online.
$con=mysqli_connect("localhost","root","famakin","k");
if(mysqli_connect_errno())
{
echo"FailedtoconnecttoMySQL:".mysqli_connect_error();
}
$sql="INSERT INTO transactions(Username,Insured_Name,combined,Residential_Address,Telephone,Email,Make_Of_Car,Model,Engine_Number,Year_Of_Manufacture,Chassis_Number,Vehicle_Class,Colour,Registeration_Number,Product_Type,Premium,Policy_Number,Start_Date,Expiry_Date,Date_Begin,Type_Of_Insurance,Status, Transaction_id)VALUES('$_POST[Username]','$_POST[Insured_Name]','$_POST[combined]','$_POST[Residential_Address]','$_POST[Telephone]','$_POST[Email]','$_POST[Make_Of_Car]','$_POST[Model]','$_POST[Engine_Number]','$_POST[Year_Of_Manufacture]','$_POST[Chassis_Number]','$_POST[Vehicle_Class]','$_POST[Colour]','$_POST[Registeration_Number]','$_POST[Product_Type]','$_POST[Premium]','$_POST[Policy_Number]','$_POST[Date]','$_POST[Date_Expiry]','$_POST[Date_Begin]','$_POST[Type_Of_Insurance]','$_POST[Status]','$_POST[Transaction_id]')";
if(!mysqli_query($con,$sql))
{
die('Error:'.mysqli_error($con));
}
mysqli_close($con);
This works for inserting details into the database,but i want to check if for example the username in which i am inserting into the database exists,please how do i go about this with what i have already?
regards
There are two main approaches, essentially...
SELECT from the database before trying to INSERT. If the record is found by the SELECT, don't perform the INSERT and instead respond to the user accordingly.
Place a UNIQUE constraint on the column (or set of columns) which needs to be unique in the table. This would cause the INSERT to fail, and the code would have to catch and handle that failure and respond to the user accordingly.
The second option puts the responsibility squarely on the database itself, which is important if anything else if ever going to use that database and needs to maintain that same responsibility.
Also, and this is important, please note that your code is open to SQL injection attacks, which allows users to execute their own code on your server. You'll want to read up on that so you can protect your application.
Here, you can do it via mysqli_num_rows():
$username = mysqli_real_escape_string($con, $_POST['Username']);
$check_select = mysqli_query("SELECT * FROM `transactions` WHERE Username = '$username'");
$numrows=mysqli_num_rows($check_select);
if($numrows > 0){
// do something
}
else{
// do something else
}
Although there are other ways to do this, it is but one example.
You can avoid this by also setting your column(s) as UNIQUE.
By the way, your present code is open to SQL injection.
Use prepared statements, or PDO with prepared statements, they much safer.
Just do a SELECT query before the INSERT. If a record with that username exists then don't insert the record.
Well before you insert one you want to query for it's existence (please refer to Google on how to "Select data from Database PHP").
If that select count(*) from Transactions.... where Username =.. returns something other than 0 the username is already taken.
Note: I have bigger concerns about the fact you include POST-Parameters directly into your SQL-Query string and recommend you read something about "SQL Injection PHP".

Perform multiple SQL queries with PHP [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a web form that should store data into two different tables in the database. In my includes, I have a php file that performs the necessary queries. The web form should store two pieces of information: The xp value being submitted from the form into the users table, and the article id into the completed_quests table. Individually, the queries work exactly as they should. However, if I try to perform both queries together, only the first query is performed and the second one is ignored. How do I make it so that both queries run once the user hits the submit button?
(edit) I have updated the code. To clarify, there is other code in my php file that defines the variables used in these queries. These are simply the two queries I was trying to run and I needed to know how to run both queries as it seemed to be ignoring the second one (the update). It is now working, however I am running into an issue of the INSERT query creating duplicate entries.
(edit) I have updated the code again. I used an ON DUPLICATE KEY UPDATE to avoid duplicate entries in the table. I made sure that the user id was the primary key in the table and it is now functioning perfectly.
mysql_select_db("questroot_joomla", $con);
mysql_query("INSERT INTO arp2i_completed_quests (user_id, content_id) Values ($userId, $currentArticle)
ON DUPLICATE KEY UPDATE content_id=$currentArticle");
mysql_query( "UPDATE arp2i_users"
. " SET userxp= $userXp"
. " WHERE id = $userId");
mysql_close($con);
$sql = "INSERT INTO `arp2i_completed_quests` (`user_id`, `content_id`) Values ('$_POST[current_user]', '$_POST[current_article]')";
/* it's not in $sql ->> */ "UPDATE `arp2i_users`
SET `userxp`= '$_POST[xpValue]'
WHERE `id` = '$_POST[current_user]'";
Try this:
$sql = "INSERT INTO `arp2i_completed_quests` (`user_id`, `content_id`) Values
('$_POST[current_user]', '$_POST[current_article]');
UPDATE `arp2i_users`
SET `userxp`= '$_POST[xpValue]'
WHERE `id` = '$_POST[current_user]'";
A lot of people here are just answering as though you are using PHP and not a framework that already is designed to handle all this stuff for you and do it safely, including checking for injection etc. You use a framework to make it simpler and avoid doing unsafe things. The combination of JForm, JDatabaseQuery and other parts of the API will handle updating multiple tables just fine, you can see that all over the core. How you would do it depends on what you are doing, such as is it more like updating the profile table when you are saving user data or is it more like updating the assets table or creating a new tag when saving content. What you should do though is stop fighting the API and start using it to your advantage.
You can simply add many mysqli_* queries as you want :
mysqli_query($link, "INSERT INTO `arp2i_completed_quests` (`user_id`, `content_id`) Values ('".$_POST['current_user']."', '".$_POST['current_article']."')";
mysqli_query($link, "UPDATE `arp2i_users` SET `userxp`= '".$_POST['xpValue']."' WHERE `id` = '".$_POST['current_user']."'");

Wrong syntax for Mysql? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
$SQL="SELECT first_name FROM people WHERE fname = '$fname' INSERT INTO (first_name) VALUES (fname)";
Anything wrong with this? Trying to insert a value from a user defined variable into a mysql table
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in D:\wamp\www\Pxxxx\process.php on line 44
This is the error
$fname is a user defined variable
first_name is the column I'm trying to insert it into and it's in a table called people
You have the order inverted. It seems like you are looking for INSERT .. SELECT syntax (see MySQL documentation here: http://dev.mysql.com/doc/refman/5.6/en/insert-select.html)
INSERT INTO target_table (first_name)
SELECT fname
FROM people
WHERE fname = ?
It was unclear from your example what the name of the table you were trying to insert data into is, so I just listed it as target_table here.
Your SQL statement has to be reordered like this:
"INSERT INTO people (fname) SELECT '$fname' FROM dual;"
This will select the value of $fname from the pseudo table "dual" and insert the value into "people".
Maybe this is more suitable:
"INSERT INTO people (fname) VALUES ('$fname');"
This snippet show you a simple insert statement.
Note: Please have a look for SQL Injection at Wikipedia. The code you are writing is open for these kinds of attacks. If you are writing PHP code, have a look for Prepared Statements and mysqli to prevent these attacks.

Categories