I'm trying to make a simple voting-function to our site. Something in it does not work.
if(isset($_POST['vote']))
{
if($_POST['rate'] == "rate_1")
{
$rate = 'rate_1';
$rate_opload = ++$rest['rate_1'];
}
if else($_POST['rate'] == "rate_2")
{
$rate = 'rate_2';
$rate_opload = ++$rest['rate_2'];
}
if else($_POST['rate'] == "rate_3")
{
$rate = 'rate_3';
$rate_opload = ++$rest['rate_3'];
}
if else($_POST['rate'] == "rate_4")
{
$rate = 'rate_4';
$rate_opload = ++$rest['rate_4'];
}
if else($_POST['rate'] == "rate_5")
{
$rate = 'rate_5';
$rate_opload = ++$rest['rate_5'];
}
$sql = "INSERT INTO kaffe ('{$rate}') VALUES ('{$rate_opload}')";
mysql_query($sql);
}
There are five different columns as you can see because we needed an average in an other part.
I don't know if it's necessary but here is the option-form
<form method=\"post\" id=\"vote\">
<select name=\"rate\">
<option value=\"rate_1\" >★</option>
<option value=\"rate_2\" >★★</option>
<option value=\"rate_3\" >★★★</option>
<option value=\"rate_4\">★★★★</option>
<option value=\"rate_5\">★★★★★</option>
</select>
<button type=\"submit\" form=\"vote\" value=\"vote\" class=\"fsSubmitButton\">Rösta</button>
First you forgot to put name="vote" into your html form
<form method=\"post\" id=\"vote\">
<select name=\"rate\">
<option value=\"rate_1\" >★</option>
<option value=\"rate_2\" >★★</option>
<option value=\"rate_3\" >★★★</option>
<option value=\"rate_4\">★★★★</option>
<option value=\"rate_5\">★★★★★</option>
</select>
<button type=\"submit\" name="vote" form=\"vote\" value=\"vote\" class=\"fsSubmitButton\">Rösta</button>
Second it's else if and not if else, your code can be much more compact, nowaday mysql function are deprecated use mysqli
$link = mysqli_connect("localhost", "my_user", "my_password", "world");// Connect to database using mysqli function since mysql function are deprecated
if(isset($_POST['vote']))
{
if($_POST['rate'] == 'rate_1' | $_POST['rate'] == 'rate_2' | $_POST['rate'] == 'rate_3' | $_POST['rate'] == 'rate_4' |$_POST['rate'] == 'rate_5'){
$rate = $_POST['rate'];
$rate_opload = ++$rest[$rate];
$sql = mysqli_prepare($link, "INSERT INTO kaffe ('{$rate}') VALUES (?)");
mysqli_stmt_bind_param($sql , $rate_opload);
mysqli_stmt_execute($sql);
}
}
Your
if(isset($_POST['vote']))
is not reached, you have to add name="vote" to your submit button
Related
Im trying to add the chosen values from my drop down menu into my database by using primary and foreign keys. Im trying to figure out how when the customer selects the drop down box option, the VALUE is entered into sql, which is the same number as room table primary. Would i somehow post the drop down box select id = rooID? Can anyone please help me with this.
Below is my makeabookingphp code:
<!DOCTYPE HTML>
<html><head><title>Make a Booking</title> </head>
<body>
<?php
//function to clean input but not validate type and content
function cleanInput($data) {
return htmlspecialchars(stripslashes(trim($data)));
}
//the data was sent using a formtherefore we use the $_POST instead of $_GET
//check if we are saving data first by checking if the submit button exists in the array
if (isset($_POST['submit']) and !empty($_POST['submit']) and ($_POST['submit'] == 'Book')) {
//if ($_SERVER["REQUEST_METHOD"] == "POST") { //alternative simpler POST test
include "config.php"; //load in any variables
$DBC = mysqli_connect("127.0.0.1", DBUSER, DBPASSWORD, DBDATABASE);
//prepare a query and send it to the server
$query = 'SELECT room.roomID, room.roomname, room.roomtype, booking.bookingID, booking.roomID, booking.roomname
FROM room
INNER JOIN booking
ON room.roomID = booking.roomID';
if (mysqli_connect_errno()) {
echo "Error: Unable to connect to MySQL. ".mysqli_connect_error() ;
exit; //stop processing the page further
};
//validate incoming data - only the first field is done for you in this example - rest is up to you do
$error = 0; //clear our error flag
$msg = 'Error: ';
if (isset($_POST['roomname']) and !empty($_POST['roomname']) and is_string($_POST['roomname'])) {
$fn = cleanInput($_POST['roomname']);
$roomname = (strlen($fn)>50)?substr($fn,1,50):$fn;
//check length and clip if too big
//we would also do context checking here for contents, etc
} else {
$error++; //bump the error flag
$msg .= 'Invalid'; //append eror message
$roomname = '';
}
$roomname = cleanInput($_POST['roomname']);
$checkindate = cleanInput($_POST['checkindate']);
$checkoutdate = cleanInput($_POST['checkoutdate']);
$contactnumber = cleanInput($_POST['contactnumber']);
$bookingextras = cleanInput($_POST['bookingextras']);
//save the customer data if the error flag is still clear
if ($error == 0) {
$query1 = "INSERT INTO booking (roomname, checkindate, checkoutdate, contactnumber, bookingextras) VALUES (?,?,?,?,?)";
$stmt = mysqli_prepare($DBC,$query1); //prepare the query
mysqli_stmt_bind_param($stmt,'sssss', $roomname, $checkindate, $checkoutdate,$contactnumber,$bookingextras);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo "<h2>Booking saved</h2>";
} else {
echo "<h2>$msg</h2>".PHP_EOL;
}
mysqli_close($DBC); //close the connection once done
}
?>
<h1>Make A Booking</h1>
<h2><a href='menu.php'>[Return to the main page]</a></h2>
<form method = "post" action = "processbooking.php">
<p>
<label for = "rooID">Room: (name, type, beds): </label>
<select id = "rooID" name = "rooID" required>
<option name = "" value = "" disabled selected>Select</option>
<option name = "1" value = "1">Kellie, S, 5</option>
<option name = "2" value = "2">Herman, D, 2</option>
<option name = "3" value = "3">Scarlett, D, 2</option>
<option name = "4" value = "4">Jelani, S, 5</option>
<option name = "5" value = "5">Sonya, S, 4</option>
<option name = "6" value = "6">Miranda, S, 2</option>
<option name = "7" value = "7">Helen, S, 2</option>
<option name = "8" value = "8">Octavia, D, 3</option>
<option name = "9" value = "9">Bernard, D, 5</option>
<option name = "10" value = "10">Dacey, D, 1</option>
</select>
</p>
<p>
<label for="checkindate">Check in date: </label>
<input type="date" name="checkindate"required>
</p>
<p>
<label for="checkout">Check out date: </label>
<input type="date" name="checkoutdate"required>
</p>
<p>
<label for="contactnumber">Contact number: </label>
<input type="tel" name="contactnumber" required>
</p>
<p>
<label for="bookingextras">Booking extras: </label>
<input type="text" name="bookingextras" size="100" minlength="5" maxlength="200" required>
</p>
<input type="submit" name="submit" value="Book">
[Cancel]
</form>
</body>
</html>
Room table:
roomID (PK)
roomname
description
roomtype
beds
Booking table:
bookingID (PK)
roomname
checkindate
checkoutdate
contactnumber
bookingextras
roomID (FK)
I've rewritten your code - hope it helps
<?php
//function to clean input but not validate type and content
function cleanInput($data) {
return htmlspecialchars(stripslashes(trim($data)));
}
// STEP 1 -test if form has been submitted
if (isset($_POST['submit']) && ($_POST['submit'] == 'Book')) {
// STEP 2. process the inputs
// get inputs - clean or set a default if not supplied
$roomID = isset( $_POST['rooID'] ) ? cleanInput($_POST['rooID']) : -1;
$checkindate = isset( $_POST['checkindate'] ) ? cleanInput($_POST['checkindate']) : "";
$checkoutdate = isset( $_POST['checkoutdate'] ) ? cleanInput($_POST['checkoutdate']) : "";
$contactnumber = isset( $_POST['contactnumber'] ) ? cleanInput($_POST['contactnumber']) : "";
$bookingextras = isset( $_POST['bookingextras'] ) ? cleanInput($_POST['bookingextras']) : "";
// STEP 3 validate/clean the inputs (don't trust anything coming in)
// validate all the inputs according to business rules
$error = 0;
$errMsg = [];
if( roomID == -1 ) {
$error++;
$errMsg[] = "Room not selected";
}
// do all other inputs
// proceed if no errors
if( $error != 0 ) {
// STEP 4 connect to the database
// connect to the database
include "config.php"; //load in any variables
$DBC = mysqli_connect("127.0.0.1", DBUSER, DBPASSWORD, DBDATABASE);
if (mysqli_connect_errno()) {
echo "Error: Unable to connect to MySQL. ".mysqli_connect_error() ;
exit; //stop processing the page further
};
// STEP 5 check if the roomID is valid
// if roomID is valid then continue
$query = "SELECT roomID FROM roomTable WHERE roomID=".$roomID;
$result = $DBC->query( $query ); // ???? check the syntax of this line
if( $result ) { // something returned ???? check syntax
// STEP 5 update the relevant table(s)
$query1 = "INSERT INTO booking (roomID, checkindate, checkoutdate, contactnumber, bookingextras) VALUES (?,?,?,?,?)";
$stmt = mysqli_prepare($DBC,$query1); //prepare the query
mysqli_stmt_bind_param($stmt,'issss', $roomID, $checkindate, $checkoutdate,$contactnumber,$bookingextras);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo "<h2>Booking saved</h2>";
}
} else {
// STEP 3.1 show user messages of what went wrong
echo $errMsg;
}
mysqli_close($DBC); //close the connection once done
}
?>
I have developed a function which runs a query and then uses the resulting variables in a logic in another file. I have used global variables to achieve this. I have read global variables are to be avoided, is there another way to write this function to avoid use of global variables.
File 1 (Function File)
<?php
function usertype()
{
include "../classes/sessionstart.php";
include "../config/dbconnect.php";
$user_id = $_SESSION['user_id'];
$select = $con->prepare("SELECT user_usertype, user_gender FROM tbl_user WHERE user_id = $user_id");
$select->setFetchMode(PDO::FETCH_ASSOC);
$select->execute();
while($data=$select->fetch()){
$GLOBALS['gender'] = $data['user_gender'];
$GLOBALS['usertype'] = $data['user_usertype'];
}
}
?>
File 2 (File Using the Function File)
<?php
usertype();
?>
<div>
<select class="searchpropertyinputs" name="user_usertype" id="user_usertype">
<?php if ($gender == "Male" && $usertype != "Marriage Bureau") { ?> <option value="Bride">Bride</option> <?php } ?>
<?php if ($gender == "Female" && $usertype != "Marriage Bureau") { ?> <option value="Groom">Groom</option> <?php } ?>
<?php if ($usertype == "Marriage Bureau") { ?>
<option value="" hidden>Bride or Groom</option>
<option value="Bride">Bride</option>
<option value="Groom">Groom</option>
<?php } ?>
</select>
</div>
You should return the value from the function:
Updated code, also fixed prepared query, and set an alias for the return columns.
<?php
function usertype()
{
include_once "../classes/sessionstart.php";
include_once "../config/dbconnect.php";
$select = $con->prepare("
SELECT user_usertype as `type`,
user_gender as `gender`
FROM tbl_user
WHERE user_id = :user_id LIMIT 1
");
$select->bindValue(':user_id', (int) $_SESSION['user_id'], PDO::PARAM_INT);
$select->execute();
return $select->fetch(PDO::FETCH_ASSOC);
}
?>
.
<?php
$usertype = usertype();
?>
<div>
<select class="searchpropertyinputs" name="user_usertype" id="user_usertype">
<?php if ($usertype['gender'] == "Male" && $usertype['type'] != "Marriage Bureau") { ?> <option value="Bride">Bride</option> <?php } ?>
<?php if ($usertype['gender'] == "Female" && $usertype['type'] != "Marriage Bureau") { ?> <option value="Groom">Groom</option> <?php } ?>
<?php if ($usertype['type'] == "Marriage Bureau") { ?>
<option value="" hidden>Bride or Groom</option>
<option value="Bride">Bride</option>
<option value="Groom">Groom</option>
<?php } ?>
</select>
</div>
You may also want to move out the includes to connect, session start, or you will have issues for future functions. So that should most likely lead you on to grouping functions into a user class, for example:
<?php
include_once "../classes/sessionstart.php";
include_once "../config/dbconnect.php";
class User {
public function __construct(PDO $con)
{
$this->con = $con;
}
public function type($user_id = 0)
{
$select = $this->con->prepare("
SELECT user_usertype as `type`,
user_gender as `gender`
FROM tbl_user
WHERE user_id = :user_id LIMIT 1
");
$select->bindValue(':user_id', (int) $user_id, PDO::PARAM_INT);
$select->execute();
return $select->fetch(PDO::FETCH_ASSOC);
}
//...
}
$user = new User($con);
$usertype = $user->type($_SESSION['user_id']);
?>
I need to store a hexadecimal value (values posted from my <options>) to my mysql database without transforming it (stay as is in string form) so that I can compare that value to my select options in string form. I've tried a lot of things, like base_convert(), (string), hex2bin(), but unfortunately. I don't know how to do this.
The image shows the stored value.
This is what I have done so far.
login.php:
$q = mysqli_query($con, "select * from users where email = '$email' and password = '$password'");
if (mysqli_num_rows($q) == 0)
{
$response['message'] = "Account not found.";
}
else
{
$_SESSION['user_currency'] = (string)$f['user_currency'];
}
dasboard.php:
<form id="form_setting_currency">
<select name="select_currency_symbol" class="form-control">
<option value="$" <?php echo $_SESSION['user_currency'] == "$" ? "selected" : ""; ?> >$ Dollar</option>
<option value="¢" <?php echo $_SESSION['user_currency'] == "¢" ? "selected" : ""; ?> >¢ Cent</option>
<option value="£" <?php echo $_SESSION['user_currency'] == "£" ? "selected" : ""; ?> >£ Pound Sterling</option>
<option value="¥" <?php echo $_SESSION['user_currency'] == "¥" ? "selected" : ""; ?> >¥ Yen</option>
</select>
</form>
SUBMIT_change_currency.php
<?php
include "includes/connection.php";
require_once("includes/encryption.class.php");
$response['success'] = false;
$response['message'] = "An error has occurred.";
if(isset($_POST['select_currency_symbol']) && trim($_POST['select_currency_symbol']) != "")
{
$currencyIcon = mysqli_real_escape_string($con,$_POST['select_currency_symbol']);
// $currencyIcon = mysqli_real_escape_string($con,hex2bin($_POST['select_currency_symbol']));
// $currencyIcon = mysqli_real_escape_string($con,(string)$_POST['select_currency_symbol']);
$query ="UPDATE users SET user_currency = '$currencyIcon' WHERE user_id = $_SESSION[user_id]";
mysqli_query($con,$query);
if(mysqli_affected_rows($con)>0)
{
$response['success'] = true;
$response['message'] = "Successfully changed currency symbol.";
$_SESSION['user_currency'] = (string)$currencyIcon;
}
else
{
$response['message'] = "You have not made changes.";
}
}
die(json_encode($response));
?> `
You need to print it with htmlspecialchars() in the value, so it becomes & amp;#x24
So I'm trying my hand at creating php methods from scratch. My classes aren't exactly classes yet, I'm still working on that. Anyway, my issue's I can't seem to get the values I expect from my database. Here's a snippet of my code:
file1.php
<?php function dbConnect() {
$connection = mysqli_connect("localhost", "music_root", "", "music");
if($connection->connect_error) {
return null;
}
return $connection;}
function getCategory() {
$cn = dbConnect();
if($cn == null) {
echo "Failed to connect to database.";
} else {
$fetchQuery = mysqli_query($cn, "SELECT * FROM tbl1 ORDER BY 'Name'") or die(mysqli_error($cn));
if(mysqli_num_rows($fetchQuery) > 0) {
while($item = mysqli_fetch_array($fetchQuery)) {
return $item["Name"];
}
}
}} ?>
Here's the snippet of how I call the above method in file2.php
<?php ini_set("display_errors", 1);
include_once("file1.php");
$con = dbConnect();
$updateStat = false; ?>
<div>
<label>Genre</label>
<select id="genre" name="genre" value="Please select genre">
<option value="<?php $con->getCategory() ?>"></option>
</select>
</div>
I've tried printing a message at the start of the method to see if the it's being called but the message did not print either so I was wondering, what am I possibly missing here?
I think you have serveral mistakes in your code ... i guess, you don't use OOP (classes) so i modfiy a example which should work .. .if not, please post error messages
file1.php
function getCategory($cn) {
$out = array();
if($cn == null) {
echo "Failed to connect to database.";
} else {
$fetchQuery = mysqli_query($cn, "SELECT * FROM tbl1 ORDER BY 'Name'") or die(mysqli_error($cn));
if(mysqli_num_rows($fetchQuery) > 0) {
while($item = mysqli_fetch_array($fetchQuery)) {
$out[] = $item["Name"];
}
}
return $out;
}
}
fil2.php
<?php
ini_set("display_errors", 1);
require_once("file1.php");
$con = dbConnect();
$updateStat = false;
$res = getCategory($con);
?>
<div>
<label>Genre</label>
<select id="genre" name="genre" value="Please select genre">
<?php
foreach($res as $cat):
?>
<option value="<?php echo $cat ?>"><?php echo $cat ?></option>
<?php endforeach;?>
</select>
I'm trying to create a system that when i submit the form, after the page refresh it should show the new values that i get from the database. The values work well when they go into the databse but they dont show after submited, only when i refresh again. Thanks for helping
<?php
include("connect.php");
$query = "SELECT * FROM `laliga`";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
$id = $row['id'];
$home = $row['home'];
$away = $row['away'];
$win = $row['win'];
$draw = $row['draw'];
$lose = $row['lose'];
}
echo "<h2>La Liga</h2>";
echo $home, " - ", $away;
if (isset($_POST) && $_POST['laliga'] == 1){
$select = mysql_real_escape_string($_POST['laliga']);
$select = $win + $select;
mysql_query("UPDATE laliga SET win='$select'");
}else if (isset($_POST) && $_POST['laliga'] == 'X'){
$select = mysql_real_escape_string($_POST['laliga']);
$select = '1';
$select = $draw + $select;
mysql_query("UPDATE laliga SET draw='$select'");
}else if (isset($_POST) && $_POST['laliga'] == 2){
$select = mysql_real_escape_string($_POST['laliga']);
$select = '1';
$select = $lose + $select;
mysql_query("UPDATE laliga SET lose='$select'");
}
header('Location: ../laliga.php');
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="radio" name="laliga" value="1">1
<input type="radio" name="laliga" value="X">X
<input type="radio" name="laliga" value="2">2
<input type="submit" name="submit" value="Submit"/>
</form>
<br/>
<?php
echo $home, " -> ", $win;
echo "<br/>Barazim -> ", $draw,"<br/>";
echo $away, " -> ", $lose;
?>
You should handle all of the post data at the top of the PHP file, whilst the header function will solve your problem it's a silly and inefficient way of approaching it. by handling the post data and updating the database first, by the time you query the database the data is there! at the moment you are trying to find the data and then adding it. does this make sense?
Good luck!
Add:
header('Location: <mypage.php>');
After mysql_query.