PHP Submitting wrong information on a MySQL database (PHP+MySQL) - php

I've been having this weird bug, basically what happens is that I have this App on Android and whenever I try to add a new "user" one of it's values (Called "Contacto") sometimes is wrong, the weird part is that it happens in a completely random way, here is my .php
<?PHP
$con=mysqli_connect("localhost","root","","proyecto");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['txtNombre']) && isset($_POST['txtcontactousuarionuevo']) &&
isset($_POST['txtPass']) && isset($_POST['txtprograma'])){
$nombreestudiante = $_POST['txtNombre'];
$contactoestudiante = $_POST['txtcontactousuarionuevo'];
$passestudiante = $_POST['txtPass'];
$programa = $_POST['txtprograma'];
$query = "INSERT INTO estudiante(Nombre, Contacto, Id_Periodo_FK, Pass)
VALUES ('$nombreestudiante', $contactoestudiante, 4, '$passestudiante');";
$query .= "INSERT INTO estudiante_programa(EstudianteE_P_FK, ProgramaE_P_FK)
VALUES(LAST_INSERT_ID(), $programa)";
$result =mysqli_multi_query($con,$query);
if($result > 0){
if(isset($_POST['mobile']) && $_POST['mobile'] == "android"){
echo "success";
exit;
}
echo "Insert Successfully";
}
else{
if(isset($_POST['mobile']) && $_POST['mobile'] == "android"){
echo "failed";
exit;
}
echo "Something Error";
}
}
?>
<html>
<head><title>Insert | ProyectoBD</title></head>
<body>
<h1>Insert ProyectoBD| <a>Santiago TroitiƱo C - 201421697</a></h1>
<form action="<?PHP $_PHP_SELF ?>" method="post">
Nombre <input type="text" name="txtNombre" value=""/><br/>
Contacto <input type="text" name="txtcontactousuarionuevo" value=""/><br/>
Pass <input type="text" name="txtPass" value=""/><br/>
<input type="submit" name="btnSubmit" value="Insert"/>
</form>
</body>
My app has a Login Screen and a button that takes it to a register form, the .php executed on that page (Login page) looks like this:
<?PHP
include_once("connection.php");
if(isset($_POST['txtUsername']) && isset($_POST['txtPassword'])){
$username = $_POST['txtUsername'];
$password = $_POST['txtPassword'];
$query = "SELECT * FROM estudiante WHERE Nombre = '$username'
AND Pass = '$password'";
$result = mysqli_query($conn, $query);
if($result->num_rows > 0){ //has record. correct username and password
echo "success";
while($row = $result->fetch_assoc()) {
echo " ". $row["Id_Estudiante"]. "";
exit;
}
exit;
}
else{
echo "Wrong username and password";
exit;
}
exit;
}
?>
<html>
<head><title>Login | ProyectoBD</title></head>
<body>
<h1>Login ProyectoBD | <a>Santiago TroitiƱo C - 201421697</a></h1>
<form action="<?PHP $_PHP_SELF ?>" method="post">
Nombre <input type="text" name="txtUsername" value="" placeholder="Ingresar Nombre" /><br/>
Password <input type="password" name="txtPassword" value="" placeholder="Ingresar Pass" /><br/>
<input type="submit" name="btnSubmit" value="Login"/>
</form>
</body>
</html>
Those are the only .php excuted on this part of the app...As you can see on this image the number "2147483647" keeps appearing at complete random times,
I used that number for a register once but kkeps appearing
Any ideas of how may I solve this? Thanks!

What is the data type of Contacto in your database? Does the issue present itself when you include Non-Numeric characters. For example, if you have your data type in your database for a phone number as a numeric type (BIGINT, INT) and your users attempt to enter VARCHAR characters like hyphens i.e. "111-111-1111" it can cause the database to save the entry as the highest number the data type can hold. If this issue occurs when you use non-numeric characters, change your data type for Contacto to VARCHAR.

Related

Connection Login Php with MySql

I am trying to Log in a webPage using MySql, however, for some reason, I can't query from the database
I keep getting the error "failure"
Here is my code php:
<?PHP
include_once("connection.php");
if (isset($_POST['txtUsername']) && isset($_POST['txtPassword'])) {
$username = $_POST['txtUsername'];
$password = $_POST['txtPassword'];
$query = "SELECT username, password FROM tbl_client ".
" WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $query);
if ($result->num_rows > 0) {
echo "success";
}
echo "failure ";
}
?>
The html Code is:
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login Example <a <br />
<form action="<?PHP $_PHP_SELF ?>" method="post">
Username <input type="text" name="txtUsername" value="" /><br />
Password <input type="password" name="txtPassword" value="" /><br />
<input type="submit" name="btnSubmit" value="Login" />
</form>
</body>
</html>
My database is:
Database
Databas
My values are: username: test and password: test
But keep getting this error:
HTML
If you are sure your $username and $password are present in database, then you probably want to return right after you figured out that user provided wrong credentials. Something like that:
$result = mysqli_query($conn, $query);
if ($result->num_rows == 0) {
echo "failure";
return;
}
echo "success";
/**
* keep doing stuff for logged user
*/
NEVER store passwords in plain text AND use placeholders and escaping for sending user data to database. Google SQL injections and take a look on real_escape_string

Is anything wrong with this code?

I used this code to create a user registration page in my website. I firstly connected to my database and then did the below codes ----->
<form action="index.php" method="post">
<p id="usr1">Name : </p><input id="input1" placeholder="Username" type="text" name="username" required> </br>
</br>
<p id="usr2">Password : </p><input id="input2" placeholder="Password" type="text" name="pwd" required> </br>
<p id="usr3">Password : </p><input id="input3" placeholder="Re-Type your password" type="text" name="cpwd" required> </br>
</br>
<input id="sub" name="subbox" type="submit">
</form>
<?php
if (isset($_POST['submit_button'])) {
$username= $_POST['username'];
$password=$_POST['pwd'];
$conpwd=$_POST['cpwd'];
}
if ($password == $conpwd) {
$query = "SELECT * FROM login WHERE name='$username' ";
$query_run = mysqli_query($con,$query);
if (mysqli_num_rows($query_run) > 1) {
echo '<script type="text/javascript">alert("This Username Already exists. Please try another username!")</script>';
// the above code will check if the username is already taken or not.
}else {
$query = "insert into login values('$username' , '$password')";
$query_run = mysqli_query($con,$query);
if ($query_run) {
echo '<script type="text/javascript">alert("Registration Successful!")</script>Click Here To Continue';
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header( "Location: homepage.php");
}else {
echo '<script type="text/javascript">alert("Server Error. Please try again after a few minutes!")</script>';
}
}
}else {
echo "Please check and re-type both passwords";
}
?>
But it always return some errors.This is what I see when i try to run the code
Is anything wrong with this code?
To answer your initial question, yes there is something wrong. Your code is vulnerable to SQL injection. You should have a look at: How can I prevent SQL injection in PHP? And password is stored plain in your database, which means no respect for your user. There are some other problems with code style but it's just bonus.
Anyway, the thing that cause you the "alert" problem is that submit_button button does not exists. There is no button with that name. Your if condition is always false. So you have to replace:
if (isset($_POST['submit_button'])) {
With
if (isset($_POST['subbox'])) {
And maybe add a value to your input (not sure it's required, I did not tested):
<input id="sub" name="subbox" type="submit" value="1">
Thanks to #Fred-ii-

Login PHP with DB

I am trying to do a login with MySQL, but it's not working. Basically I'm trying to check the login and password posted against my DB, but it's not working for some reason. Could someone give me a hint?
login.php
include "conexao.php";
$result = mysql_query("SELECT * FROM usuario WHERE login = '".$_POST['login']."' AND senha = '".$_POST['senha']."'") or die (mysql_error());
while ($row = mysql_fetch_assoc($result)) {
session_start();
if ($_POST['login'] && $_POST['senha']) {
if ($row['login'] == $_POST['login'] && $row['senha'] == $_POST['senha']) {
$_SESSION['login'] = $row['login'];
$_SESSION['senha'] = $row['senha'];
header("Location: index.php");
} else {
unset ($_SESSION['login']);
unset ($_SESSION['senha']);
header("Location: login2.php?i=n");
}
}
}
HTML form
<form method="post" action="login.php" class="cbp-mc-form" autocomplete="off">
<label for="login">Login</label>
<input type="text" name="login" id="login" /><br />
<label for="senha">Senha</label>
<input type="password" name="senha" id="senha" /><br />
<center><input class="cbp-mc-submit" type="submit" value="Login""/></center>
</form>
Dear Brother try the following code, (I edited your code)
I hope it will work in your case, but if you're using the same code for production, than please take care of the Sanitization.
the code I edited for you is as follows (if it still doesn't work, than there might be some error in your database connection).
The PHP Script:
<?php
session_start(); // better to start the session in the begining,
//in some cases it doesn't work in the mid of the document'
include 'conexao.php';
if (isset($_POST['login']) && isset($_POST['senha'])) // check if both the form fields are set or not
{
// Values coming from the user through FORM
$login_form = $_POST['login'];
$senha_form = $_POST['senha'];
// query the database only when user submit the form with all the fields filled
$result = mysql_query("SELECT * FROM usuario WHERE login='$login_form' AND senha='$senha_form'") or die (mysql_error());
while ($row = mysql_fetch_assoc($result))
{
// values coming from Database
$login_db = $row['login'];
$senha_db = $row['senha'];
}
// compare the values from db to the values from form
if ($login_form == $login_db && $senha_form == $senha_db)
{
// Set the session only if user entered the correct username and password
// it doesn't make sense to set session even if the user entered wrong values
$_SESSION['login'] = $login_db;
$_SESSION['senha'] = $senha_db;
header("Location: index.php");
}
else
{
header("Location: login2.php?i=n");
}
}
?>
The HTML: (exactly your html copied)
<form method="post" action="login.php" class="cbp-mc-form" autocomplete="off">
<label for="login">Login</label>
<input type="text" name="login" id="login" /><br />
<label for="senha">Senha</label>
<input type="password" name="senha" id="senha" /><br />
<center><input class="cbp-mc-submit" type="submit" value="Login""/></center>
</form>
from PHP Header not redirecting
I added ob_start(); on the very first line and it worked.

Issue with php mysql login $_POST['username'] = $result['username']

I'm kinda' beginner and I've coded my own PHP login from Zero, but I still got some errors, here's the code:
<?php
include 'connection.php';
$query = " SELECT * FROM admin";
$result = mysql_query($query) or die(mysql_error());
?>
<form action="<?php echo $_SERVER['SELF_PHP']; ?>" method="post">
Username : <input type="text" name="usernameInput" value="" />
Password : <input type="password" name="passwordInput" value="" />
<input type="submit" value="Login" />
</form>
<?php
$username = $_POST['usernameInput'];
$password = $_POST['passwordInput'];
if ($username = $result['username']) {
if ($password = $result['password']){
header('Location: admin.php');
} else {
echo "PASSWORD IS INCORRECT";
}
} else {
echo "USERNAME IS INCORRECT";
}
?>
So if you can fix this or got an easier way from PHP login from please tell me. :)
A few things...
Don't use mysql functions
You need to use == to compare strings, not =
You need to actually fetch the results of your query
include 'connection.php';
$query = " SELECT * FROM admin";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_row($result); /* add this */
?>
<form action="<?php echo $_SERVER['SELF_PHP']; ?>" method="post">
Username : <input type="text" name="usernameInput" value="" />
Password : <input type="password" name="passwordInput" value="" />
<input type="submit" value="Login" />
</form>
<?php
if(isset($_POST['usernameInput']) && isset($_POST['passwordInput'])){
$username = $_POST['usernameInput'];
$password = $_POST['passwordInput'];
}
else{
echo 'some error ...';
}
if($username == $row ['username'] && $password == $row ['password']){
header('Location: admin.php');
}
else{
echo ' username or password is wrong';
}
?>
I have to point out that you are sending the same form over and over without first checking the post. And when you send the form, you will not be able to send the header to redirect, because html is started and headers are sent already.
Mysql functions are deprecated, please use mysqli interface.
Among other several bugs like assignment = instead of is equal ==
Try it this way:
If no post exists send the form else check and if ok redirect or not ok. resend the form
<?php
if($_POST){
include 'connection.php';
$query = " SELECT * FROM admin";
$r = mysql_query($query) or die(mysql_error());
// get an associated array from query result resource.
$result = mysql_fetch_assoc($r);
$username = $_POST['usernameInput'];
$password = $_POST['passwordInput'];
if ( ($username == $result['username'])
&& ($password == $result['password'])){
header('Location: admin.php');
exit(0);
} else {
echo "PASSWORD IS INCORRECT";
}
}
?>
<form action="<?php echo $_SERVER['SELF_PHP']; ?>" method="post">
Username : <input type="text" name="usernameInput" value="" />
Password : <input type="password" name="passwordInput" value="" />
<input type="submit" value="Login" />
</form>
<?php
?>

inserting data into mysql from an html textboxes. using php/mysql

I can't see where i am going wrong, it just won't let me connect to the mysql database and i only get error message when trying to save details.?????? i think there may be a problem where it shows $sql for inserting the values into the table. the first part newstudent.php works, but sql.php does not work.
//new student.php
<html>
<head>
</head>
<body>
<h2>Your details</h2>
<form name="frmdetails" action="sql.php" method="post">
ID Number :
<input name="txtid" type="text" />
<br/>
Password :
<input name="txtpassword" type="text" />
<br/>
Date of Birth :
<input name="txtdob" type="text" />
<br/>
First Name :
<input name="txtfirstname" type="text" />
<br/>
Surname :
<input name="txtlastname" type="text" />
<br/>
Number and Street :
<input name="txthouse" type="text" />
<br/>
Town :
<input name="txttown" type="text" />
<br/>
County :
<input name="txtcounty" type="text" />
<br/>
Country :
<input name="txtcountry" type="text" />
<br/>
Postcode :
<input name="txtpostcode" type="text" />
<br/>
<input type="submit" value="Save" name="submit"/>
</form>
</body>
</html>
//sql.php
$conn=mysql_connect("localhost", "20915184", "mysqluser");
mysql_select_db("db5_20915184", $conn);
// If the form has been submitted
$id=$_POST['txtstudentid'];
$password=$_POST['txtpassword'];
$dob=$_POST['txtdob'];
$firstname=$_POST['txtfirstname'];
$lastname=$_POST['txtlastname'];
$house=$_POST['txthouse'];
$town=$_POST['txttown'];
$county=$_POST['txtcounty'];
$country=$_POST['txtcountry'];
$postcode=$_POST['txtpostcode'];
// Build an sql statment to add the student details
$sql="INSERT INTO student
(studentid,password,dob,firstname,lastname,house,town,county,country,postcode) VALUES
('$id','$password','$dob','$firstname','$lastname','$house','$town','$county','$country','$postcode')";
$result = mysql_query($sql,$conn);
if($result){
echo"<br/>Your details have been updated";
echo "<BR>";
echo "<a href='Home.html'>Back to main page</a>";
}
else {
echo "ERROR";
}
// close connection
mysql_close($conn);
?>
The username comes before the password in mysql_connect();
Try running the sql statement in phpmyadmin and see if it works there!
With in your if else statement, where you echo "ERROR", try printing mysql_error() this would show that your mysql_connect() is wrong If the username/password combo is wrong.
To clean this up a bit, Here is what the if/else should look like
if($result){
echo"<br/>Your details have been updated";
echo "<BR>";
echo "<a href='Home.html'>Back to main page</a>";
} else {
echo "There has been an error <br/>";
print mysql_error();
}
EDIT :
Also, Prevent sql injection with mysql_real_escape_string() on all posted values
Well your code is incomplete, you must insert when the button is clicked also its important to check if a field isset before saving the field in the database also important to filter and sanitize user inputs before submitting. Learn to use prepared statements, with mysqli prepared or PDO whatever works for you, Also don't store passwords in plain text/md5 use password_hash() and password_verify()
Your code with mysqli prepared should look like :
<html>
<head>
</head>
<body>
<h2>Your details</h2>
<form name="frmdetails" action="sql.php" method="post">
ID Number :
<input name="txtid" type="text" />
<br/>
Password :
<input name="txtpassword" type="text" />
<br/>
Date of Birth :
<input name="txtdob" type="text" />
<br/>
First Name :
<input name="txtfirstname" type="text" />
<br/>
Surname :
<input name="txtlastname" type="text" />
<br/>
Number and Street :
<input name="txthouse" type="text" />
<br/>
Town :
<input name="txttown" type="text" />
<br/>
County :
<input name="txtcounty" type="text" />
<br/>
Country :
<input name="txtcountry" type="text" />
<br/>
Postcode :
<input name="txtpostcode" type="text" />
<br/>
<input type="submit" value="Save" name="submit"/>
</form>
</body>
</html>
sql.php
<?php
$servername = "localhost";
$username = "20915184";
$password = "mysqluser";
$dbname = "db5_20915184";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$errors = "";
if (isset($_POST['submit'])) { // submit button clicked
// validate fields
if (empty($_POST['txtstudentid'])) {
echo "enter id";
$errors++;
} else {
$id = userData($_POST['txtstudentid']);
}
if (empty($_POST['txtpassword'])) {
echo "enter password";
$errors++;
} else {
$password = userData($_POST['txtpassword']);
$hash = password_hash($password, PASSWORD_DEFAULT); //hashing password
}
if (empty($_POST['txtdob'])) {
echo "enter date of birth";
$errors++;
} else {
$dob = userData($_POST['txtdob']);
}
if (empty($_POST['txtfirstname'])) {
echo "enter first name";
$errors++;
} else {
$firstname = userData($_POST['txtfirstname']);
}
if (empty($_POST['txtlastname'])) {
echo "enter last name";
$errors++;
} else {
$lastname = userData($_POST['txtlastname']);
}
if (empty($_POST['txthouse'])) {
echo "enter house";
$errors++;
} else {
$house = userData($_POST['txthouse']);
}
if (empty($_POST['txttown'])) {
echo "enter town";
$errors++;
} else {
$town = userData($_POST['txttown']);
}
if (empty($_POST['txtcounty'])) {
echo "enter country";
$errors++;
} else {
$country = userData($_POST['txtcounty']);
}
if (empty($_POST['txtpostcode'])) {
echo "enter post code";
$errors++;
} else {
$postcode = userData($_POST['txtpostcode']);
}
if ($errors <= 0) { //all fields are set no errors
//start query
//check if user id does not exist
$statement = $conn->prepare("SELECT studentid FROM students WHERE studentid = ?");
$statement->bind_param('s', $id);
$statment->execute();
$statement->bind_result($studentID);
if ($statement->num_rows == 1) {
echo "the student Id " . $studentID . " already registered please login";
} else {
// no results then lets insert
$stmt = $conn->prepare("INSERT INTO students (studentid,password,dob,firstname,lastname,house,town,country,postcode) VALUES(?,?,?,?,?,?,?,?,?)");
$stmt->bind_param("sssssssss", $id, $hash, $dob, $firstname, $lastname, $house, $town, $country, $postcode);
$stmt->execute();
echo "<p>Your Details have been updated<br> <a href=\"Home.html\">Back to main page";
$stmt->close();
$conn->close();
}
}
}
//filter userinput
function userData($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
There are many good tutorials on the net on this, hopes this will help, I'm also open to suggestions and corrections incase I missed something.
**> Question mark (?)(placeholder) is used to assign the value.In Prepared
Statements we assign in the values in bind parameter function so that
our query is processed in secure way and prevent from SQL injections.**
In Prepared Statements we pass or attach the values to database query with the help of Bind Parameter function.
You have to attach all the variables whose value you want in your query with their appropriate Data Types just like we pass the 's' means the variable contains a string Data Type.
To execute the query in Prepared Statements you have to use execute() function with query object.
Remove the parameter from your with the inside inside and put in an empty string. i.e
VALUES('','$password','$dob',
etc etc

Categories