I am teaching myself php and MySQL, and right now I have a problem with MySQL.
I want to compare the phone number that the user put in with the phone number in MYSQL, and if it is in MYSQL to not register it again.
My code:
<?php
require_once 'connection/connection.php';
// Variables from HTML to php
$worker_Name = $_POST['workerNameFromHtml']; // worker Name
$worker_City = $_POST['workerCityFromHtml']; // workerCity
$worker_career = $_POST['workerCareerFromHtml']; // worker career
$worker_PhoneNumber = $_POST['workerPhonNumberFromHtml']; // worker Phone Number
$worker_SecondPhoneNumber = $_POST['workerSecondPhoneNumberFromHtml']; // worker Second Phone Number
$submt=$_POST['submitFromHtml'];
if($submt){
$qry = ( "SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '$worker_PhoneNumber'") or die(mysql_error());
$result = $connect->query($qry);
$num = $result->num_rows;
if ($num == 1) {
$here = "INSERT INTO workersTable VALUES('','$worker_Name','$worker_City','$worker_career','$worker_PhoneNumber','$worker_SecondPhoneNumber')";
$query = $connect->query($here);
print "Successfully added!";
}
else {print "This number has already been entered Thank you for your cooperation!";}}
$connect->close();
So far I have not found a solution to this problem.
your biggest problem here is that you are trying to include variables inside of a string.
"SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '$worker_PhoneNumber'"
If you want to do it this way, you need to concatenate your variables with your string.
"SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '".$worker_PhoneNumber."'"
Keep in mind if you do this you will want to sanitize your variables first to prevent SQL injections. Also, when you INSERT variables, you will actually want to use a prepared statement like this:
"INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)"
where the 1st set of values are the names of your columns in the database and the second set are your PHP variables you are putting into it.
Related
I've tried to follow several answers on this question but can't seem to get it to work for my specific problem.
I want to insert data but only if the flight_number doesn't exists already. How can I do that?
$sql = mysqli_query($con,
"INSERT INTO space (`flight_number`, `mission_name`, `core_serial`, `payload_id`)
VALUES ('".$flight_number."', '".$mission_name."', '".$core_serial."', '".$payload_id."')"
);
Rob since you saying flight_number is a unique then you can use INSERT IGNORE
<?php
$sql = "INSERT IGNORE INTO space (`flight_number`, `mission_name`, `core_serial`, `payload_id`) VALUES (?,?,?,?)";
$stmt = $con->prepare($sql);
$stmt->bind_param('isss',$flight_number,$mission_name,$core_serial,$payload_id);
if($stmt->execute()){
echo 'data inserted';
// INSERT YOUR DATA
}else{
echo $con->error;
}
?>
OR you could select any row from your database that equal to the provided flight number then if u getting results don't insert.
$sql = "SELECT mission_name WHERE flight_number = ? ";
$stmt = $con->prepare($sql);
$stmt->bind_param('i',$flight_number);
if(mysqli_num_rows($stmt) === 0){
// INSERT YOUR DATA
}
A unique index on flight number should do the trick.
CREATE UNIQUE INDEX flight_number_index
ON space (flight_number);
If you want to replace the existing row with the new one use the following:
$sql = mysqli_query($con,
"REPLACE INTO space (`flight_number`, `mission_name`, `core_serial`, `payload_id`)
VALUES ('".$flight_number."', '".$mission_name."', '".$core_serial."', '".$payload_id."')"
);
Make note that I just copied your code and changed INSERT to REPLACE to make it easy to understand. PLEASE PLEASE PLEASE do not use this code in production because it is vulnerable to injection.
If you don't want to replace the existing row, run an insert and check for errors. If there is an error related to the index, the row already exists.
Disclaimer: I haven't tested any of this code, so there may be typos.
I've been trying to insert a variable that has a comma in it to a SQL database for 30 minutes or so. I've echoed the variable, and the comma is there, but when it inserts, there's no comma!
Example (some code like mine):
$variable1 = "test";
$variable2 = "$variable1,";
$sql1 = "INSERT INTO table (`column`) VALUES ('$variable2')";
$query1 = mysqli_query($con,$sql1); //I dont think I need to put a con variable up there for an example code
And when I do:
echo $variable2;
The result is test, with the comma, but the data in the column is just test WITH NO COMMA.
Help please.
Thanks.
Edit:
Your Common Sense fixed it, apparently I needed brackets around '$variable2' so it's like:
$sql1 = "INSERT INTO table (`column`) VALUES (('$variable2'))";
Thanks Your Common Sense and everyone else who tried!
Well, the answer is simple.
It's your own code does remove this comma, either before insert or after fetch.
If you care to write a reproduceable test case, you will see that noone is taking your comma.
Test case means code that involves the behavior in question and nothing else. Not a single line of code beside insert and fetch:
$variable1 = "test";
$variable2 = "$variable1,";
$sql1 = "INSERT INTO users (username) VALUES ('$variable2')";
mysqli_query($db,$sql1);
$sql2 = "SELECT username FROM users WHERE username ='$variable2'";
$res = mysqli_query($db,$sql2);
$row = mysqli_fetch_row($res);
var_dump($variable1, $variable2, $sql1, $sql2, $row[0]);
run it, see it all with comma in place, and then search your own code for the comma trimming code
or may be you have just test without comma in your table, ans select this one all the time, instead of one with comma.
or whatever silly error of the like
Try it like this:
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
$stmt = $mysqli->prepare("INSERT INTO table ('column') VALUES (?)");
$stmt->bind_param($variable2);
/* execute prepared statement */
$stmt->execute();
This is more safe and will not trigger such strangeties. (Is that a word?)
What happens here is, that the query is send to the sql database and this returns a statement. The statement has some holes, these are the ?, in it.
When using bind_param you fill the holes and then you can execute.
This has a couple of advantages:
It is safe
You can reuse your statement
It is easier than string interpolation stuff
Try "INSERT INTO table ('column') VALUES ('" . $variable2 . "');"
I need to insert encrypted values in mysql table, but when I use traditional pdo method to insert its inserting the data in wrong format. ex: I insert aes_encrypt(value, key) in place of inserting encrypted value its inserting this as string.
Following is the code :
$update = "insert into `$table` $cols values ".$values;
$dbh = $this->pdo->prepare($update);
$dbh->execute($colVals);
$arr = array("col"=>"aes_encrypt ($val, $DBKey)");
I know i am doing it wrong, but not able to find correct way.
You are almost there, here is a simplified version:
<?php
$sql = "insert into `users` (`username`,`password`) values (?, aes_encrypt(?, ?))";
$stmt = $this->pdo->prepare($sql);
// Do not use associative array
// Just set values in the order of the question marks in $sql
// $fill_array[0] = $_POST['username'] gets assigned to first ? mark
// $fill_array[1] = $_POST['password'] gets assigned to second ? mark
// $fill_array[2] = $DBKey gets assigned to third ? mark
$fill_array = array($_POST['username'], $_POST['password'], $DBKey); // Three values for 3 question marks
// Put your array of values into the execute
// MySQL will do all the escaping for you
// Your SQL will be compiled by MySQL itself (not PHP) and render something like this:
// insert into `users` (`username`,`password`) values ('a_username', aes_encrypt('my_password', 'SupersecretDBKey45368857'))
// If any single quotes, backslashes, double-dashes, etc are encountered then they get handled automatically
$stmt->execute($fill_array); // Returns boolean TRUE/FALSE
// Errors?
echo $stmt->errorCode().'<br><br>'; // Five zeros are good like this 00000 but HY001 is a common error
// How many inserted?
echo $stmt->rowCount();
?>
you can try it like this.
$sql = "INSERT INTO $table (col) VALUES (:col1)";
$q = $conn->prepare($sql);
$q->execute(array(':cols' => AES_ENCRYPT($val, $DBKey)));
I have this code:
public function updateOrder($num, $ufood, $uquan) {
$response = array();
mysql_query("SET NAMES 'utf8'");
foreach ($ufood as $index => $f) {
$result = mysql_query("SELECT food, quantity, uquantity FROM table1 WHERE food ='".$f."'") or die(mysql_error());
$no_of_rows = mysql_num_rows($result);
$response['number rows'] = $no_of_rows;
if ($no_of_rows>0) {
while ($row = mysqli_fetch_array($result)); {
if (!$row['uquantity']) {
$w = "INSERT INTO table1(uquantity) VALUES ('$uquan[$index]')";
mysql_query($w);
$e = (int)$row['quantity'];
$q = (int)$uquan[$index];
$sum = $e+$q;
$s = (string)$sum;
$d = "UPDATE table1 SET quantity = '$s' WHERE food = ".$row['$food']." ";
mysql_query($d);
} else if($row['uquantity']) {
$c = (int)$row['uquantity'];
$q = (int)$uquan[$index];
$sumq = $c+$q;
$sq = (string)$sumq;
$d = "UPDATE table1 SET uquantity = '$sq' WHERE food = ".$row['$food']." ";
}
}
} else {
$string ="INSERT INTO table1(food,uquantity) VALUES ('".$f."','".$uquan[$index]."')";
$z = mysql_query($string);
}
}
}
Well i can not make this work, and i am trying all kinds of things put still it doesn't work.
So i have some questions:
Is this structure of foreach and while valid?
Though the $result query returns some rows from the database, when i try to use $row['quantity'], as a value, i get null.
In this code i receive some data from an android app, and i try to "see", if there are already entries for the type food of my db_table(table1). If there are entries i want the db to sum the quantity entry of the android sent, data with the one that are inside my db, and update the field. This is the basically it. But as i said when i try to use the data that comes from the database, i get null values.
Please if someone could give me some hint, cause I'm really stuck..
There are many problems with your code. I'm marking this answer as Community Wiki, and I invite others to edit and add things as they find them.
You may also consider posting to https://codereview.stackexchange.com/ instead, when you have so many mistakes, until you have a more specific question.
Bad variable interpolation
This line won't do what you want it to:
$w = "INSERT INTO table1(uquantity) VALUES ('$uquan[$index]')";
This is not quite valid PHP syntax. You can either concatenate expressions:
$w = "INSERT INTO table1(uquantity) VALUES ('".$uquan[$index]."')";
Or you can embed expressions in curly braces:
$w = "INSERT INTO table1(uquantity) VALUES ('{$uquan[$index]}')";
Or you can use a query parameter placeholder:
$w = "INSERT INTO table1(uquantity) VALUES (?)";
$stmt = mysqli_prepare($w) or die(mysqli_error());
$uqi = $uquan[$index];
mysqli_stmt_bind_param($stmt, "i", $uqi);
mysqli_stmt_execute($stmt);
Mixing MySQL APIs
You can't mix mysql_query() with mysqli_fetch_array(). PHP has more than one API for MySQL, and you can't mix them. You should standardize on using the mysqli API, because the older mysql API is now deprecated.
Semicolon defeats while loop
The semicolon after the while statement makes the loop a no-op, and when it terminates, the $row contains nothing.
while ($row = mysqli_fetch_array($result)); {
Should be:
while ($row = mysqli_fetch_array($result)) {
Using variables inappropriately
Referencing a $row key with a single-quoted variable is probably not what you mean, in multiple ways:
$d = "UPDATE table1 SET quantity = '$s' WHERE food = ".$row['$food']." ";
The column name in the select-list of your earlier SELECT query is 'food', not '$food'.
Also, even if you meant to use a variable name $food as the key, putting it in single quotes would not use the value of the variable, it would be the literal string '$food'.
Failure to quote string literal?
Furthermore, you use a quoted literal for comparing to the food column in your SELECT query, which makes me think it might be a string.
So the UPDATE should be something like:
$d = "UPDATE table1 SET quantity = '$s' WHERE food = '".$row['food']."' ";
Or:
$d = "UPDATE table1 SET quantity = '$s' WHERE food = " . intval($row['food']);
Or preferably use parameters and a prepared query, then you don't need to worry about quotes or types:
$d = "UPDATE table1 SET quantity = ? WHERE food = ?";
. . .
Failure to check for errors
Every query might fail, either because you have a syntax error (e.g. a string without quoting), or because the table doesn't have a column by the name you reference, or privileges issues, etc.
Always check the return status of the query function when you run a SQL query. The function returns false if there's an error, and if that happens you must check the error message.
mysqli_query($mysqli, $d) or trigger_error(mysqli_error($mysqli), E_USER_ERROR);
Failure to execute the UPDATE
Your second update assigns a SQL query string to the variable $d, but then does not execute that update query at all!
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.