I'm making a web application, and I'm having trouble figuring out how to stop the PHP from making a query to my database every time the page is reloaded.
Basically when the form is submitted I want the PHP to make a query to the database adding the variables, however, because it has saved those values in the $_POST, it's making a query every time I refresh with those same values.
I want it to make the query, then perhaps unset the $_POST values or something so that it doesn't satisfy the if condition, and in turn stops it from querying the database with repeat values when the submit button hasn't updated them with new values.
Sorry if that's convoluted I'm trying to explain my problem the best I can.
Here is the PHP
<?php
//Require login gile -- Fatal error if not found
require_once('login.php');
require_once('app.html');
//Connect w/ MySQL database [login variables]
$con = new mysqli($hn, $un, $pw, $db);
//If connection error -> kill application and display error
if ($con->connect_error) die('Connect Error (' . $con->connect_errno . ') '. $con->connect_error);
//If both goal and difficulty are set
if (!empty($_POST['goal']) && !empty($_POST['difficulty'])) {
$goal = get_post($con, 'goal');
$difficulty = get_post($con, 'difficulty');
$query = "INSERT INTO items VALUES" . "('$goal', 1, '$difficulty', NULL)";
$result = $con->query($query);
if(!$result) echo "INSERT failed: $query<br>" . $con->error . "<br><br>";
}
unset($_POST['goal']);
unset($_POST['difficulty']);
//close connection
$con->close();
function get_post($conn, $var) {
return $conn->real_escape_string($_POST[$var]);
}
?>
html
<!DOCTYPE html>
<html>
<head>
<title>Testing</title>
<!--Page Style-->
<link type="text/css" rel="stylesheet" href="Style.css">
<!--jQuery-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<!--RateYo | http://prrashi.github.io/rateYo/-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/rateYo/2.0.1/jquery.rateyo.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/rateYo/2.0.1/jquery.rateyo.min.js"></script>
</head>
<body>
<div id="parent1">
<form id="goalForm" method="post" action="PHP.php">
<!--Goal Value-->
<input id="goalName" type="text" name="goal" maxlength="150" placeholder="Type your goal here!">
<!--Star Rating-->
<div id="rateYo"></div><br>
<!--Value from stars to be submitted-->
<input id="dif" type="hidden" name="difficulty">
<input class="but1" id="firstSubmit" type="button" value="Submit">
<input class="but1" id="submitton" type="submit" style="display:none" value="Difficulty?">
</form>
</div>
<script>
$("#goalName").val("");
//First Submit Onclick
$("#firstSubmit").click(function() {
if($("#goalName").val() == "") {
alert("Please insert a value.");
}
else {
$("#goalName").fadeOut("slow" , function() {
$("#rateYo").rateYo({
numStars: 10,
rating: 0,
fullStar: true,
starWidth: "70px",
ratedFill: "#E74C3C",
maxValue: 10
});
$("#rateYo").fadeIn("slow");
});
$(this).hide();
$("#submitton").show();
}
});
//Star Submit
$("#goalForm").submit(function() {
var $rateYo = $("#rateYo").rateYo();
var rating = $rateYo.rateYo("rating");
if($("#goalName").val() == "") {
alert("Please insert a value.");
return false;
}
else if(rating == 0) {
alert("Please set a difficulty level.");
return false;
}
else {
$("#dif").val(rating);
}
});
</script>
Try it plz
<?php
//Require login gile -- Fatal error if not found
require_once('login.php');
require_once('app.html');
//Connect w/ MySQL database [login variables]
$con = new mysqli($hn, $un, $pw, $db);
//If connection error -> kill application and display error
if ($con->connect_error) die('Connect Error (' . $con->connect_errno . ') '. $con->connect_error);
//If both goal and difficulty are set
if (!empty($_POST['goal']) && !empty($_POST['difficulty'])) {
$goal = get_post($con, 'goal');
$difficulty = get_post($con, 'difficulty');
$query = "INSERT INTO items VALUES" . "('$goal', 1, '$difficulty', NULL)";
$result = $con->query($query);
if(!$result) echo "INSERT failed: $query<br>" . $con->error . "<br><br>";
//You can write samepage name in location as window.location='abc.php'
echo "<script>window.location=''</script>";
}
//close connection
$con->close();
function get_post($conn, $var) {
return $conn->real_escape_string($_POST[$var]);
}
?>
Related
I'm currently trying to set up a chat. It works fine on its own, however when I try and get the username from another database for a log in system I have instead of having people choose a username then and there, the system breaks down and doesn't upload the messages to the database. I get no errors.
Here's the code:
<?php
$mysqli = new mysqli("localhost", "root", "", "forum");
$mysqli2 = new mysqli("localhost", "root", "", "login");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (isset($_GET['message']) && isset($_GET['username'])) {
$user=$mysqli2->real_escape_string($_GET['username']);
$message=$mysqli->real_escape_string($_GET['message']);
$date=date('Y-m-d H:i:s');
$sql="INSERT INTO forum(id, user, message, date) VALUES(0,'$user','$message','$date')";
$mysqli->query($sql);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Forum</title>
</head>
<body>
<h2>Forum Messages:</h2>
<?php
$sql = "SELECT * FROM forum";
$result = $mysqli->query($sql);
$sql2 = "SELECT * FROM users";
$result2 = $mysqli2->query($sql2);
while($row = $result->fetch_assoc() && $row2 = $result2->fetch_assoc()) {
echo $row2['username'].', '.$row['date'].' <br>';
echo $row['message'].'<br>';
echo '------------------------ <br>';
}
?>
<form method="get" action="forum.php">
<p>Message:<br>
<label for="message"></label>
<textarea name="message" id="message" cols="45" rows="5"></textarea>
</p>
<p>
<input type="submit" name="submit" id="submit" value="Post message">
</p>
</form>
</body>
</html>
Anyone got an idea of why its not working?
You get no errors because you're not checking for any. It's probable that the insert is failing. Your call to query() will return FALSE in this case, so you'll need to check for that.
$sql = "INSERT INTO forum(user, message, date) VALUES('$user','$message','$date')";
if ($mysqli->query($sql) === false) {
throw new Exception('Error performing insert: ' . $mysqli->error);
}
Also note, in this following code, you're not aborting, you just print the error message and then continue on with the script anyway:
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
Change the echo to a throw so the script stops.
And ideally, you want to use prepared statements instead of real_escape_string(). Something like this:
$stmt = $mysqli->prepare('INSERT INTO forum(user, message, date) VALUES(?, ?, ?)');
if ($stmt === false) {
// prepare failed
}
$stmt->bind_param('sss', $_GET['username'], $_GET['message'], date('Y-m-d H:i:s'));
if ($stmt->execute() === false) {
// exec failed
}
I am trying to set the value to be displayed in a SELECT list using php scripts.
What I have done is create an input html page (MatchSelect.php) which shows two select boxes and a submit button.
On pressing the submit button a new new php file is called (MatchSelectResult.php) which is as follows;
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Seniors Inter-Club Match Management</title>
<link rel="stylesheet" href="MainBody.css">
<link href="dropDown.css?v=1.1" rel="stylesheet" >
<?PHP require '../../configure.php';
include "Main_PHP_Code.php" ;
?>
</head>
<body>
<?PHP include "MatchPopulate.php"; ?>
<div class="container">
<?PHP include "menu.txt" ?>
<div class="content">
<div>
<h1>Team Selection</h1>
<form name="matchSelect" method="POST" action="MatchUpdate.php">
<p>
<select id = "Venue" name= "Venue" >
<option disabled selected value> -- select an option -- </option>
<option value="Away">Away</option>
<option value="Home">Home</option>
</select>
match against
<select id ="Opponents" name ="Opponents">
<?php
Global $OpponentName;
$oop = $OpponentName;
opponent_load('$oop');
?>
</select>
etc.
the function opponent_load() is contained within the "Main_PHP_Code.php" code and is as follows;
function opponent_load($oppon){
Global $OpponentName;
$db_handle = mysqli_connect(DB_SERVER, DB_USER, DB_PASS );
$database = "matchmanagementdb";
$db_found = mysqli_select_db($db_handle, $database);
if ($db_found) {
$SQL = "SELECT * FROM opponentsdb";
$result = mysqli_query($db_handle, $SQL);
while ( $db_field = mysqli_fetch_assoc($result) ) {
$uName = $db_field['Opponents'];
if ($uName == $oppon)
{
$selected = 'selected="selected"';
}
else
{
$selected = '';
}
echo "<option value='$uName' $selected> $uName </option>";
}
}
else {
print "Database NOT Found ";
}
mysqli_close($db_handle);
}
The "MatchPopulate.php" code in the HEAD section is used to search the mySQL database using the two values from MatchSelect.php page. If the data is found, then the global variable $OpponentName is defined. The code is thus;
<?php
Global $OpponentName;
//require '../../configure.php';
$uOpponentName = $_POST['Opponents'];
$uVenue = $_POST['Venue'];
//$db_handle = mysqli_connect(DB_SERVER, DB_USER, DB_PASS );
$database = "matchmanagementdb";
$conn = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// check to see if Match (Opponents + Venue)already in the database, if so, retrieve data or add match to database
$SQL = "SELECT * FROM teamselect WHERE Opponents = '$uOpponentName' AND Venue = '$uVenue'";
$result = $conn->query($SQL);
//if $result->num_rows >0 then retrieve data ELSE add match to database
if (!$result){
print "Error selecting record: " . $sql . "<br>" . $conn->error;
} else {
if ($result->num_rows >0) {
while($row = $result->fetch_assoc()) {
$OpponentName = $row['Opponents'];
}
} else {
$sql = "INSERT INTO teamselect (Opponents, Venue) VALUES ('$uOpponentName', '$uVenue')";
if ($conn->query($sql) === TRUE) {
} else {
print "Error adding record: " . $sql . "<br>" . $conn->error;
}
}
}
$conn->close();
?>
The code stops when it tries to populate the Opponents Select box on MatchSelectResult.php. Any help to solve this would be appreciated.
I have solved the problem by opening a session and using $_SESSION["Opponents"] to pass the variable around the scripts.
Also changed opponent_load('$oop') to opponent_load($oop).
I am working on a test login-check with PHP/HTML and MySQL. I got it working great; it successfully connects to the database, it can grab my database values and save them in a variable, etc., but I ran into one slight problem.
I'm using two PHP pages to do the check. The login.php page, which only contains the forum, and the welcome.php page, which does the database connecting. When I ran a test page to just have it echo the database info, it printed out right (testUser, testEmail#email.com, testPassword, 1/1/1900). So when I tried to run my login-authentication check, it just says 'Unknown user!' twice, even when I try the usernames 'usr', 'testUser', and 'testUser2' (I made two tables, and the second one is the same with 2 added to the end). Here's my code.
<html>
<head>
<?php
$title = ucfirst(basename($_SERVER['PHP_SELF'], ".php"));
echo "<title>$title</title>";
?>
</head>
<body>
<form name="form" accept-charset="utf-8" action="welcome.php" method="post">
<span class="header">Username</span><input type="text" name="usr" value="usr"></input><br>
<span class="header">Password</span><input type="text" name="pass" value="pass"></input>
<input type="submit">
</form>
</body>
</html>
<?php
$servername = removed;
$username = removed;
$password = removed;
$dbname = removed;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ID, USER, PASSWORD FROM usrdatabase";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
// the given info from the form
$usrUser = $_POST["usr"];
$usrPass = $_POST["pass"];
// convert the findings to uppercase to get rid of sensitivity
if (strtoupper($usrUsr) == strtoupper($row["USER"]) && strtoupper($usrPass) == strtoupper($row["PASSWORD"])) {
echo "Welcome $usrUser!<br>Your login was successful! ?>";
}
elseif (strtoupper($usrUsr) == strtoupper($row["USER"]) && strtoupper($usrPass) != strtoupper($row["PASSWORD"])) {
echo "Login failed as $usrUser!";
}
else {
echo "Unknown user!";
}
}
} else {
echo "0 results";
}
$conn->close();
?>
This always produces a 'Unknown user!' Is there something wrong with my check? I want it to go through each user in the database to check the info with each existing user.
Change
strtoupper($usrUsr) == strtoupper($row["USER"])
To
strtoupper($usrUser) == strtoupper($row["USER"])
Fetch single user from the database by using the username since they are unique for each user.
$sql = "SELECT ID, USER, PASSWORD FROM usrdatabase WHERE USER = '" . mysqli_real_escape_string($_POST['usr']) . "' AND PASSWORD = '" . mysqli_real_escape_string($_POST['pass']) . "'";
hey i see your if else contains $usrUsr shoudn't it be $usrUser ? (forgot the e)
I was trying to make a php page that would display a MySQL search engine, and itworked on one server: however, on that server crashed and I was forced to reboot it. Even when I'm using the same code, the search engine no longer works - my code is as follows:
<html>
<head>
<meta charset="UTF-8">
<title>Search Engine Test</title>
<h1>Gromax</h1>
</head>
<body>
<form action="search1.php" method="post">
<input type="text" name="keyword">
<input type="submit" name="search" value="Search">
<br>
<br>
</form>
<script language="php">
// Create a database connection
error_reporting(0);
$connection = mysql_connect("localhost", "$ mysql -u anonymous", "");
if (!$connection) {
die("Please reload page. Database connection failed: " . mysql_error());
}
// Select a databse to use
$db_select = mysql_select_db("test", $connection);
if (!$db_select) {
die("Please reload page. Database selection failed: " . mysql_error());
}
// Search Engine
// Only execute when button is pressed
if (isset($_POST['keyword'])) {
// Filter
$keyword = trim($_POST['keyword']);
// Select statement
$search = "SELECT Price FROM table_1 WHERE Model = '$keyword'";
// Display
$result = mysql_query($search) or die('query did not work');
while ($result_array = mysql_fetch_array($result)) {
$arrlength=count($result_array);
for($x=0;$x+1<$arrlength;$x++){
echo "Price: " . $result_array[$x];
echo "<br>";
}
}
}
?>
</script>
</body>
</html>
Any help would be appreciated.
I'm pretty sure you have an error in your query or your Database connection. Try commenting the line:
// error_reporting(0);
and see what error you get...
Try to use a format like this to determine what is going wrong in your select query:
<?php
$sql = "
SELECT
Price
FROM
table_1
WHERE
Model = '".$keyword."'
";
if(!$res = mysql_query($sql))
{
trigger_error(mysql_error().'<br />In query: '.$sql);
}
elseif(mysql_num_rows($res) == 0)
{
echo 'Geen resultaten gevonden';
}
else
{
while($row = mysql_fetch_assoc($res))
{
echo $row['voornaam'].'<br />';
}
}
?>
I've created a webpage which uses JQuery to redirect the content of a form to another webpage using PHP to connect to a database to find some content and put it back on the first page.
Eveything works great (thanks to the help of followers of stack overflow :-) ) but now I'd like the following : I'm asking for the postal code of a city, if I'm lucky this postal code is unique (only one city has it) but it also happens that a postal code is the same for several cities so I'd like in that case to display a listbox for the user to choose his/her city.
Does someone has an idea of how to do this ?
my code :
home.html
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form action="/" id="myform">
<input type="text" name="postal_code" id="postal_code" placeholder="Search..." />
<input type="submit" value="Search" />
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>
<script>
$('#myform').submit(function() {
var url = 'target.php';
var postal_code = $('#postal_code').val();
$.post( url, { postal_code: postal_code },
function( data ) {
$( "#result" ).empty().append( data );
}
);
return false;
});
target.php
<?php
try
{
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$bdd = new PDO('mysql:host=localhost;dbname=mydatabase', 'root', '', $pdo_options);
$response = $bdd->prepare('SELECT city FROM city_list where postal_code = ?');
$response->execute(array($_POST['postal_code']));
echo '<ul>';
while ($data = $response->fetch())
{
?>
<br/>The city you entered the postal code is : <?php echo $data['city'];
}
$response->closeCursor();
}
catch (Exception $e)
{
die('Error : ' . $e->getMessage());
}
?>
EDIT:
This is the code ok for my needs. I'd only to make some very minor changes from Jules' code to make it ok (for an unknow reason his answer worked perfectly for him but not for me :-) )
<?php
try {
//Get the postal code:
$postcode = $_POST['code_postal'];
//Make MySQL connection
mysql_connect("localhost", "root", "") or die (mysql_error());
//Select the database
mysql_select_db("site_artisans_amélioré");
//Do your query based on the postcode...
$query = "SELECT ville FROM liste_communes_code_postaux where code_postal = '" . mysql_real_escape_string($postcode) . "'";
//Return the response in a variable
$data = mysql_query($query) or die (mysql_error());
//echo "Num rows: " . mysql_num_rows($data);
//Check how many rows the query returned. If more than 1 that means several cities
//exist for one postcode, so you should show a listbox.
//If not, just return the ville name
if (mysql_num_rows($data) > 1) { ?>
<select name="cities">
<?php while ($row = mysql_fetch_assoc($data)) { ?>
<option value="<?php echo $row['ville']?>"><?php echo $row['ville']?></option>
<?php } ?>
</select>
<?php }
else {
$row = mysql_fetch_assoc($data);
echo $row['ville'];
}
}
catch (Exception $e) {
die("Error : " . $e->getMessage());
}
?>
I am not sure which library you are using for your Database queries, so I'll do it in Pseudo-code and mysql_query..
target.php
<?php
try {
//Get the postal code:
$postcode = $_POST['postal_code'];
//Make MySQL connection
mysql_connect("localhost", "username", "password") or die (mysql_error());
//Select the database
mysql_select_db("mydatabase");
//Do your query based on the postcode...
$query = "SELECT city FROM city_list where postal_code = '" . mysql_real_escape_string($postcode) . "'";
//Return the response in a variable
$data = mysql_query($query);
//Check how many rows the query returned. If more than 1 that means several cities
//exist for one postcode, so you should show a listbox.
//If not, just return the city name
if (mysql_num_rows($data) > 1) { ?>
<select name="cities" multiple="multiple">
<? while ($row = mysql_fetch_assoc($data)) { ?>
<option value="<?=$row['city']?>"><?=$row['city']?></option>
<? } ?>
</select>
<? }
else {
$row = mysql_fetch_assoc($data);
echo $row['city'];
}
}
catch (Exception $e) {
die("Error : " . $e->getMessage());
}
?>
I hope you catch my drift and you can complete it yourself.