After being advised that i MUST validate my form so that no-one could hack my database i then made some changes which were adding the mysql_real_string()
$query="INSERT INTO allymccoist (id, firstname, lastname, email, date)
VALUES (NULL, '".$firstname."', '".$lastname."', '".$email."', '".mysql_real_escape_string($new_date)."')";
$firstname = mysql_real_escape_string($_POST['firstname']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$email = mysql_real_escape_string($_POST['email']);
$datepicker = mysql_real_escape_string($_POST['date']);
since doing this, nothing is being sent to firstname lastname or email although the date seems to be sending ok though
is thereanything that may be causing this that you can see from my code?
If you're sure that those data actually are set (var_dump your $_POST array to check that),then make sure you have a connection active before using mysql_real_escape_string(), as it would return FALSE otherwise:
A MySQL connection is required before using mysql_real_escape_string()
otherwise an error of level E_WARNING is generated, and FALSE is
returned. If link_identifier isn't defined, the last MySQL connection
is used.
So you can well be entering FALSE in every value.
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')or die(mysql_error());
mysql_select_db('database_name', $link) or die('cannot select database '.mysql_error());
$firstname = mysql_real_escape_string($_POST['firstname']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$email = mysql_real_escape_string($_POST['email']);
$datepicker = mysql_real_escape_string($_POST['date']);
You'd be better off altogether by using prepared statements, so you won't have to worry about SQL injections.
Also, I'd advice you against using NULL in your insert query for the field ID. If you're table is strcutred as I can guess, and ID is a primary key with AutoIncrement, you don't need to enter it in your query, as it would be automatically filled by the engine.
For wheter it is better to use prepared statements or mysql_real_escape_string(), check this resource mysql_real_escape_string vs prepared statements
The issue of missing data is likely as Damien suggests. Establish a connection, then use mysql_real_escape_string(). The connection is required in part so that mysql_real_escape_string() can take into account the current character set of the connection.
Also, mysql_real_escape_string() is perfectly safe when used in combination with the sprintf() function (full details on sprintf). Most important with sprintf() is setting the correct type specifier so that values get cast properly. Generally, for integers you will use %d. For floats use %f. And for string and date values use %s.
So for your program the code should look something like (note: as Damien suggests, leave id out of the query):
/* Read form data. */
$firstName = $_POST['firstname'];
$lastName = $_POST['lastname'];
$email = $_POST['email'];
$date = $_POST['date']);
/* Your form validation code here. */
/* Your db connection code here. */
/* Setup and run your query. */
$query = sprintf("INSERT INTO allymccoist (firstname, lastname, email, date)
VALUES ('%s', '%s', '%s', '%s')",
mysql_real_escape_string($firstName),
mysql_real_escape_string($lastName),
mysql_real_escape_string($email),
mysql_real_escape_string($date));
$result = mysql_query($query);
/* Check for errors with query execution. */
if (!$result) echo("Query Error! Process aborted.");
Related
I have created a form that submits to the mysql database. Now what I am trying to do is get it to update. The bit I'm having trouble with is the update query below, I just can not figure out where I am going wrong.
<?php
/*
Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password)
*/
include 'db.php';
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$title = mysqli_real_escape_string($link, $_POST['title']);
$price = mysqli_real_escape_string($link, $_POST['price']);
$sqm = mysqli_real_escape_string($link, $_POST['sqm']);
$sqm_land = mysqli_real_escape_string($link, $_POST['sqm_land']);
$type = mysqli_real_escape_string($link, $_POST['type']);
$area = mysqli_real_escape_string($link, $_POST['area']);
$location = mysqli_real_escape_string($link, $_POST['location']);
$bedroom = mysqli_real_escape_string($link, $_POST['bedroom']);
$terrace = mysqli_real_escape_string($link, $_POST['terrace']);
$orientation = mysqli_real_escape_string($link, $_POST['orientation']);
$water = mysqli_real_escape_string($link, $_POST['water']);
$seaview = mysqli_real_escape_string($link, $_POST['seaview']);
$pool = mysqli_real_escape_string($link, $_POST['pool']);
$ownerinfo = mysqli_real_escape_string($link, $_POST['ownerinfo']);
$gaddress = mysqli_real_escape_string($link, $_POST['gaddress']);
$description = mysqli_real_escape_string($link, $_POST['description']);
// attempt insert query execution
$sql = "update INTO property (title, price, sqm, sqm_land, type, area, location, bedroom, terrace, orientation, water, seaview, pool, ownerinfo, gaddress, description) VALUES
('$title', '$price', '$sqm', '$sqm_land', '$type', '$area', '$location', '$bedroom', '$terrace', '$orientation', '$water', '$seaview', '$pool', '$ownerinfo', '$gaddress', '$description' )";
if(mysqli_query($link, $sql)){
echo "Records updated successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
You're using the wrong syntax for UPDATE.
Read the manual:
http://dev.mysql.com/doc/en/update.html
What you're using is INSERT syntax. http://dev.mysql.com/doc/en/insert.html
Example from the manual:
UPDATE t1 SET col1 = col1 + 1, col2 = col1;
and use a WHERE clause, otherwise you will be updating your entire db.
Example from the manual:
UPDATE items,month SET items.price=month.price
WHERE items.id=month.id;
So in your case and for example (fill in the rest):
UPDATE property SET title = '$title', price = '$price' ... WHERE column = ?
column being the column name you want to target and the ? being the row.
Your mysqli_error($link) would have thrown you something about it.
Sidenote: "Teach a person how to fish, rather than throwing them a fish".
However, if the goal here is to INSERT, then you need to use INSERT INTO table and not UPDATE INTO table.
Also make sure your form uses a POST method and that all POST arrays contain values.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Footnotes:
The MySQL API used to connect with in db.php is unknown. Make sure you are using the same API you are using to query with, being mysqli_. Different APIs do not intermix.
Your syntax is incorrect, it should be formatted like this:
$sql = "UPDATE property SET title='$title'";
You'll have to add all the name/value pairs separated by commas since I only included 'title.'
trying to submit data from a form but does not seem to be working. Can't spot any problems?
//Include connect file to make a connection to test_cars database
include("prototypeconnect.php");
$proId = $_POST["id"];
$proCode = $_POST["code"];
$proDescr = $_POST["descr"];
$proManu = $_POST["manu"];
$proCPU = $_POST["cpu"];
$proWPU = $_POST["wpu"];
$proBarCode = $_POST["barcode"];
$proIngredients = $_POST["ingredients"];
$proAllergens = $_POST["allergenscon"];
$proMayAllergens = $_POST["allergensmay"];
//Insert users data in database
$sql = "INSERT INTO prototype.Simplex_List (id, code, descr, manu, cpu, wpu, barcode, ingredients, allergenscon, allergensmay)
VALUES ('$proId' , '$proCode', '$proDescr' , '$proManu' , '$proCPU' , '$proWPU' , '$proBarCode' , '$proIngredients' , '$proAllergens' , '$proMayAllergens')";
//Run the insert query
mysql_query($sql)
First and foremost, please do not use mysql_*** functions and please use prepared statements with
PDO http://php.net/manual/en/pdo.prepare.php
or mysqli http://php.net/manual/en/mysqli.quickstart.prepared-statements.php instead. Prepared statements help protect you against sql injection attempts by disconnecting the user submitted data from the query to the database.
You may want to try using mysql_real_escape_string http://php.net/manual/en/function.mysql-real-escape-string.php to ensure no stray " or ' is breaking your query.
$proId = mysql_real_escape_string($_POST["id"]);
$proCode = mysql_real_escape_string($_POST["code"]);
$proDescr = mysql_real_escape_string($_POST["descr"]);
$proManu = mysql_real_escape_string($_POST["manu"]);
$proCPU = mysql_real_escape_string($_POST["cpu"]);
$proWPU = mysql_real_escape_string($_POST["wpu"]);
$proBarCode = mysql_real_escape_string($_POST["barcode"]);
$proIngredients = mysql_real_escape_string($_POST["ingredients"]);
$proAllergens = mysql_real_escape_string($_POST["allergenscon"]);
$proMayAllergens = mysql_real_escape_string($_POST["allergensmay"]);
Additionally ensure your form is being submitted by calling var_dump($_POST) to validate the data
You can also see if the query is erroring by using mysql_error http://php.net/manual/en/function.mysql-error.php
if (!mysql_query($sql)) {
echo mysql_error();
}
advices about PDO, prepared statements were done.
1) Do you have a database and connection to it?
Look at your prototypeconnect.php and find database name there. check that its name and password is similar that u have.
2) Do you have a table named prototype.Simplex_List in your database?
a) IF YOU HAVE:
check if your mysql version >= 5.1.6
http://dev.mysql.com/doc/refman/5.1/en/identifiers.html
b) IF YOU HAVE BUT ITS NAME is Simplex_List:
b-1) if your database name IS NOT prototype:
replace your
$sql = "INSERT INTO prototype.Simplex_List
with
$sql = "INSERT INTO Simplex_List
b-2) if your database name IS prototype:
you should escape your $_POST data with mysql_real_escape_string as #fyrye said.
c) IF YOU HAVE NOT:
you should create it
3) Check your table structure
does it have all theese fields id, code, descr, manu, cpu, wpu, barcode, ingredients, allergenscon, allergensmay?
if you have there PRIMARY or UNIQUE keys you should be sure you are not inserting duplicate data on them
but anyway replace your
$sql = "INSERT INTO
with
$sql = "INSERT IGNORE INTO
PS: its not possible to help you without any error messages from your side
I have using PHP for inserting integer value in Database.
Iam using like this
$postcode = $_POST['postcode'];
$mysql_user_resultset = mysqli_query($con, "INSERT into user (postcode) VALUES ($postcode)");
I have several field in DB. like name, username, etc. all are defined as varchar, but postcode only defined as int. If not enter the value for postcode, it doesn't insert into database
You could simply cast your variable into int:
$postcode = (int) $_POST['postcode'];
$mysql_user_resultset = mysqli_query($con, "INSERT into user (postcode) VALUES ($postcode)");
Note that you're not using any precautions regarding SQL injections, I would suggest you to bind your parameters before query them, using PDO class.
Convert $_POST['postcode'] to int, using
$postcode = (int)$_POST['postcode'];
Use PDO or sprintf for formatting mysql query:
sprintf example:
$mysql_user_resultset = mysqli_query($con, sprintf(
"INSERT into user (postcode) VALUES (%d)",
$_POST['postcode']));
PDO example:
$st = $db->prepare("INSERT into vendors user (postcode) VALUES (:postcode)");
$st->bindParam(':postcode', $_POST['postcode'], PDO::PARAM_INT);
$mysql_user_resultset = $st->execute();
I have just implemented mysql_real_escape_string() and now my script won't write to the DB. Everything worked fine before adding mysql_real_escape_string():
Any ideas??
$name = mysql_real_escape_string($_POST['name']);
$description = mysql_real_escape_string($_POST['description']);
$custid = mysql_real_escape_string($_SESSION['customerid']);
mysql_send("INSERT INTO list
SET id = '',
name = '$name',
description = '$description',
custid = '$custid' ");
what is that mysql_send function?
what if to change it to mysql_query();
It should be easy to figure out what's going on.
Fist, instead of sending the query you're constructing to the database, echo it out (or log it), and see what you're actually sending to the database.
If that doesn't make it obvious, see what mysql_error() has to say.
mysql_real_escape_string should have a database connection passed as the second argument since it asks the database what characters need to be escaped.
$connection = mysql_connect(HOST, USERNAME, PASSWORD);
$cleanstring = mysql_real_escape_string("my string", $connection);
A typical failure on understanding how to use certain functions...
You're just using mysql_real_escape_string on raw input data. Have you ever heard of santizing / validating input? mysql_real_escape_string does not make sense on numbers. If you've validated a variable to be a number, you don't need to escape it.
mysql_send is an alias for mysql_query right?
Use debug code, add echo mysql_error(); after mysql_send(...).
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$name = mysql_real_escape_string($_POST['name']);
$description = mysql_real_escape_string($_POST['description']);
$custid = mysql_real_escape_string($_SESSION['customerid']);
//If you doing Update use this code
mysql_query("UPDATE list SET id = '', name = '$name', description = '$description' WHERE custid = '$custid' ") or die(mysql_error());
//OR if you doing Insert use this code.
mysql_query("INSERT INTO list(name, description, custid) VALUES('$name', '$description', '$custid')") or die(mysql_error());
//If custid is Integer type user $custid instead of '$custid'.
If you are updating the records in the list table based on the custid use the UPDATE command OR if you are insertinf the records into list table use INSERT command.
The simple query below is not working. Any idea why? When I echo the three variables, the correct values are returned, so I know I have variables.
Thanks in advance,
John
$comment = $_POST['comment'];
$uid = $_POST['uid'];
$subid = $_POST['submissionid'];
echo $comment;
echo $uid;
echo $subid;
mysql_connect("mysqlv12", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$query = sprintf("INSERT INTO comment VALUES (NULL, '%s', '%s', '%s', NULL, NULL)", $uid, $subid, $comment);
mysql_query($query);
The query looks fine on the surface. What are the values you're inserting? Do any of them have a single quote in them? I'd guess the comment field is the likeliest culprit for that. Your code is utterly vulnerable to SQL injection as it stands now. You should replace all the variable assignments as follows, for a bare minimum of security:
$comment = $_POST['comment'];
becomes
$comment = mysql_real_escape_string($_POST['comment']);
This will also incidentally take care of any single quotes that may be causing your query to fail. As well, you do need to check if the query succeeded:
mysql_query($query) or die (mysql_error());
which would immediately tell you if there were any problems (sql syntax error, database server died, connection failed, etc...)