how to validate and limit dynamic radio button inside a while loop - php

I tried to generate radio buttons dynamically from my database, but I am stuck where I need to limit (check if the user selected at least 5 groups(5 different games) of the generated button before submission into the database.
<?php while($row = mysql_fetch_array($query)) : ?>
<?php
$home_team = $row\['home_team'\];
$away_team = $row\['away_team'\];
$game_id = $row\['game_id'\];
$team_joined = $home_team.' VS '.$away_team;
$teams = $home_team.'vs'.$away_team;
$match_day = #$row\['match_day'\];
$match_time = #$row\['match_time'\];
date_default_timezone_set('Africa/Lagos');
$time = date('l, jS F h:iA');
?>
<?php
if (isset($_POST\['submit'\])) {
$amount = mysql_real_escape_string($_POST\['amount'\]);
$games = #$_POST\[''.$game_id.''\];
$countGames = count($games);
echo $countGames;
/* if ($countGames < 3) {
$errorfill = "please selecet 3 games";
} else { */
if ($amount) {
foreach ($games as $game) {
$gameValue = $game;
if ($amount < $bank_verify) {
$money_left = $bank_verify - $amount;
$deduct_query = mysql_query("UPDATE bank SET money_unit='$money_left' WHERE username='$username' ");
$query_start_game = mysql_query("INSERT INTO bet10_players VALUES('', '$username', '$amount',
'$gameValue', '$team_joined', '$game_id','$time', '$pin', '$match_day', '$match_time')") or die(mysql_error());
header("Location: print.php?pin=$pin&time=$time");
} else {
$errorbank = "SORRY!!! You do not have enough units to stake this bet";
}
}
} else {
$errorfill = "You have not entered any amount";
}
//}
}
?>
<form role="form" action="#" method="post">
<h5><?php echo $team_joined; ?></h5>
<h5><?php echo '<span style="color:#f0ad4e;">' . $match_day . ', ' . $match_time . '</span>'; ?></h5>
<label><input type="radio" name="<?php echo '' . $game_id . '\[' . $game_id . '\]'; ?>" value="<?php echo $home_team; ?>">Home</label>
<label><input type="radio" name="<?php echo '' . $game_id . '\[' . $game_id . '\]'; ?>" value="Draw ">Draw</label>
<label><input type="radio" name="<?php echo '' . $game_id . '\[' . $game_id . '\]'; ?>" value="<?php echo $away_team; ?>">Away</label>
<hr>
<?php endwhile; ?>
<div class="form-group">
<input type="text" name="amount" class="form-control" placeholder="Enter your amount here">
<input type="submit" name="submit" value="submit" class="btn btn-danger" style="margin-bottom: 10px;">
This is the link to the image of what I intend to achieve with these code https://i.stack.imgur.com/Xif8M.png

Because there are a lot of issues just with what you have, I can not actually "fix" what you have in good conscience. The mysql_* library is deprecated (removed in >= PHP7) and you are escaping a bunch of things you don't need to, as I noted. Also, as noted, using # to silence warnings is not a good idea, you will want to just fix them. If I were to do this, I would have a series of classes that I would create. I would also do an .htaccess or web.config (Windows) to force everything through the index page, but I suspect from your script you have individual pages, so I will go on that notion:
First off, I would probably create a base app that had some simple, helpful features.
/vendors/App.php
<?php
class App
{
# Easily return post values even if they don't exist without drawing errors
public function getPost($key=false)
{
if(!empty($key))
return (isset($_POST[$key]))? $_POST[$key] : false;
return $_POST;
}
# Easily return session values even if they don't exist without drawing errors
public function getSession($key=false)
{
if(!empty($key))
return (isset($_SESSION[$key]))? $_SESSION[$key] : false;
return $_SESSION;
}
# Used to render pages
public function render($file)
{
ob_start();
include($file);
$data = ob_get_contents();
ob_end_clean();
return $data;
}
}
/vendors/Game.php
If you create a base Game class, you will better be able to control Game-related base features
<?php
class Game extends App
{
protected $games = array();
protected $errors = array();
protected $con;
# Inject the database
public function __construct(\PDO $con)
{
$this->con = $con;
}
# Fetch a list (or just one) game
public function gameList($game_id = false)
{
$where = (!empty($game_id))? " WHERE game_id = '{$game_id}'" : "";
$this->games = array();
$query = $this->con->query("SELECT * FROM games{$where}");
while($result = $query->fetch(PDO::FETCH_ASSOC)) {
$this->games[] = $result;
}
return $this;
}
# Send back the games if stored
public function getGames($first = false)
{
# If you you only need one row returned
if($first)
return (isset($this->games[0]))? $this->games[0] : false;
# Return entire list
return $this->games;
}
# Count how many are currently stored
public function getCount()
{
return count($this->games);
}
}
/vendors/Game/Observer.php
If you create a base Game Observer class, you will better be able to control listeners and processing of requests.
<?php
namespace Game;
class Observer extends \Game
{
protected $time;
# This is a general listener method, listens for the post
# It needs work, I don't know where you are getting some of these
# variables from...I am injecting for example-sake
public function listen($bank_verify,$pin,$min=5)
{
# Listen for the submission
if(empty($this->getPost('submit')))
return $this;
elseif(empty($this->getSession('username')))
return $this;
# Fetch the post values, fitler empty
$REQUEST = array_filter($this->getPost('game'));
# See if there are at least 5 submitted
if(count($REQUEST) < $min) {
$this->errors[] = 'You must have at least '.$min.' selected';
return $this;
}
foreach($REQUEST as $id => $value) {
$this->games[$id] = $value;
}
$username = $this->getSession('username');
$amount = $this->getPost('amount');
if($amount < $bank_verify) {
$money_left = $bank_verify - $amount;
$this->updateAccount($money_left,$username);
foreach($this->games as $id => $value) {
$query_start_game = $this->con->prepare("INSERT INTO bet10_players VALUES('',?,?,?,?,?,?,?,?,?)");
$query_start_game->execute(array(
$username,
$amount,
$gameValue,
$team_joined,
$game_id,
$time,
$pin,
$match_day,
$match_time
));
}
}
else {
$this->errors[] = 'Not enough money.';
return $this;
}
header("Location: print.php?pin=$pin&time=$time");
exit;
}
# This sets the timezone (just once)
public function setTime($tz = 'Africa/Lagos')
{
date_default_timezone_set($tz);
$this->time = date('l, jS F h:iA');
return $this;
}
# This will update the account safely
public function updateAccount($money_left,$username)
{
$sql = "UPDATE bank SET money_unit = ? WHERE username = ?";
$query = $this->con->prepare($sql);
$query->execute(array($money_left,$username));
return $query;
}
# This probably needs work, but you should insert using this method
public function addBets($array,$table='bet10_players')
{
$fill = "'', ".implode(', ',array_fill(0,count($array),'?'));
$sql = "INSERT INTO `{$table}` VALUES({$fill})";
$query = $this->con->prepare($sql);
$query->execute($array);
return $query;
}
# Returns the time if need be...
public function getTime()
{
return $this->time;
}
}
/config.php
I would create this page to be included on all pages at the top. It can be expanded and is good to keep everything consistent like your root path and such.
<?php
# start the session
session_start();
# Create some useful defines
define('DS',DIRECTORY_SEPARATOR);
define('ROOT_DIR',__DIR__);
define('CLASSES',ROOT_DIR.DS.'vendors');
define('DB_HOST','localhost');
define('DB_NAME','databasename');
define('DB_USER','root');
define('DB_PASS','');
# Create a class autoloader which turns a \Namespace\Class into a directory
# like /var/html/domain/mydomain/vendor/Namespace/Class.php
spl_autoload_register(function($class) {
$path = str_replace(DS.DS,DS,CLASSES.DS.str_replace('\\',DS,$class).'.php');
if(is_file($path))
include_once($path);
});
/index.php
<?php
# Check if we are inside the class, if not, do so
if(!isset($this)) {
# Include the config file
require_once(__DIR__.DIRECTORY_SEPARATOR.'config.php');
# Create your connection (you should expand on this...)
$con = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER,DB_PASS);
# Create a Game object
echo (new \Game\Observer($con))->render(__FILE__);
# Stop further execution
exit;
}
# Now we are inside the \Game\Observer class, so you can now use $this
# Set the time and add a listener for post
$this->setTime();
# Since there is no indication of where some of these variables come from,
# this listen method will need attention...actually all the elements from the
# \Game and \Game\Observer need review, but they should be close enough to figure out
$this->listen($bank_verify,$pin);
?>
<form role="form" action="" method="post">
<?php
# $this->gameList()->getGames() should just return an array from your database
foreach($this->gameList()->getGames() as $row) {
$team_joined = $row['home_team'].' VS '.$row['away_team'];
$teams = $row['home_team'].'vs'.$row['away_team'];
?>
<h5><?php echo $team_joined; ?></h5>
<h5><span style="color:#f0ad4e;"><?php echo $row['match_day'].', '.$row['match_time'] ?></span></h5>
<input type="hidden" name="game[<?php echo $row['game_id'] ?>]" value="" />
<label><input type="radio" name="game[<?php echo $row['game_id'] ?>]" value="<?php echo $row['home_team']; ?>" />Home</label>
<label><input type="radio" name="game[<?php echo $row['game_id'] ?>]" value="draw" />Draw</label>
<label><input type="radio" name="game[<?php echo $row['game_id'] ?>]" value="<?php echo $row['away_team']; ?>" />Away</label>
<hr>
<?php
}
?>
<div class="form-group">
<input type="text" name="amount" class="form-control" placeholder="Enter your amount here" />
<input type="submit" name="submit" value="submit" class="btn btn-danger" style="margin-bottom: 10px;" />
</div>
</form>
When you process the post, you will retrieve data from the database based on the game id, so you should get all the variables you need except for ones that have no indication of origin in your script. Anyway, this is what I would do if I were you. One final note, I have not tested any of this, some of the methods are based off a framework I use, but I think it's a safer version of your script where sql injection is concerned, though you will have to research what some of this is doing...

Related

php: how to change array value (text)

I'm trying to change value in my array but can't for some reason...
`
My code:
<form action="index.php" method="POST" class="form-control">
<label for="soortMeel">Soort meel:</label>
<input type="text" name="soortMeel" id="soortMeel">
<label for="vorm">Soort vorm:</label>
<input type="text" name="vorm" id="vorm">
<label for="gewicht">gewicht:</label>
<input type="number" name="gewicht" id="gewicht">
<label for="gewicht">row aanpassen:</label>
<input type="number" name="arr_input" id="arr_input">
<div>
<input type="submit" name="add" value="add">
<input type="submit" name="update" value="update">
</div>
</form>
<?php
class brood {
public $soort_meel;
public $vorm_brood;
public $gewicht;
function __construct($soort_meel, $vorm_brood, $gewicht) {
$this->soort_meel = $soort_meel;
$this->vorm_brood = $vorm_brood;
$this->gewicht = $gewicht;
}
function getGewicht() {
return $this->gewicht;
}
function setGewicht($gewicht) {
$this->gewicht = $gewicht;
}
function getVorm_brood() {
return $this->vorm_brood;
}
function setVorm_brood($vorm_brood) {
$this->vorm_brood = $vorm_brood;
}
function getSoort_meel() {
return $this->soort_meel;
}
function setSoort_meel($soort_meel) {
$this->soort_meel = $soort_meel;
}
}
$soort_meel = isset($_POST['soortMeel']) && !empty($_POST['soortMeel']) ? $_POST['soortMeel'] : null;
$vorm_brood = isset($_POST['vorm']) && !empty($_POST['vorm']) ? $_POST['vorm'] : null;
$gewicht = isset($_POST['gewicht']) && !empty($_POST['gewicht']) ? $_POST['gewicht'] : null;
$arr_input = isset($_POST['update']) && !empty($_POST['update']) ? $_POST['update'] : null;
// if(isset($_SESSION['update'])) {
// $arr_input = $_SESSION['update'];
// } else {
// $brood_winkel['soort_meel'] = $soort_meel;
// }
if(isset($_SESSION['brood_winkel'])) {
$brood_winkel = $_SESSION['brood_winkel'];
} else {
$brood_winkel = array(
new brood("volkorenmeel", "volkorenbrood", "35 gram")
);
}
// ADD NEW BROOD
if ($soort_meel != null && $vorm_brood != null && $gewicht != null) {
array_push($brood_winkel, new brood($soort_meel, $vorm_brood, $gewicht));
}
foreach($brood_winkel as $newbrood) {
echo "<table>";
echo "<tr>";
echo "<th>" . $newbrood->getSoort_meel() . "</th>";
echo "<th>" . $newbrood->getVorm_brood() . "</th>";
echo "<th>" . $newbrood->getGewicht() . "</th>";
echo "</tr>";
echo "</table>";
}
$_SESSION['brood_winkel'] = $brood_winkel;
$_SESSION['update'] = $arr_input;
echo $brood_winkel[0];
?>
</body>
</html>
`
trying to echo array but doesn't work:
echo $brood_winkel[0];
Fatal error: Uncaught Error: Cannot use object of type brood as array
in index.php on line 148
Error: Cannot use object of type brood as array in
index.php on line 148
All i want is to set new value in the targetted index of the array.
(if something is not good explained ask them please).
As the error-message already mentions, you can't print a complete object or array with echo. For these cases always use print_r or var_dump.
var_dump($brood_winkel[0]);
print_r($brood_winkel[0]);
You can use echo, if you want to print out single values. In your case this could be one or multiple attribute values:
echo $brood_winkel[0]->getGewicht();
Also, I wanted to add that since all your object-attributes are public you actually don't need your getter-Functions. You can simply access them like this:
echo $brood_winkel[0]->gewicht;
This is also the same way how you can update single values of this object:
$brood_winkel[0]->gewicht = 2;
Of course you can also replace the complete object at the index of that array:
$test_brood = new brood("meel", "brood", "40");
$brood_winkel[0] = $test_brood;
I hope I could help you. Keep it up!

Unable to use an array as an array?

I am in the process of building a software download site for my company.
However, I have come across a problem that I am unsure how to get past.
I am retrieving all the information from a table about a particular software release and placing them in a multidimensional array. I am then trying to run a foreach (I have even tried a for loop) against that array and I get an error shown below:
When I run var dump against the original array, I get this:
So I am really confused as I don't know what I'm missing or where I am going wrong. The reason why I want to run this is so that I can filter the array into a one dimensional array.
Below is the code for the main web page
<?php
//Displays list of companies in 2 columns
$versionAccess = VersionAccess::findAccess($relId);//This gets set earlier in the webpage
$count = count($versionAccess);
var_dump($versionAccess);
foreach ($versionAccess as $va)
{
if ($va->company_access != '0')
{
$versionAcc[] = $va->comapny_id;
}
}
foreach ($company as $compAccess)
{
$compAccessId = $compAccess->company_id;
if (in_array($compAccessId, $versionAcc))
{
$access = 'checked disabled';
}
else { $access = 'disabled'; }
$accessName = 'access'.$compAccessId;
if ($ctr % 2 == 0)
{
echo '<td>'.$compAccess->company_name.':</td>';
echo '<td><label class="switch"><input type="checkbox" name="'.$accessName.'" value="1" '.$access.'><span class="slider round"></span></label></td>';
echo '</tr>';
}
else
{
if ($ctr < $compCount)
{
echo '<tr>';
echo '<td>'.$compAccess->company_name.':</td>';
echo '<td><label class="switch"><input type="checkbox" name="'.$accessName.'" value="1" '.$access.'><span class="slider round"></span></label></td>';
}
else
{
echo '<tr>';
echo '<td>'.$compAccess->company_name.':</td>';
echo '<td><label class="switch"><input type="checkbox" name="'.$accessName.'" value="1" '.$access.'><span class="slider round"></span></label></td>';
echo '</tr>';
}
}
$ctr++;
}
?>
The function that brings the data from the database is:
public static function findAccess($accessId)
//find the version access in database
{
return self::findQuery("SELECT * FROM version_access WHERE version_id = '$accessId'");
}
The findQuery method:
public static function findQuery($sql)
{
global $database;
$resultSet = $database->query($sql);
$objectArray = array();
while ($row = mysqli_fetch_array($resultSet))
{
$objectArray[] = self::instant($row);
}
return $objectArray;
}
I am still relatively new and any help is greatly appreciated.

PHP - How can I get the name of a POST technique from one page to another?

I'm posting a select option from one page to another, on my actual server code (PHP), I'm wanting to firstly, get the POST name, for example, $_POST['selection_value'] and secondly, check if it's equal to a value from the selection, like : if($_POST['selection_value'] == 'time') {} . (time is the value of a selection option). How would I go about doing this ?
My code for the POST grab :
The markup
<div class="form-group" style="padding-left: 4%;">
<div class="form-group m-r-12">
<label class="col-sm-12 control-label";">Add User</label>
</div>
<input type="text" name="username" id="username" placeholder="Username" class="form-control" required />
<input type="text" name="email" id="email" placeholder="Email" class="form-control" required />
<input type="text" name="cpukey" id="cpukey" placeholder="CPUKey" class="form-control" required />
<button onclick="addUser()" class="btn btn-success"><i class="fa fa-user-plus"></i> Add User</button>
<select class="form-control" id="selection_value" name="selection_value">
<option value="account_credits">Account Credits</option>
<option value="free_gifted_credits">Free Gifted Credits</option>
<option value="time">Member Server Days</option>
</select>
<input type="text" name="add_to_all_value" id="add_to_all_value" placeholder="Value to add to current" class="form-control" required />
<button id="button1" onclick="add_to_all()" class="btn btn-primary"><i class="fa fa-user-plus"></i> Add To All Users</button>
The AJAX
function add_to_all() {
myOutput = document.getElementById('add_user_result');
var member_selection = $('#selection_value :selected').text()
var member_value = $('#add_to_all_value').val();
if(member_selection != "" & member_value != "") {
$.ajax ({
type: "POST",
url: 'includes/ajax_data_add_to_all.php',
data: { selection: member_selection, value: member_value },
success:function(response) {
$("#add_user_result").show();
$('#add_user_result').fadeOut(3000).html(response);
header('Location: admin_members.php');
},
error: function() {
$("#add_user_result").show();
$('#add_user_result').fadeOut(3000).html(response);
header('Location: admin_members.php');
}
});
} else {
$("#add_user_result").show();
$('#add_user_result').fadeIn(3000).fadeOut(3000);
myOutput.innerHTML = "<font style='color: red;'>You must fill in all the blanks.</font>";
}
return false;
}
Now my code for the add time (server code) :
function grab_all_time() {
global $con;
$usersTime = "SELECT time FROM users";
$result = $con->query($usersTime) or die("Error");
while ($row = mysqli_fetch_assoc($result)) {
return $row['time'];
}
}
$AllusersTime = grab_all_time();
if(!empty($_POST) && isset($_POST)) {
$selection = mysqli_real_escape_string($con, $_POST['selection']);
$value = mysqli_real_escape_string($con, $_POST['value']);
$membersDate = new DateTime($AllusersTime);
$membersDate->add(new DateInterval('P'.$value.'D'));
$finishedDT = $membersDate->format('Y-m-d') . "\n";
if($selection == 'Member Server Days') {
$insert_query = mysqli_query($con, "UPDATE users SET '".$selection."' + '".$value."'");
if($insert_query) {
echo '<font style="color: green;">Successfully Added to all users</font>';
echo '<META HTTP-EQUIV="Refresh" CONTENT="3; URL=admin_members.php">';
}
else {
echo '<font style="color: red;">Failed to add to all users</font>';
echo '<META HTTP-EQUIV="Refresh" CONTENT="3; URL=admin_members.php">';
}
} else {
$insert_query = mysqli_query($con, "UPDATE users SET time = '".$finishedDT."'");
if($insert_query) {
echo '<font style="color: green;">Successfully Added to all users</font>';
echo '<META HTTP-EQUIV="Refresh" CONTENT="3; URL=admin_members.php">';
}
else {
echo '<font style="color: red;">Failed to add to all users</font>';
echo '<META HTTP-EQUIV="Refresh" CONTENT="3; URL=admin_members.php">';
}
}
To return all records for the query in your function grab_all_time you could use an array, add each result to it and return that array:
function grab_all_time() {
global $con;
$usersTime = "SELECT time FROM users";
$result = $con->query($usersTime) or die("Error");
$results = array();
while( $row = mysqli_fetch_assoc($result) ) {
$results[]=$row['time'];
}
return $results;
}
That obviously returns an array so you can't simply assign the return value as a DateTime object which you later go on to do. If it is just the one result from the query you need to process then why fetch all rows?
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['selection'], $_POST['value'] ) ){
$selection = mysqli_real_escape_string( $con, $_POST['selection'] );
$value = mysqli_real_escape_string( $con, $_POST['value'] );
$AllusersTime = grab_all_time();
foreach( $AllusersTime as $i => $time ){
$membersDate = new DateTime( $time );
$membersDate->add( new DateInterval('P'.$value.'D') );
$finishedDT = $membersDate->format('Y-m-d') . "\n";
/* .... the rest of you code .... */
/* dont add the `meta refresh` */
}
}
Still a trifle confused with what you actually wish to do - hopefully I have understood correctly in that you wish to update each user's record according to values and options selected. To update each record individually using pre-existing content in each of their records using a where clause for the update statement would seem logical.
I think my confusion stems from the sql that retrieves data from the users table in your function. The way it was originally structured meant that despite selecting all records you returned only the first one in the recordset and used that as the basis for the remaining code. If, and I say IF, you intended to return ALL records and process them individually then returning an array from your function seems the best option.
You will note I modified ( again ) your function to also get the user_id associated with each record - substitute that for the correct column name.
function grab_all_time() {
global $con;
/* NOTE: assumed a column `user_id` !! */
$usersTime = "SELECT `user_id`,`time` FROM `users`;";
$result = $con->query($usersTime) or die("Error");
$results = array();
while( $row = mysqli_fetch_assoc($result) ) {
/* NOTE: assumed column `user_id` !! */
$results[ $row['user_id'] ]=$row['time'];
}
return $results;
}
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['selection'], $_POST['value'] ) ){
$selection = mysqli_real_escape_string( $con, $_POST['selection'] );
$value = mysqli_real_escape_string( $con, $_POST['value'] );
$AllusersTime = grab_all_time();
$results = array();
foreach( $AllusersTime as $user_id => $time ){
$membersDate = new DateTime( $time );
$membersDate->add( new DateInterval('P'.$value.'D') );
$finishedDT = $membersDate->format('Y-m-d');
/* .... the rest of you code .... */
if( $selection == 'Member Server Days' ) {
$sql='update `users` set `'.$selection.'`=`'.$selection.'` + '.$value.' where `user_id`="'.$user_id.'";';
} else {
$sql='update `users` set `time`="'.$finishedDT.'" where `user_id`="'.$user_id.'";';
}
$results[ $user_id ]=mysqli_query( $con, $sql ) ? 'Success' : 'Fail';
}
echo '<pre>',print_r( $results, true ),'</pre>';
echo '<META HTTP-EQUIV="Refresh" CONTENT="3; URL=admin_members.php">';
}

Passing information using post method without session variables

I will admit immediately that this is homework. I am only here as a last resort after I cannot find a suitable answer elsewhere. My assignment is having me pass information between posts without using a session variable or cookies in php. Essentially as the user continues to guess a hidden variable carries over all the past guesses up to that point. I am trying to build a string variable that holds them all and then assign it to the post variable but I cannot get anything to read off of the guessCounter variable i either get an undefined index error at the line of code that should be adding to my string variable or im just not getting anything passed over at all. here is my code any help would be greatly appreciated as I have been at this for awhile now.
<?php
if(isset($_POST['playerGuess'])) {
echo "<pre>"; print_r($_POST) ; echo "</pre>";
}
?>
<?php
$wordChoices = array("grape", "apple", "orange", "banana", "plum", "grapefruit");
$textToPlayer = "<font color = 'red'>It's time to play the guessing game!(1)</font>";
$theRightAnswer= array_rand($wordChoices, 1);
$passItOn = " ";
$_POST['guessCounter']=$passItOn;
$guessTestTracker = $_POST['guessCounter'];
$_POST['theAnswer'] = $theRightAnswer;
if(isset($_POST['playerGuess'])) {
$passItOn = $_POST['playerGuess'];
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$guessTestTracker = $_GET['guessCounter'];
$theRightAnswer = $_GET['theAnswer'];
}
else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_POST['playerGuess'])) {
if(empty($_POST['playerGuess'])) {
$textToPlayer = "<font color = 'red'>Come on, enter something(2)</font>";
}
else if(in_array($_POST['playerGuess'],$wordChoices)==false) {
$textToPlayer = "<font color = 'red'>Hey, that's not even a valid guess. Try again (5)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
if(in_array($_POST['playerGuess'],$wordChoices)&&$_POST['playerGuess']!=$wordChoices[$theRightAnswer]) {
$textToPlayer = "<font color = 'red'>Sorry ".$_POST['playerGuess']." is wrong. Try again(4)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
if($_POST['playerGuess']==$wordChoices[$theRightAnswer]) {
$textToPlayer = "<font color = 'red'>You guessed ".$_POST['playerGuess']." and that's CORRECT!!!(3)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
}
}
}
$_POST['guessCounter'] = $passItOn;
$theRightAnswer=$_POST['theAnswer'];
for($i=0;$i<count($wordChoices);$i++){
if($i==$theRightAnswer) {
echo "<font color = 'green'>$wordChoices[$i]</font>";
}
else {
echo $wordChoices[$i];
}
if($i != count($wordChoices) - 1) {
echo " | ";
}
}
?>
<h1>Word Guess</h1>
Refresh this page
<h3>Guess the word I'm thinking</h3>
<form action ="<?php echo $_SERVER['PHP_SELF']; ?>" method = "post">
<input type = "text" name = "playerGuess" size = 20>
<input type = "hidden" name = "guessCounter" value = "<?php echo $guessTestTracker; ?>">
<input type = "hidden" name = "theAnswer" value = "<?php echo $theRightAnswer; ?>">
<input type = "submit" value="GUESS" name = "submitButton">
</form>
<?php
echo $textToPlayer;
echo $theRightAnswer;
echo $guessTestTracker;
?>
This is a minimal functional example of what you need to do. There are still a couple of minor bugs (like duplicate entries in the history), but I've left these as an exercise for you. Treat this as a starting point and build up what you need from it.
I've added comments to explain what's happening, so hopefully it is clear to you.
$answer = null;
$history = [];
$choices = ['apple', 'grape', 'banana'];
$message = '';
// check if a guess has been made.
if (!empty($_POST) && !empty($_POST['guess'])) {
// check if previous guesses have been made.
if (!empty($_POST['history'])) {
$history = explode(',', $_POST['history']);
}
// check guess.
if (!empty($_POST['answer']) && !empty($_POST['guess'])) {
// check guess and answer are both valid.
if (in_array($_POST['guess'], $choices) && isset($choices[$_POST['answer']])) {
if ($_POST['guess'] == $choices[$_POST['answer']]) {
// correct; clear history.
$history = [];
$message = 'correct!';
} else {
// incorrect; add to history and set previous answer to current.
$history[] = $_POST['guess'];
$answer = $_POST['answer'];
$message = 'incorrect!';
}
} else {
// invalid choice or answer value.
}
}
}
if (empty($answer)) {
// no answer set yet (new page load or correct guess); create new answer.
$answer = rand(0, count($choices) - 1);
}
?>
<p>Guess the word I'm thinking:</p>
<p><?php echo implode(' | ', $choices) ?></p>
<form method="POST">
<input type="hidden" name="answer" value="<?php echo $answer; ?>">
<input type="hidden" name="history" value="<?php echo implode(',', $history); ?>">
<input type="text" name="guess">
<input type="submit" name="submit" value="Guess">
</form>
<p><?php echo $message; ?></p>

Checkbox removing listing in a random way

I have a list of favorite cars which i have added to each favorite car a checkbox for letting the user to remove the favorite car from his favorite car list. The problem is that the checkbox is working in a different way: If I check any car (1st, second.. last or multiple cars) and after hit submit the car that will get removed is the last one added instead of removing the selected one. If I check multiple cars, happens same thing, removes only the last car added.
PHP
public function GetFavoriteCars() {
include("inc/membersite_config.php");
$email = $fgmembersite->UserEmail(); // this is how I take the e-mail of the
global $base_path;
$FavoriteCars = $this->QueryResult("SELECT * FROM favoritecar WHERE email='$email'");
if (count($FavoriteCars)) {
$mystring='http://';
echo '<form action="" class="deletebutton" method="post">';
echo '<input type="submit" name="deletebtn" id="deletebtn" value="Submit">';
echo '<div class="roster_slideri-login">';
foreach ($FavoriteCars as $FavoriteCar) {
$carlink = $FavoriteCar->favoritecarlink;
echo '<div class="car-info-col-login">';
echo '<input type="checkbox" name="checkbox" value="'.$carlink.'" class="checkbox-login">';
$val=strpos($FavoriteCar->favoritecarimg,$mystring);
if ($val !== false) {
if($FavoriteCar->favoritecarimg!='') {
echo '<a href="'.$base_path.'detail-page_'.$FavoriteCar->favoritecarlink.'">';
echo '<img src="'.$FavoriteCar->favoritecarimg.'" alt="'.$FavoriteCar->favoritecartitle.'" width="160" height="120" />';
echo '</a>';
echo '<div class="name">'.substr($FavoriteCar->favoritecartitle,0,20).'</div>';
echo '</div>'; //car-info-col-login
}
} else {
echo '<a href="'.$base_path.'detail-page_'.$FavoriteCar->favoritecarlink.'">';
echo '<img src="'.$base_path.'uploads/no-img.jpg" alt="'.$FavoriteCar->favoritecartitle.'" width="160" height="120" />';
echo '</a>';
echo '<div class="name">'.substr($FavoriteCar->favoritecartitle,0,20).'</div>';
echo '</div>';
}
}
echo '</form>';
if (isset($_POST["checkbox"])) {
$this->QueryResult("DELETE from favoritecar WHERE email='$email' AND favoritecarlink='$carlink'");
echo '<script type="text/javascript">alert("Car had been deleted");</script>';
}
echo '</div>'; // div roster_slideri-login
}
}
Explaning:
$email = $fgmembersite->UserEmail(); - this is how I take the e-mail of the current logged in user. It will echo "email_of_logged_in_user#domain.com"
QueryResult is a custom function that looks like this. I usually use it for SELECTING purposes but it seams that is working for deleting purposes too.
abstract class DBDetails {
protected $link = NULL;
protected function connector() {
global $DBHOSTNAME;
global $DBUSERNAME;
global $DBPASSWORD;
global $DBNAME;
$this->link = mysqli_connect($DBHOSTNAME, $DBUSERNAME, $DBPASSWORD, $DBNAME) or die("Can't connect to MySQL server on localhost");
}
protected function close() {
mysqli_close($this->link);
}
}
abstract class N2 extends DBDetails {
public function QueryResult($strQuery) {
$this->connector();
$query = mysqli_query($this->link, $strQuery);
$arr = array();
if ($query) {
while ($result = mysqli_fetch_object($query)) {
array_push($arr, $result);
}
}
$this->close();
return $arr;
}
}
Expected output
When I check the checkbox of a car, it should delete only that car. If I check the checkboxes of multiple cars, should delete the specific cars that I checked.
Please help, I am quite a noob in checkboxes. I have checked lots of questions from here, but did not find my answer.
In this line :
echo '<input type="checkbox" name="checkbox" value="'.$carlink.'" class="checkbox-login">';
--------------
When using multiple checkboxes with same name , you would need to include [] in the name :
echo '<input type="checkbox" name="checkbox[]" value="'.$carlink.'" class="checkbox-login">';
----------------
Then $_POST["checkbox"] will be an array and you can use foreach on it to get all the checked values .
if( isset( $_POST["checkbox"] ) )
{
foreach( $_POST["checkbox"] as $value )
{
/* $value contains $carlink */
echo $value; // For test purpose
/* Sanitize and use it to identify and delete the corresponding row */
}
}
( Rather than name="checkbox[]" it might be better to choose another name . )

Categories