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
Related
I am trying to perform an insert with the information of a query from another table, using php and mysql, I know that I have not done the protection part against sql injection correctly, I will solve that at the end, I tell you why then they only go to scold and do not contribute, would you be kind enough to tell me how to use the value obtained from the query, thank you.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
include("conection.php");
$credits = mysqli_real_escape_string($con, $_POST['credits']);
$namesec = mysqli_real_escape_string($con, $_POST['namesec']);
$change = mysqli_real_escape_string($con, $_POST['change']);
$stmt = $con->prepare("UPDATE students
SET student_credits = (student_credits + ?)
WHERE student_qr = ?");
$stmt->bind_param("is", $_POST['credits'], $_POST['namesec']);
$stmt->execute();
$insert_query = $con->prepare("INSERT INTO historical_credits (id_students, credits_paid)
SELECT id_students, ?
FROM students
WHERE student_qr = ?"
);
$insert_query->bind_param("is", $_POST['credits'], $_POST['namesec']);
$insert_query->execute();
mysqli_close($con);
?>
I want to use the value of id_student obtained from the query to insert it into a new table
You forgot to call fetch_assoc() to get the row that the query returns.
You also didn't quote $namesec in the SELECT query, so it's getting an error. This wouldn't be a problem if you used a parameter instead of substituting the variable.
But there's no need to do this in two queries. You can give a SELECT query as the source of the data in INSERT.
$insert_query = $con->prepare("
INSERT INTO historical_credits (id_students, credits_paid)
SELECT id_students, ?
FROM students
WHERE student_qr = ?");
$insert_query->bind_param("is", $_POST['credits'], $_POST['namesec']);
$insert_query->execute();
When I submit the form and use this script to insert the data in the db i get the error mentioned above...any ideas?
//Include connect file to make a connection to test_cars database
include("prototypeconnect.php");
$proCode = $_POST["code"];
$proDescr = $_POST["description"];
$proManu = $_POST["manufacturer"];
$proCPU = $_POST["cost_per_unit"];
$proWPU = $_POST["weight_per_unit"];
$proBarCode = $_POST["bar_code"];
$proIngredients = $_POST["ingredients_list"];
$proAllergens = $_POST["allergens_contains"];
$proMayAllergens = $_POST["allergens_may_contain"];
//Insert users data in database
$sql = "INSERT INTO prodb.simplex_list
code, description, manufacturer,
cost_per_unit, weight_per_unit, bar_code,
ingredients_list, allergens_contains,
allergens_may_contain)
VALUES
( '$proCode', '$proDescr' , '$proManu',
'$proCPU' , '$proWPU' , '$proBarCode',
'$proIngredients' , '$proAllergens',
'$proMayAllergens')";
//Run the insert query
if (!mysql_query($sql)) {
echo mysql_error();
}
?>
UPDATE: I removed id inserts as they are auto-increment and i learned from your answers that a null does not need to be coded and mysql looks after AI. Thanks guys!
Query need to be like:-
$sql = "INSERT INTO prodb.simplex_list
(code, description, manufacturer,
cost_per_unit, weight_per_unit,
bar_code, ingredients_list, allergens_contains,
allergens_may_contain)
VALUES ('$proCode', '$proDescr', '$proManu',
'$proCPU','$proWPU', '$proBarCode',
'$proIngredients', '$proAllergens',
'$proMayAllergens')";
Note:- please stop using mysql_*. Use mysqli_* or PDO. Also this will work only when id field must be auto incremented.
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username&&$password)
{
$connect = mysql_connect("CiniCraftData.db.55555555.hostedresource.com", "CiniCraftData", "*********") or die("Couldn't Connect");
mysql_select_db("CiniCraftData") or die ("Couldn't Find Database");
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('$username')";
$result = mysql_query($query) or die("Error occurred.");
}
else die("Please enter a username and password.");
?>
For this part of the code:
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('$username')";
The VALUES seem to not be working properly, I need whatever the string value of $username is to be inserted into my CiniUsers database. What do I need to do to make the code above work? I'm very new to php and sql syntax and the guides I'm finding online are all completely different from each other as if they keep updating php.
Try reviewing this part:
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('$username')";
The syntax is:
$query = "INSERT INTO table (column) VALUES ('$strvar')";
What is the column name you wanted to insert into?
If it is username.CINIDAT then try removing the qoutes.
Like this:
$query = "INSERT INTO CiniUsers (username.CINIDAT) VALUES ('$username')";
or maybe your column is named username so:
$query = "INSERT INTO CiniUsers (username) VALUES ('$username')";
UPDATE
The query from your comment, change it to this:
$query = "INSERT INTO CiniUsers (username.CINIDAT) VALUES ('$username')";
The format for the SQL statement is as so:
INSERT INTO nameOfTable (column1, column2, column3, etc) VALUES ('column1', 'column2', 'column3', 'etc')
You MUST make sure that you are using the field names exactly as they are stored in MySQL.
Your SQL could appear like so:
$query = "INSERT INTO CiniUsers (username) VALUES('$username')";
OR
$query = "INSERT INTO CiniUsers (username) VALUES('{$username}')";
Another thing that may help is that your die() statement is not very helpful. Yes, it is a bummer when your php program quits early, but it will save you a lot of time and frustration if you know why it quit. Although you may still be learning PHP and MySQL and may not know what the errors mean, they will start to make sense the more you see them and can tell you whether your query was bad, the connection failed or many more things. Change to something like this:
$connect = mysql_connect("CiniCraftData.db.55555555.hostedresource.com", "CiniCraftData", "*********") or die("Couldn't Connect: mysql_error()");
mysql_select_db("CiniCraftData") or die ("Couldn't Find Database: mysql_error()");
...
$result = mysql_query($query) or die("Some kind of error occurred...Query failed: mysql_error()");
You find that seeing the mysql_error() will help you solve problems like this much faster.
USE phpMyAdmin to test your query out, your query may be working perfectly. It is really the only way to know for sure. Use the suggested SQL and replace the PHP variable with some dummy data like "testUsername_1". If the query works, you will have manually added the username to the db, if not, the problem lies in SQL statement.
Here is some documentation on SQL INSERT INTO statements if you need more details:
http://www.w3schools.com/sql/sql_insert.asp
I think you should use mysqli or pdo. This liberary you are using is deprecated.
That said, what is username.CINIDAT? I think this is where your problem is. It should be something like this
$query = "INSERT INTO CiniUsers (username) VALUES('$username')";
I am assuming that CiniUsers is the table name and username is the column name.
The simplest way is to build the query by concatenating the statement with the value.
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('".$username."')";
Without validation, this is not a very good idea, or something like this is very easy.
So I've been trying to replicate a second order SQL Injection. Here's an example template of two php based sites that I've prepared. Let's just call it a voter registration form. A user can register and then you can check if you're a registered voter or not.
insert.php
<?php
$db_selected = mysql_select_db('canada',$conn);
if (!db_selected)
die("can't use mysql: ". mysql_error());
$sql_statement = "INSERT into canada (UserID,FirstName,LastName,Age,State,Town)
values ('".mysql_real_escape_string($_REQUEST["UserID"])."',
'".mysql_real_escape_string($_REQUEST["FirstName"])."',
'".mysql_real_escape_string($_REQUEST["LastName"])."',
".intval($_REQUEST["Age"]).",
'".mysql_real_escape_string($_REQUEST["State"])."',
'".mysql_real_escape_string($_REQUEST["Town"])."')";
echo "You ran the sql query=".$sql_statement."<br/>";
$qry = mysql_query($sql_statement,$conn) || die (mysql_error());
mysql_close($conn);
Echo "Data inserted successfully";
}
?>
select.php
<?php
$db_selected = mysql_select_db('canada', $conn);
if(!db_selected)
die('Can\'t use mysql:' . mysql_error());
$sql = "SELECT * FROM canada WHERE UserID='".addslashes($_POST["UserID"])."'";
echo "You ran the sql query=".$sql."<br/>";
$result = mysql_query($sql,$conn);
$row=mysql_fetch_row($result);
$sql1 = "SELECT * FROM canada WHERE FirstName = '".$row[1]."'";
echo "The web application ran the sql query internally=" .$sql1. "<br/>";
$result1 = mysql_query($sql1, $conn);
$row1 = mysql_fetch_row($result1);
mysql_close($conn);
echo "<br><b><center>Database Output</center></b><br><br>";
echo "<br>$row1[1] $row1[2] , you are a voter! <br>";
echo "<b>VoterID: $row[0]</b><br>First Name: $row[1]<br>Last Name: $row[2]
<br>Age: $row[3]<br>Town: $row[4]<br>State: $row[5]<br><hr><br>";
}
?>
So I purposely made this vulnerable to show how second order SQL Injection works, a user can type in a code into the first name section (where I am currently stuck, I've tried many different ways but it seems that I can't get it to do anything).
Then when a person wants to activate the code that he has inserted in the first name section, all he needs to do is just type in the userID and the code will be inserted.
For example:
I will type into the insert.php page as:
userid = 17
firstname = (I need to inject something here)
lastname = ..
age = ..
town = ..
state = ..
Then when I check for my details, and type in 17, the SQL script injected will be activated.
Can I get few examples on what sort of vulnerabilities I can show through this?
What is there to demonstrate?
Second order SQL injection is nothing more than SQL injection, but the unsafe code isn't the first line.
So, to demonstrate:
1) Create a SQL injection string that would do something unwanted when executed without escaping.
2) Store that string safely in your DB (with escaping).
3) Let some other piece of your code FETCH that string, and use it elsewhere without escaping.
EDIT: Added some examplecode:
A table:
CREATE TABLE tblUsers (
userId serial PRIMARY KEY,
firstName TEXT
)
Suppose you have some SAFE code like this, receiving firstname from a form:
$firstname = someEscapeFunction($_POST["firstname"]);
$SQL = "INSERT INTO tblUsers (firstname) VALUES ('{$firstname }');";
someConnection->execute($SQL);
So far, so good, assuming that someEscapeFunction() does a fine job. It isn't possible to inject SQL.
If I would send as a value for firstname the following line, you wouldn't mind:
bla'); DELETE FROM tblUsers; //
Now, suppose somebody on the same system wants to transport firstName from tblUsers to tblWhatever, and does that like this:
$userid = 42;
$SQL = "SELECT firstname FROM tblUsers WHERE (userId={$userid})";
$RS = con->fetchAll($SQL);
$firstName = $RS[0]["firstName"];
And then inserts it into tblWhatever without escaping:
$SQL = "INSERT INTO tblWhatever (firstName) VALUES ('{$firstName}');";
Now, if firstname contains some deletecommand it will still be executed.
Using a first name of:
' OR 1 OR '
This will produce a where clause in the second SQL of
WHERE FirstName = '' OR 1 OR ''
Therefore the result will be the first record in the table.
By adding a LIMIT clause, you can extract all rows from the table with:
' OR 1 ORDER BY UserID ASC LIMIT 0, 1 --
Obviously it will only extract 1 row at a time, so you would need to repeat that and increment the 0 in the LIMIT. This example uses a comment -- to terminate the remaining SQL which would otherwise cause the query to fail because it would add a single quote after your LIMIT.
The above is a simple example, a more complex attack would be to use a UNION SELECT which would give you access to the entire DB through the use of information_schema.
Also you are using addslashes() in one of your queries. That is not as secure as mysql_real_escape_string() and in turn: escaping quotes with either is not as secure as using prepared statements or parameterised queries for example in PDO or MySQLi.
i wrote the following code,but its not updating the database,,its a part of a script and it cease to work..cant find a way around it .. need suggestions
<?php
$link = mysql_connect('xxxxxxxx');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xxx", $link);
$usernames='aneeshxx';
echo $usernames;
$update = "INSERT sanjana SET $name ='$usernames'";
mysql_query($update, $link);
$update1 = "INSERT INTO sanjana (name)VALUES ($usernames)";
mysql_query($update1, $link);
?>
$update = "INSERT sanjana SET $name ='$usernames'";
this probably is meant as an UPDATE statement, so for an update it should be
$update = "UPDATE sanjana set name = '$usernames'";
I put name and not $name due to your second query and not seeing $name being defined anywhere. Be aware that this will change the value in the column name of every row in the sanjana table to the value of $usernames, normally a statement such as this gets limited by conditions, e.g. WHERE userid = 33
$update1 = "INSERT INTO sanjana (name) VALUES ($usernames)";
for an INSERT statement it needs to have the values quoted so
$update1 = "INSERT INTO sanjana (name) VALUES ('$usernames')";
Be wary that this way of putting variables directly into your query string makes you vulnerable to SQL injection, to combat this please use the PDO or mysqli extensions, they both protect you from injection by providing you with prepared statements ; plain old mysql_* is not recommended for use anymore.
using pdo you'd use prepared statements like this
<?php
// we got $usernames from wherever you define it
$pdo = new PDO('mysql:dbname=mydb;host=localhost','username','password');
// to insert
$statement = $pdo->prepare('INSERT INTO `sanjana` (name) VALUES (:name)');
// the following replaces :name with $usernames in a safe manner, defeating sql injection
$statement->bindParam(':name',$usernames);
$statement->execute(); // it is done
// to update
$statement = $pdo->prepare('UPDATE `sanjan` SET `name` = :name');
$statement->bindParam(':name',$usernames);
$statement->execute(); // it is done
so as you can see protecting your code from malicious input is not hard and it even makes your SQL statements a lot easier to read. Did you notice that you didn't even need to quote your values in the SQL statement anymore? Prepared statements take care of that for you! One less way to have an error in your code.
Please do read up on it, it will save you headaches. PDO even has the advantage that it's database independent, making it easier to use another database with existing code.
The right update sql clause is like so:
UPDATE table
SET column = expression;
OR
UPDATE table
SET column = expression
WHERE predicates;
SQL: UPDATE Statement
Your query should be like this:
$update = "UPDATE sanjana SET $name ='$usernames'";
mysql_query($update, $link);
Of course you need to specify a row to update (id), other wise, the whole table will set column $name to $usernames.
UPDATE:
Because you are inserting a data in empty table, you should first execute $update1 query then execute $update query. UPDATE clause will make no change/insert on empty table.
Problem 1: use the correct "insert into" (create new record) vs. "update" (modify existing record)
Problem 2: It's good practice to create your SQL string before you call mysql_query(), so you can print it out for debugging
Problem 3: It's also good practice to detect errors
EXAMPLE:
<?php
$link = mysql_connect('xxxxxxxx')
or die('Could not connect: ' . mysql_error());
mysql_select_db("xxx", $link);
$usernames='aneeshxx';
$sql = "INSERT INTO sanjana (name) VALUES ('" . $usernames + ")";
echo "sql: " . $sql . "...<br/>\n";
mysql_query($sql, $link)
or die(mysql_error());
You have INSERT keyword for your update SQL, this should be changed to UPDATE:
$update = "UPDATE sanjana SET $name ='$usernames'";