Easier way for button information submits (secure) - php

When using a button to submit an information which is prepared but you want to add a something like title to the button, so the "value" with form like :
<form action="" method="POST">
<input type="submit" name="Man" value="Man">
</form>
With the php code like this :
if (isset($_POST['Man'])) {
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "
UPDATE users
SET gender = ?
WHERE username = ?
";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('ss', $_POST['Man'], $_SESSION['username']);
$ok = $stmt->execute();
if ($ok == TRUE) {
echo "<font color='#00CC00'>Your gender has been updated.</font><p>";
} else {
echo "Error: " .$stmt->error;
}
}
This is the code, which so many people using (normal easy code with prepared statements) but there is a one mistake... If somebody change the value of Man to eg. lol , the gender in database will be set to "lol" because the value is "lol"...
I noticed this problem in so many websites and codes here, and so the way to fix this, is to pre-define the $_POST... Check answer

You need to whitelist the allowed values in an array
if (isset($_POST['Man'])) {
$allowed_values=array("Man","Women");
if(!in_array($_POST['Man'],$allowed_values)){
echo"error message";
die();
}
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "
UPDATE users
SET gender = ?
WHERE username = ?
";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('ss', $_POST['Man'], $_SESSION['username']);
$ok = $stmt->execute();
if ($ok == TRUE) {
echo "<font color='#00CC00'>Your gender has been updated.</font><p>";
} else {
echo "Error: " .$stmt->error;
}
}

One simple thing to do is to pre-define the $_POST so the value will never be changed...
with simple one line code :
$_POST['Man'] = Man;
By adding this code to your code, the value cannot be changed with html so
the result wll be still the "Man" and you are good to go.

Related

duplicate row formed in table when using PHP to store a form

I am making a site to display the family relations of an individual...I made use of PHP to store data from a form. I use access code to categorize different relations if an individual. i.e..101-the relations of person X.
I need a bit of help as to why to an entry is being entered twice into the database.(new to PHP and first time asking for help here)
Thank you in Advance!
forms code(IN ct.php):
<form id="frm1" action="ap.php" method="POST">
access code: <input type="text" name="code_entered" value=""><br><br>
position in family: <select name="fpos_entered">
<option>Grandfather</option>
<option>Grandmother</option>
<option>Father</option>
<option>Mother</option>
<option>Brother</option>
<option>Sister</option>
<option>Uncle</option>
<option>Aunt</option>
<option>Nephew</option>
<option>Niece</option>
<option selected>Yourself</option>
</select><br><br>
name: <input type="text" name="name_entered" value=""><br><br>
DOB:<input type="date" name="dob_entered" value=""><br><br>
<input type="submit" value="Submit">
</form>
i use the following PHP code to store the data from the form:
<?php
include 'ct.php';
$temp="temp";
$conn= mysqli_connect ('localhost','root','','familytree');
if (!$conn)
{
die ('Could not connect:' . mysql_error());
}
if (isset($_POST['code_entered']))
{
$acc= $_POST['code_entered'];
}if (isset($_POST['fpos_entered']))
{
$fpos= $_POST['fpos_entered'];
}if (isset($_POST['name_entered']))
{
$n= $_POST['name_entered'];
}if (isset($_POST['dob_entered']))
{
$db= $_POST['dob_entered'];
}
$sql ="insert into temp values ('$acc', '$n','$fpos','$db')";
$result = mysqli_query($conn,$sql);
if ($conn->query($sql) === TRUE) {
echo "<p>New record created successfully</p>.";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
which results in me having :
pic of the database after 2 enteries
<?php
declare(strict_types=1);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "familytree";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
try {
$stmt = $conn->prepare("
INSERT INTO `temp` (code, fpos, name, dob)
VALUES (:code, :fpos, :name, :dob)");
$stmt->bindParam(':code', $_POST['code_entered'] ?? null);
$stmt->bindParam(':fpos', $_POST['fpos_entered'] ?? null);
$stmt->bindParam(':name', $_POST['name_entered'] ?? null);
$stmt->bindParam(':dob', $_POST['dob_entered'] ?? null);
$stmt->execute();
echo "<p>New record created successfully</p>.";
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
I recommend you to use PDO instead of mysqli. Also, bind the attributes coming from outside :)
Official docu: https://www.w3schools.com/php/php_mysql_prepared_statements.asp
you can change the code of this
$result = mysqli_query($conn,$sql);
if ($conn->query($sql) === TRUE) {
echo "<p>New record created successfully</p>.";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
into this
$result = mysqli_query($conn,$sql);
if ($result === TRUE) {
echo "<p>New record created successfully</p>.";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
and also you must to be careful about sql injection so i think you must use this

How can I check for duplicate usernames using PHP and MySQL?

I'm just learning PHP and I thought it would be a good idea to learn some MySQL too.So I started working on the code and for some strange reason I keep getting duplicate users which is really really bad.
<?php
$link = mysqli_connect(here i put the data);
if(!$link)
{
echo "Error: " . mysqli_connect_errno() . PHP_EOL;
exit;
}
else
{
if(isset($_POST['user']))
{ echo "User set! "; }
else { echo "User not set!"; exit; }
if(isset($_POST['pass']) && !empty($_POST['pass']))
{ echo "Password set! "; }
else { echo "Password not set!"; exit; }
$num = mysqli_num_rows(mysqli_query("SELECT * FROM `users` WHERE ( username = "."'".$_POST['user']."' )"));
if($num > 0)
{ echo "Cannot add duplicate user!"; }
mysqli_close($link);
}
?>
For some strange reason I don't get the output I should get.I've tried some solutions found here on StackOverflow but they didn't work.
The first parameter of connectionObject is not given in mysqli_query:
$num = mysqli_num_rows(mysqli_query($link, "SELECT * FROM `users` WHERE ( `username` = '".$_POST['user']."' )"));
//----------------------------------^^^^^^^
Also, your code is vulnerable to SQL Injection. A simple fix would be:
$_POST['user'] = mysqli_real_escape_string($link, $_POST['user']);
mysqli_query must receive two parameters in order to work. In this case, your mysqli_connect.
$num = mysqli_num_rows(mysqli_query($link, "SELECT * FROM `users` WHERE ( username = "."'".$_POST['user']."' )"));
Also, you can be affected by SQL Injection, in this code.
Never add user input directly in your queries without filtering them.
Do that to make your query more readable and safe:
$u_name=mysqli_real_escape_string($link, $_POST['user']);
$num = mysqli_num_rows(mysqli_query($link, "SELECT * FROM `users` WHERE ( username = '$u_name' )"));
To use mysqli_* extension, you must include your connection inside of the parameters of all queries.
$query = mysqli_query($link, ...); // notice using the "link" variable before calling the query
$num = mysqli_num_rows($query);
Alternatively, what you could do is create a query() function within your website, like so:
$link = mysqli_connect(...);
function query($sql){
return mysqli_query($link, $sql);
}
and then call it like so:
query("SELECT * FROM...");
This could be a problem of race condition.
Imagine that two users wants to create the same username at the same time.
Two processes will execute your script. So both scripts select from database and find out that there is not an user with required username. Then, both insert the username.
Best solution is to create unique index on username column in the database.
ALTER TABLE users ADD unique index username_uix (username);
Then try insert the user and if it fails, you know the username exists ...
Here's how to write your code using prepared statements and error checking.
Also uses a SELECT COUNT(*)... to find the number of users instead of relying on mysqli_num_rows. That'll return less data from the database and just seems cleaner imo.
<?php
$link = mysqli_connect(here i put the data);
if(!$link) {
echo "Error: " . mysqli_connect_errno() . PHP_EOL;
exit;
}
else if(!isset($_POST['user'])) {
echo "User not set!"; exit;
}
echo "User set! ";
if(!isset($_POST['pass']) || empty($_POST['pass'])) {
echo "Password not set!"; exit;
}
echo "Password set! ";
$query = "SELECT COUNT(username)
FROM users
WHERE username = ?";
if (!($stmt = $mysqli->prepare($query))) {
echo "Prepare failed: (" . mysqli_errno($link) . ") " . mysqli_error($link);
mysqli_close($link);
exit;
}
$user = $_POST ['user'];
$pass = $_POST ['pass'];
if(!mysqli_stmt_bind_param($stmt, 's', $user)) {
echo "Execute failed: (" . mysqli_stmt_errno($stmt) . ") " . mysqli_stmt_error($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
exit;
}
if (!mysqli_execute($stmt)) {
echo "Execute failed: (" . mysqli_stmt_errno($stmt) . ") " . mysqli_stmt_error($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
exit;
}
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
$num = $row[0];
if($num > 0) {
echo "Cannot add duplicate user!";
}
}
mysqli_stmt_close($stmt);
mysqli_close($link);
please do suggest fixes to syntax, this was typed from a phone

MYSQL assign column name to variable?

I have a database table which has two columns, business and tourist.
I ask a user to select one of them from dropdown list, then use the result in a SELECT statement in MySQL. I assign this column to $cclass, then I make this statement SELECT $cclass FROM flights ....
But it always returns NULL. Why does it return NULL and how do I fix this?
My code:
$check = mysql_query("SELECT $cclass FROM flights WHERE flight_no = '$flightno'");
while ($result = mysql_fetch_assoc($check))
{
$db_seats = $result['$cclass'];
}
you should replace this line:
$db_seats = $result['$cclass'];
with this:
$db_seats = $result[$cclass];
string between 2 single quotes doesn't parsed:
Strings
Have you tried doing the following:
$check = mysql_query("SELECT".$cclass." FROM flights WHERE flight_no = '$flightno'");
First of all, this code has a serious security issue, as it is vulnerable to SQL Injection. You should be using the MySQLi extension instead, and properly filtering your input.
Try something like this:
<?php
/* Create the connection. */
$mysql = new mysqli("localhost", "username", "password", "myDB");
if ($mysql->connect_error)
{
error_log("Connection failed: " . $mysql->connect_error);
die("Connection failed: " . $mysql->connect_error);
}
/* Sanitize user input. */
if (!in_array($cclass, array('business', 'tourist')))
{
error_log("Invalid input: Must be 'business' or 'tourist'");
die("Invalid input: Must be 'business' or 'tourist'");
}
$statement = $mysql->stmt_init();
$statement->prepare("SELECT $cclass FROM flights WHERE flight_no = ?");
$statement->bind_param("s", $flightno);
if (!$statement->execute())
{
error_log("Query failed: " . $statement->error);
die("Query failed: " . $statement->error);
}
if ($statement->num_rows < 1)
{
echo "No results found.";
}
else
{
$statement->bind_result($seats);
while ($statement->fetch())
{
echo "Result: $seats";
// Continue to process the data... You can just use $seats.
}
}
$mysql->close();
However, the reason your original example is failing, is that you're quoting $cclass:
$db_seats = $result[$cclass];
However, please do not ignore the serious security risks noted above.

How do I redirect with PHP and save the link in SQL?

I have XAMPP and I want to write a simple PHP page, that redirects me to the link that I specify, and also saves the link in an SQL database.
Let's say I want to visit www.google.com:
I'd visit something like:
localhost:80/redirect.php?url=https://google.com
And PHP would redirect me there and also save the www.google.com link in an SQL table.
Can you help me out?
Considering how you formed your question, it looks as if you had an idea an just want someone to give you the solution without you even making an effort (please correct me if I'm wrong but that's how it seams...)
The task you are trying to achieve is a simple one, and it's only fair to point you in the right direction. your "task" can be broken into several smaller ones:
Create database / table for storing data | PHP Create MySQL Tables
Get URL parameter in PHP
PHP Insert Data Into MySQL
How to make a redirect in PHP
Sorry if this is not the kind-a answer you are looking for, but I figure the point of this website is for people to learn something and not just copy+paste. The provided links can be used to solve your task problem.
This is what I came up with, after MySQLi Object-oriented did not validate this:
$sql = "SELECT * FROM logging WHERE link=$link";
if ($conn->query($sql) === TRUE) {}
It still increments the number of visits sometimes by +2. I don't know why.
<?php
$servername = " ";
$username = " ";
$password = " ";
$dbname = " ";
$datetime = date_create()->format('Y-m-d H:i:s');
$datetime = "'".$datetime."'";
$link_clean = $_GET['link'];
$link = "'".$link_clean."'";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM logging WHERE link=$link";
if ($result = mysqli_query($conn, $sql))
{
if(mysqli_num_rows($result)>0)
{
$sql="UPDATE logging SET last_visit_date = $datetime, visit_count = visit_count + 1 WHERE link=$link";
if (mysqli_query($conn, $sql)) {
$conn->close();
header("Location: https://$link_clean");
exit;
} else {
echo "1Error: " . $sql . "<br>" . mysqli_error($conn);
$conn->close();
exit;
}
}
else
{
$sql="INSERT INTO logging (link, last_visit_date, visit_count) VALUES ($link , $datetime , 1)";
if (mysqli_query($conn, $sql)) {
mysqli_close($conn);
header("Location: https://$link_clean");
exit;
} else {
echo "2Error: " . $sql . "<br>" . mysqli_error($conn);
mysqli_close($conn);
exit;
}
}
}
else
{
echo "3Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>

PHP/MYSQLI - How to check if this query is possible, if so show error (see example)

I am learning some myqli and would like to make a simple check.
Basically, A user will enter their email addess then submit a form, if the email address is already contained in a certain mysql table, then the script must stop with an error.
This is my example:
$userEmail = sanitize($_POST['specials']);
// Check to see if email already exists, if not proceed
if ($stmt = $link->prepare("SELECT email FROM specials WHERE email=$userEmail"))
{
$specialsErrorFocus = 'autofocus="autofocus"';
$specialsInfo = 'This email address: $userEmail, is already in our database.';
include "$docRoot/html/shop/home.html.php";
exit();
}
This code does not do as I have intended it to as described.
Could someone please explain where I am going wrong with this, or possibly offer a better solution for this task.
Thanks in advance!
You need to execute the query first, as simply preparing the statement is not sufficient. See the documentation as it is a multi stage process.
First, you prepare the statement:
$stmt = $link->prepare("SELECT `email` FROM `specials` WHERE `email` = ?")
if (!$stmt) {
echo $link->errno . " : " . $link->error;
}
Next, bind the parameters:
if (!$stmt->bind_param("s", $userEmail)) {
echo $stmt->errno . " : " . $stmt->error;
}
Finally, execute the query:
if (!$stmt->execute()) {
echo $stmt->errno . " : " . $stmt->error;
}
Get the results:
$stmt->store_result();
if ($stmt->num_rows) {
# Email exists
}
Prepare does not execute the statement. You can use mysql::query to execute the statement.
Your Example would become:
$result = $link->query("SELECT email FROM specials WHERE email=$userEmail");
if ( $result ) {
if ( $result->num_rows > 0 ) {
$specialsErrorFocus = 'autofocus="autofocus"';
$specialsInfo = 'This email address: $userEmail, is already in our database.';
include "$docRoot/html/shop/home.html.php";
exit();
}
}

Categories