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'm new in php.
Usually my update query is working, only in this block resulting a query fail, I get the officer value from $_SESSION[id] that determined before, and contact_id from a form before.
Please help...
<?php
$server="localhost";
$db_user="root";
$pass="h6194v";
$db="my_db";
$koneksi=mysql_connect($server,$db_user,$pass)
or die ("Connection Error!!");
$dateline=date("Ymd");
$query="UPDATE `contact` SET `date`=\'$dateline\', `officer`=\'$_SESSION[id]\' WHERE `contact_id`=\'$_POST[no]\'";
$result=mysql_query($query) or die ("Query fail");
?>
First of all
Please, don't use mysql_* functions for new code. They are no longer maintained and the community has begun the deprecation process. See the red box? Instead you should learn about prepared statements and use either PDO or MySQLi. If you can't decide, this article will help to choose. If you care to learn, here is good PDO tutorial.
Other than that and if you use mysql:
select a database after you made a connection with mysql_select_db($db,$koneksi) or use database name in front of the table name in UPDATE statement like UPDATE my_db.contact ...
fix your UPDATE statement as suggested by others
use correct format for date date('Y-m-d') or better yet ditch it altogether and use NOW() in your UPDATE statement
I formatted your query and try this.
$query="UPDATE `contact` SET `date`='{$dateline}', `officer`='{$_SESSION['id']}' WHERE `contact_id`='{$_POST['no']}'";
Note: Dont use MySQL functions and they are deprecated instead use PDO or MySQLi functions. You code is open to SQL injection try to add validation or use prepared statement to protect.
try this -
$query="UPDATE `contact` SET `date`='".$dateline."', `officer`='".$_SESSION['id']."' WHERE `contact_id`='".$_POST['no']."'";
But validate $_POST or $_GET before using in query or anywhere.
It would help to know what kind of error you're getting.
Don't put user input or session variables straight into a query, you should sanitize them first, perhaps with prepared statements.
When you get an error like this, try using var_dump and die to see what's going on. I.e. before your query var_dump($_SESSION['id']). (And now that I write that, I see you don't have quotes on your array index, which will cause problems.
You need to access your array with quotes: $_SESSION['id'], $_POST['no']
Change your update query like this
$query="UPDATE `contact` SET `date`='".$dateline."', `officer`='".$_SESSION[id]."'
WHERE `contact_id`=".$_POST[no];
If contact_id is string, do like this
$query="UPDATE `contact` SET `date`='".$dateline."', `officer`='".$_SESSION[id]."'
WHERE `contact_id`='".$_POST[no]."'";
Related
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 have an HTML form which is processed with PHP.
The input in the form is used as a condition in a SQL WHERE clause.
When there is no input the WHERE clause looks for an empty string and won't return anything. Instead I want to return ALL rows.
How can this be achieved? I thought about using LIKE instead but I want to match only exact input when there is indeed input.
To be clear:
I want to check if the variable that the input is stored in is empty. If so, I want to return all rows.
I wanted to know if it is possible to do such thing in SQL without having to change the statement around. Rather, by just changing the variable.
Note that there can be multiple fields of input.
EDIT:
Ignore the possibility of security risks. Is there a SQL command that can achieve this without changing the query itself, just the variables? For the record I am already checking if the variables are empty strings before the query. Also, where would the security risk be if I am checking if the variables are empty or not and I am doing proper validation otherwise?
Since you should not use user generated strings directly inside an SQL query anyways (See PHP: SQL Injection), I would handle that in the PHP script, not in SQL:
if(isset($user_input) && !empty($user_input)) {
// add WHERE clause
}
Edit: isset() is redundant if checked for !empty(). This will do, too:
if(!empty($user_input)) {
// add WHERE clause
}
Thanks AbraCadaver!
A common method to dynamically add filters on a query is:
$sql ='select * from table where (1=1) ';
if (array_key_exists($_POST,'email'))
{
$email=mysql_real_escape_string($_POST['email']);
$sql.=" and (email='$email')";
}
if (array_key_exists($_POST,'city'))
{
$city=mysql_real_escape_string($_POST['city']);
$sql.=" and (city='$city')";
}
//.....
mysql_query($sql);
This can allow you to use the same query, and effectively ignore the parameter if blank. I am not sure I would actually recommend it in lieu of constructing a (still parameterized) query, since it might not play nice with indexes all the time, but it is possible.
WHERE ([my_parameter] = '' OR the_field = [my_parameter])
even more generalized:
WHERE ([my_parameter] = [ignore value] OR the_field = [my_parameter])
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();
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".
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';
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 am new to PHP and mysql and i am trying to make API's for my iphone app.
So far i have been able to connect and retrive data from my sql database now m trying to make entries to it using API's and parameters.
Can anyone help me out here please.
Thanks alot!!
If by to make entries you mean adding data to the database.
You do this in the same way that you select data.
Instead of issuing a select statement like:
SELECT x,y,z FROM table1
You do:
INSERT INTO table1 (x,y,z) VALUES ('a', 1, 'test')
Or:
UPDATE table1 SET x = 'b' WHERE x = 'a'
How you pass parameters depends on the API you use.
It is best (safest) to use PDO to pass parameters.
How to get parameters out of a url
In order to get the parameters out of the url (e.g.: example.com/test.php?username=xyz&password=!##$%) do:
$username = mysql_real_escape_string($_GET['username']);
$password = mysql_real_escape_string($_GET['password']);
$query = "SELECT * FROM users WHERE username = '$username'
AND passhash = sha2(CONCAT(salt,'$password'),512)";
Note that it's vital to put single quotes around the injected variable names when using mysql_real_escape_string() or the escaping will be useless. Used like this the code is 100% secure from SQL-injection.
If you're using PDO, you can drop the mysql_real_escape_string() if not you need it to prevent SQL-injection.
Links
http://dev.mysql.com/doc/refman/5.5/en/update.html
http://dev.mysql.com/doc/refman/5.5/en/insert.html
http://php.net/manual/en/ref.pdo-mysql.php
https://stackoverflow.com/search?q=%5Bphp%5D+%5Bmysql%5D+pdo
http://php.net/manual/en/reserved.variables.get.php
http://php.net/manual/en/function.mysql-real-escape-string.php