POST Issue with PHP - php

I have tried putting together a basic jQuery Mobile page that connects to another file on the same path of the server to send the data. I have tested the PHP by itself in the commented out part of code.
The PHP File - submit harvest.php
$dbConnection = mysqli_connect('*********', '*********', '*********', '*********');
/*
$variety = "Aji Limon";
$picked = "11";
$weight = "22";
*/
$variety = $_POST['variety'];
$picked = $_POST['picked'];
$weight = $_POST['weight'];
$query = "INSERT INTO `harvest` (`variety`, `picked`, `weight`) VALUES ('$variety', '$picked', '$weight')";
if (mysqli_query($dbConnection, $query)) {
echo "Successfully inserted " . mysqli_affected_rows($dbConnection) . " row";
} else {
echo "Error occurred: " . mysqli_error($dbConnection);
}
?>
And the html file - index.html
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
<!--Mobile Device Scaling -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0" />
</head>
<body>
<div data-role="page" id="harvest">
<div data-role="header" data-theme="b">
<h1>Chilli Harvest</h1>
</div>
<div data-role="content">
<form name="harvest" action="submitharvest.php" method="post" data-ajax="false">
<div data-role="fieldcontain">
<label for="variety" class="select" >Variety:</label>
<select name="variety" id="variety" data-theme="b">
<option value="7 Pot Red">7 Pot Red</option>
<option value="7 Pot Yellow">7 Pot Yellow</option>
<option value="Aji Limon">Aji Limon</option>
</select>
</div>
<div data-role="fieldcontain">
<label for="picked">Qty Picked:</label>
<input type="range" name="picked" id="picked" value="1" min="0" max="200" step="1" data-theme="b" data-track-theme="c"/>
</div>
<div data-role="fieldcontain">
<label for="weight">Weight (g):</label>
<input type="number" name="weight" id="weight" value="" data-theme="b" />
</div>
<div data-role="fieldcontain">
<input type="submit" value="Send" id="submit">
</div>
</form>
</div>
</div>
</body>
</html>
Having added the data-ajax="false" and even removing the entire query mobile framework I get the same problem of the php stating "Error Occurred" with no extra detail following it, I can't see anything going wring in the console either. Hopefully I'mm missing something very basic here? Please help.
So having tried a few things from the first couple of comments below - would it also be that the dbconnection being the culprit? I am using a NAS drive with personal MySQL database on it, do I need to speify the port number at the end? Currently I have:
$dbConnection = mysqli_connect('home IP Address:3306', 'username', 'password', 'databasename');
I have seen some connection strings like this where port numbers are involved:
$dbConnection = mysqli_connect('home IP Address', 'username', 'password', 'database name', 3306);
Which really adds to my confusion as I have tried all of the above and even putting the port number in "3306"... Stumped, anyone got any further ideas please?

Turns out after many hours of wasting time the web server that it was hosted on was blocking the MySQL via it's Firewall, so all my check were ok but the web host firewall was to blame and the web company have added an exclusion to allow this to work!

Related

Why is the condition not right with my code? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I'm a beginner in PHP and MySQL and I want to add values that come from an input in HTML, to a MySQL database.
I have to find some things on the Internet but this doesn't work and so I tried to learn a little bit more PHP but I still don't understand why the condition in the code below is not valid:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8">
<title>SHAR-APP</title>
</head>
<body>
<div class='div1'>
<div class='div2'>
<label for="name">Name of the user:</label>
<input class ='in'type="text" id="name" name="name" size="20">
</div>
<div class='div2'>
<label class = 'label' for="name">Code:</label>
<input class='in' id ='code' type="text" name="code" size="20">
</div>
<div class="div2" id='b'>
<input type="submit" value="send" class='button'>
</div>
</div>
<?php
echo "test1";
if (isset($_POST['name'])) {
echo "test2";
$mtsqli = mysqli_connect('localhost','the_name_of_my_project','my_password');
mysqli_select_db('project_database', $msqli);
$requete = 'INSERT INTO the_name_of_the_database's_table VALUES(NULL,"' . $_POST['name'] . '","' . $_POST['code'] . '")';
$query = "SELECT * FROM the_name_of_the_database's_table";
echo $_POST['name'];
echo "test3";
}
?>
</body>
</html>
I'm on this for 3 days and I'm really blocked. Maybe I have others mistake in the PHP code. If I can do that with another language i prefer to stay on PHP because I don't want to learn too much languages. If I can do a bridge between HTML and MySQL with Python or JavaScript I'm OK to know that.
THIS PART IS GOOD but another problem is come ...
when i want to connect on my database this error message is display
C:\Users\titou>set PATH=$PATH$;C:\Program Files\MySQL\MySQL Server 8.0\bin
C:\Users\titou>mysql -h localhost -u root -p
Enter password: **********
ERROR 1045 (28000): AccŠs refus‚ pour l'utilisateur: 'root'#'#localhost' (mot de passe: OUI)
its in french but you can see that there is two # instand of one ('root'#'localhost')
First you need to add a Form Method
<form action="" method="POST">
<div class='div2'>
<label for="name">Name of the user:</label>
<input class ='in'type="text" id="name" name="name" size="20">
</div>
<div class='div2'>
<label class = 'label' for="name">Code:</label>
<input class='in' id ='code' type="text" name="code" size="20">
</div>
<div class="div2" id='b'>
<input type="submit" value="send" class='button'>
</div>
</form>
The is some kind of class that tells the browser to expect inputs and then on the button click- to treat them.
The Action="" is for initializing where to treat the given inputs.
In your case, since your php code is in the same class as the form, you can leave it blank, either way you should initialize the path you want to send those data.
The Method="POST" is just a Method for treating your data on the web. It is also more secure than GET method which it works too but it's more sensitive since all the data from the inputs it's going to be exposed also in the URL.
Furthermore, I hope you have already installed XAMPP and already created a database in MySQL.
Add the form attribute to your form and in it add a method and an action. Method is needed to tell the form to post, and action is needed to tell the form what to do when you submit.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8">
<title>SHAR-APP</title>
</head>
<body>
<form method="post" action="">
<div class='div1'>
<div class='div2'>
<label for="name">Name of the user:</label>
<input class ='in'type="text" id="name" name="name" size="20">
</div>
<div class='div2'>
<label class = 'label' for="name">Code:</label>
<input class='in' id ='code' type="text" name="code" size="20">
</div>
<div class="div2" id='b'>
<input type="submit" value="send" class='button'>
</div>
</div>
</form>
<?php
if (isset($_POST['name'])) {
$db = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$requete = 'INSERT INTO the_name_of_the_database's_table VALUES(NULL,"' . $_POST['name'] . '","' . $_POST['code'] . '")';
mysqli_query($db, $requete);
$query = "SELECT * FROM the_name_of_the_database's_table";
$Data = mysqli_query($db, $query);
var_dump[$Data];
}
?>
</body>
</html>
Now an important thing to note, never use this in a live website as it would open up your website to SQL injection. You should use prepared statements instead, but for learning purposes, this is fine.

Data retrieved From MySQL not showing when using PHP

I am working on this program that gets some inputs from the user and then uses that input to retrieve data from a few tables in a MySQL database. My issue is that it seems like I am not getting anything from the MySQL tables, and it would be great if you could help.
dbConn.php
<?php
$ser = "localhost";
$user = "root";
$pass = "pass";
$db = "dbvisual";
$conn = mysqli_connect($ser, $user, $pass, $db) or die("connection failed");
echo "connection success";
?>
form.php
<?php
if(isset($_Post['submit'])){ // Checking to see if the form has been submitted
$battery = (int) $_POST['battery']; // Battery Input element
$cycle = (int) $_POST['cycle']; // Cycle input element
$xVar = $_POST['X']; // X variable
$yVar = $_POST['Y']; // Y variable
// Trying to get the x variable based on what the user said
$mySqlQueryX = "SELECT cap
FROM cycle
WHERE cycleID = $cycle";
$feedbackX = mysqli_query($conn, $mySqlQueryX);
echo "<h1>$feedbackX</h1>";
}
?>
index.php
<!-- Connecting to the database -->
<?php
include 'dbConn.php';
?>
<!-- The Styling of the website -->
<style>
<?php include 'main.css'; ?>
</style>
<!-- The Skeleton of the website -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<?php include "form.php" ?>
<!-- The entire website -->
<div id="body">
<!-- The input half -->
<div id="inputs">
<!-- The input form -->
<form action="index.php" method="POST">
<div id="form">
<!-- Labels -->
<div id="label">
<label for="">Which Batteries?</label>
<label for="">What Cycles?</label>
<label for="">What's X?</label>
<label for="">What's Y?</label>
<label for="">Discharge?</label>
<label for="">Charge?</label>
</div>
<!-- User Info -->
<div id="info">
<input type="text" placeholder="Batteries" required
oninvalid="this.setCustomValidity('No Batteries Were Entered')"
oninput="setCustomValidity('')" name="battery">
<input type="text" placeholder="Cycles" required
oninvalid="this.setCustomValidity('No Cycles Were Entered')"
oninput="setCustomValidity('')" name="cycle">
<select name="X">
<option value="cap">Capacity</option>
<option value="speCap">Specific Capacity</option>
<option value="voltage">Voltage</option>
</select>
<select name="Y">
<option value="cap">Capacity</option>
<option value="speCap">Specific Capacity</option>
<option value="voltage">Voltage</option>
</select>
<input type="checkbox" name="discharge" checked>
<input type="checkbox" name="charge" checked>
</div>
</div>
<!-- Submit Button -->
<div>
<button type="submit" name="submit">Submit</button>
</div>
</form>
</div>
<!-- The graph half -->
<div id="graph">
<p>hello</p>
</div>
</div>
</body>
</html>
When I try to "echo" what I am supposed to get from the database, nothing shows up and I am guessing the issue could be related to mysqli_query() having problems with $conn.
Thank you all!
You need to change your form.php file this is what I propose
<?php
if(isset($_POST['submit'])){
$battery = (int) $_POST['battery']; // Battery Input element
$cycle = (int) $_POST['cycle']; // Cycle input element
$xVar = $_POST['X']; // X variable
$yVar = $_POST['Y'];
$con = mysqli_connect("localhost","root","passer","arduino");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$mySqlQueryX = "SELECT cap
FROM cycle
WHERE cycleID = '".$cycle."' ";
$result = mysqli_query($con, $mySqlQueryX);
// Fetch all
print_r(mysqli_fetch_all($result, MYSQLI_ASSOC));
// Free result set
mysqli_free_result($result);
mysqli_close($con);
}

HTML will not display after php validation? [duplicate]

This question already has answers here:
How can I get useful error messages in PHP?
(41 answers)
Closed 3 years ago.
My HTML on my page is eliminated after running my PHP validation on the input form.
HTML: InsertUser.php
<?php
session_start();
require_once('File Below');
echo $errors; //Errors is local variable within insertBackend.php i know. i just wanted this example to be exact compared next to my code.
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script
</head>
<body>
<div class="container">
<form class="form-horizontal" role="form" method="post" action="InsertUser.php">
<div class="form-group">
<label for="txtName" class="col-sm-2 control-label">Name:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputName" name="txtName" placeholder="Name" value="">
</div>
</div>
<div class="form-group">
<label for="txtPassword" class="col-sm-2 control-label">Password:</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword" name="txtPassword" placeholder="Password" value="">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="btnSubmit" name="insert_form" type="submit" value="Submit" class="btn btn-primary">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="btnCreate" onclick="location.href = 'createUser.php';" name="createUser" type="button" value="Create User" class="btn btn-primary">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="btnsame" onclick="location.href = 'InsertUser.php';" name="InsertUser" type="button" value="Insert User" class="btn btn-primary">
</div>
</div>
</form>
</div>
</body>
</html>
PHP Page: InsertBackend.php
<?php
session_start();
require_once('*DIRECTORY CONTAINING SQL CONNECTION*'); //works fine
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
if(isset($_POST['insert_form']))
{
$_SESSION['InsertUser'] = "Insert User Pass"; //This ensures i make it INTO the method
$name= "";
$password = "";
$nameInsert = mysqil_real_escape_string($_POST['txtName']);
//^This right here. mysqli_real_escape_string();
$passInsert = mysqil_real_escape_string($_POST['txtPassword']);
//^This right here. mysqli_real_escape_string();
$errors = array();
if(empty($nameInsert))
{
array_push($errors, "Please enter your Name");
}
if(empty($passInsert))
{
array_push($errors, "Please enter your password");
}
if(count($errors = 0))
{
$name = mysqil_real_escape_string($con, $_POST['txtName']);
$password = mysqil_real_escape_string($con, $_POST['txtPassword']);
$hashPass = password_hash($password, PASSWORD_DEFAULT);
$sqlInsert = "INSERT INTO Table (Name, Phash)
VALUES ('$name', '$hashPass')";
$_SESSION['VerifyHash'] = $hashPass; // Super security issue using a hashed password as a flag? I know. Just wanted visual representation of pass to compare next to my database
if ($con->query($sqlInsert) === TRUE)
{
header('location: InsertUser.php');
echo "New record created successfully <br>";
}
else
{
header('location: InsertUser.php');
echo "Error: " . $sql . "<br>" . $con->error;
}
}
}
echo "Connected"; //Flag to verify Database connection throughout usage. If it makes it here then its connected. End flag.
//CLOSE DATABASE CONNECTION
mysqli_close($con);
?>
When I run all of this together and enter test data. It arrives on: InsertUser.php. and directs properly. However it displays nothing. No code, no Sessions, no HTML. Nothing? However when I simply refresh the page without navigating anywhere it displays the entire insert form fine. And 2 of my flags display:
ConnectedInsert User Pass
I then proceed to eliminate session data. Then I just see
Connected
above the login form. After this all takes place there is no change in my Database? And no users are actually added.
Using this information I can deduce that:
my form submits to my InsertBackend.php file when called from the form.
is connected to my database appropriately.
And that my Backend script is:
Not correctly inserting into the database.
Not properly hashing my password input.
Not rendering the HTML when called back to the insert form.
I have tried really hard to figure out where exactly in this chain of events things are going awry. However I have been unable to figure out why it is not all calling properly, and why my inserts are not working at all.
I really tried finding something on here that would help me figure it out. Unfortunately I was unable to locate anything that gave me clarity. And after the last few hours i have decided to see if anyone here might have any helpful insight into my issue. Just to even have a second set of eyes on it.
This was just poorly built with no session checking. The session cannot be created if it already exists i suppose.
Using
print_r(error_get_last());
Provides me with
Array ( [type] => 8 [message] => session_start(): A session had already been started - ignoring [file] => *InsertBackend.php* [line] => 2 )
Maybe? I guess i have to test this theory. I will update code as i progress until page is all displaying and inserting into database in case anyone else runs into a similar issue down the road.

Issues with using SHA1 password encryption in PHP/mysql

I have a simple script for user login. I have the passwords encrypted as SHA1 in mySQL database table (using charset utf8_unicode_ci).
When I run "$q" in the database with values it returns result all right. But through the script even after entering correct credentials, I am not able to login. Also, it is working fine if I remove the encryption at both places (script and database). Same problem occurs if I use MD5 instead.
I am not sure what I am missing at. I tried to echo the SHA1 output and it comes out to be different than the encrypted password visible in the database. I have checked for any extra spaces in my input as well. Please help me understand what is wrong. Let me know if you need anything else. Thanks in advance!
connection.php holds the login credentials to the database and the below line:
$dbc = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
Below is the login page : "login.php"
<?php
#Start the session:
session_start();
include('../setup/connection.php');
if($_POST) {
$q = "select * from users where email = '$_POST[email]' and password = SHA1('$_POST[password]');";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) == 1) {
$_SESSION['username'] = $_POST['email'];
header('Location: index.php');
}
else {$msg="Username/Password incorrect. Please try again!";}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Admin Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<?php include('config/css.php'); ?>
<?php include('config/favicon.php'); ?>
<?php include('config/js.php'); ?>
<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/r29/html5.min.js"></script>
<![endif]-->
</head>
<body>
<!--NAVIGATION BAR-->
<?php //include(D_TEMPLATE.'/navigation.php'); ?>
<div class="container">
<div class="col-lg-4 col-lg-offset-4">
<div class="panel panel-info">
<div class="panel-heading">
<h1 class="lato fs20"><strong>Login</strong></h1>
</div>
<div class="panel-body">
<?php echo $msg; ?>
<form role="form" method="post" action="login.php">
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" class="form-control" name="password">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
For the "$q" variable, you should use php sha1 function:
$q = "select * from users where email = '$_POST[email]' and password = '" . sha1($_POST[password]) . "'";
But as Fred-ii said you really shoud (have to) protect your variables before.
For example :
$_POST['email'] = mysqli_real_escape_string($_POST['email']);
It will protect your variable against SQL injection (https://php.net/manual/en/mysqli.real-escape-string.php)

my jquery mobile is not working with my php code

Below is my code(jquery mobile and php) I am trying to insert into the database and also echo the following message (pls fill all field and registration complete) that is if the user complete the field or not the following message show display but non of it is working with my jquery mobile code and it is working with my normal site how can I fix this I will appreciate it if you work on my code thank you
<?php
$db= “user”;
$connect = mysql_connect(“localhost“, “alluser”, “six4”)or die(“could not connect”);
Mysql_select_db($db) or die (“could not select database”);
If (isset($_POST['submit'])){
If(empty($_POST['name']) OR empty($_POST['email']) OR empty($_POST['add'])){
$msg = 'pls fill all field';
$name = ($_POST['name']);
$email = ($_POST['email']);
$address = ($_POST['add']);
mysql_query(“INSERT INTO people (Name, Email, Address”) VALUES ('$name, $email, $address')”) or die (mysql_error());
$msg='registration complete ';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<link rel="stylesheet" href="css/jquery.mobile-1.0a1.min.css" />
<script src="js/jquery-1.4.3.min.js"></script>
<script src="js/jquery.mobile-1.0a1.min.js"></script>
</head>
<body>
<div data-role="page">
<div data-role="header">
<h1>User</h1>
</div>
<div data-role="content">
<?php echo “$msg”; ?>
<form name=“form” action=“” method=“post”>
<label for=“name”>Name</label>
<input type=“text” name=“name” />
<label for=“email”>Email</label>
<input type=“text” name=“email” />
<label for=“address”>Address</label>
<input type=“text” name=“add” />
<input type=“submit” name=“submit” value=“Submit” />
</form>
</div>
<div data-role="footer">
<h4>Page Footer</h4>
</div>
</div>
</body>
</html>
Check your brace positions after your if statements. You check for empty values, but you don't alter the program flow in a meaningful way if you find them.
Also, replace your curly quotes with real quotes. And check for SQL injection. And double-check your MySQL call. You'll get an error from PHP before you'll ever get $msg echoed, based on the way things are written.

Categories