So I'm trying to get records from database by using this code, but I'm only getting else alert message. Can somebody say what I am doing wrong or where is an error in the code? It populates the dropdown, but like I said I don't get the result only the alert message:
<form method='post' action='grafikastest.php'>
<select id="name">
<?php
include_once ('inc\connect.php');
echo "Pasirinkite datą:  ";
$date = strtotime("+0 day");
$dtt=date('Y-m-d', $date);
echo "<option value=$dtt>$dtt</option>";
$date = strtotime("+1 day");
$dtt=date('Y-m-d', $date);
echo"<option value=$dtt>$dtt</option>";
$date = strtotime("+2 day");
$dtt=date('Y-m-d', $date);
echo "<option value=$dtt>$dtt</option>";
$date = strtotime("+3 day");
$dtt=date('Y-m-d', $date);
echo "<option value=$dtt>$dtt</option>";
$date = strtotime("+4 day");
$dtt=date('Y-m-d', $date);
echo "<option value=$dtt>$dtt</option>";
$date = strtotime("+5 day");
$dtt=date('Y-m-d', $date);
echo "<option value=$dtt>$dtt</option>";
$date = strtotime("+6 day");
$dtt=date('Y-m-d', $date);
echo "<option value=$dtt>$dtt</option>";
$sql = "SELECT ID, data, laikas, laikas2 FROM vizitai4 WHERE darb_stat NOT LIKE 'Atlikta' and data LIKE '%" . $dtt . "%' OR
darb_stat IS NULL and data LIKE '%" . $dtt . "%' GROUP BY laikas";
$result = mysql_query($sql);
//rodymas lenteleje
echo $dtt;
echo "<table id=t01>
<tr>
<th>Data</th>
<th>Remonto pradžia</th>
<th>Remonto pabaiga</th>
</tr>";
if(mysql_num_rows($result) > 0) {
while( $row=mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['data'] . "</td>";
echo "<td>Remontas prasideda nuo " . $row['laikas'] . " </td>";
echo "<td>Numatomas remonto baigimo laikas " . $row['laikas2'] . " </td>";
echo "<td style='display: none;'><form method=post>
<input name=id type=hidden value='".$row['id']."';>
</form></td>";
echo "</tr>";
}
}else{
echo "<script>alert('Šios dienos įrašų nėra');</script>";
}
echo "</table>";
?>
</select>
<input type="submit" name="submit" value="Ieskoti">
</form>
</body>
</html>
From our exchange, the core of the issue is that you want interaction with the form to change the form itself and that you are trying to accomplish this with only PHP. Since PHP runs once to generate the page, you can not interact with the form elements after and have PHP react to those changes. You need a triggering effect that will re-query PHP. This is a job for a client-side language such as JavaScript.
Since you asked for an example here is a basic one. It is no easy task and has a bunch of moving parts, so I have a feeling that if you "barely know these things..." with what you have now, you will really be in the dark with this answer.
Follow the instruction and it should work for you. I have tested most of this (or have copied snippets from scripts I use) so pay attention to what things are called and where they are placed and read the notation. I suggest you create this directory/file structure as I have it, then test it out there before you attempt to do any modification to your working document(s). Once you do this stuff, if you don't know what you are doing it's near impossible to troubleshoot. Also take note I can not, in good conscience, answer this question without removing the reference to mysql_, those functions are deprecated or removed completely (php7):
/config.php
<?php
// This page goes on every main page of your site
// Comment out the error lines when live,
// you don't want errors showing on your page except in test
session_start();
ini_set("display_errors",1);
error_reporting(E_ALL);
define('DB_HOST','yourdbhost');
define('DB_USERNAME','yourdbusername');
define('DB_PASSWORD','yourdbpass');
define('DB_NAME','yourdbname');
define('SITE_ROOT',__DIR__);
define('DS', DIRECTORY_SEPARATOR);
define('CLASS_DIR', SITE_ROOT.DS.'core'.DS.'classes');
define('FUNCTION_DIR', SITE_ROOT.DS.'core'.DS.'functions');
require_once(FUNCTION_DIR.DS.'autoloader.php');
// This will help to autoload your classes
// **RESOURCE:** http://php.net/manual/en/function.spl-autoload-register.php
spl_autoload_register('autoloader');
// put whatever else you want on this page to make available to your site.
// You don't need the database connection however
/core/functions/makeOptions.php
<?php
/*
** #description This function uses a for loop to make your options
** You need to think how to use php to make your script(s)
** for you
** **RESOURCE:** http://php.net/manual/en/control-structures.for.php
** #param $max [int] This is how many options the function will make
*/
function makeOptions($max = 6)
{
for($i = 0; $i <= $max; $i++) {
$date = strtotime("+".$i." day");
$dtt = date('Y-m-d', $date);
echo '<option value="'.$dtt.'">'.$dtt.'</option>'.PHP_EOL;
}
}
/core/functions/autoloader.php
<?php
/*
** #description This function is used to autoload classes
** #param $class [string] This is automated and is populated by spl_autoload_register()
** **RESOURCE:** http://php.net/manual/en/function.spl-autoload-register.php
*/
function autoloader($class)
{
if(class_exists($class))
return true;
if(is_file($inc = CLASS_DIR.DS.$class.".php"))
include_once($inc);
}
/page1.php
<?php
// Include our config file
require_once(__DIR__.DIRECTORY_SEPARATOR.'config.php');
// Include the function to create our options
include_once(FUNCTION_DIR.DS.'makeOptions.php');
?><!DOCTYPE html>
<html>
<head>
<!-- include in head with anything else you need -->
<!-- **RESOURCE:** http://www.jquery.com/ -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
$(document).ready(function(){
// Observe any change made to select with name=name
$(this).on('change','select[name=name]',function() {
// get the value of that selection
var thisVal = $(this).val();
// Use ajax to query page2.php
// **RESOURCE:** http://api.jquery.com/jquery.ajax/
$.ajax({
// This is the link that will load the contents of the form
url: '/page2.php',
data: {
// This is equivalent to $_POST['name']
"name":thisVal
},
type: 'POST',
success: function(response) {
// On success of the ajax, this will post the contents of
// page2.php into the div with id=loadspot
$("#loadspot").html(response);
}
});
});
});
</script>
</head>
<body>
<form method='post' action='grafikastest.php'>
<!--
I am not sure the placement of this text, but it can not be
in the middle of a drop down
-->
Pasirinkite datą:  
<select id="name" name="name">
<option value="">Select</option>
<!-- Apply the options function -->
<?php makeOptions(); ?>
</select>
<!-- This is where you will load the contents of the dropdown via ajax -->
<div id="loadspot"></div>
<input type="submit" name="submit" value="Ieskoti">
</form>
</body>
</html>
/core/classes/Database.php
<?php
/*
** #description This class is your new database which replaces your `mysql_`
** **RESOURCE:** http://php.net/manual/en/pdo.connections.php
*/
class Database
{
// static elements are kind of like a global
private static $singleton;
private static $con;
// This will save the class for reuse
public function __construct()
{
if(self::$singleton instanceof Database)
return self::$singleton;
self::$singleton = $this;
}
// This is the connection to the database
public function connect()
{
if(self::$con instanceof PDO)
return self::$con;
// Review the PDO class for instruction how to make this
// connection better using some PDO presets (Emulation of prepares, etc)
// **RESOURCE** http://php.net/manual/en/pdo.constants.php
self::$con = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USERNAME,DB_PASSWORD);
return self::$con;
}
}
/core/classes/qEngine.php
<?php
/*
** #description This class is what you use to safely query your database
** **RESOURCE:** http://php.net/manual/en/pdo.prepare.php
** **RESOURCE:** http://php.net/manual/en/pdo.query.php
** **RESOURCE:** http://php.net/manual/en/pdostatement.fetch.php
**
*/
class qEngine
{
private static $con;
private $query;
public function query($sql = false,$bind = false)
{
// This checks if the connection is already saved
// You can also use "dependency injection" to pass your
// database connection to this class. I prefer to use
// a static connection but here is how that dependency works:
// **RESOURCE** http://code.tutsplus.com/tutorials/dependency-injection-in-php--net-28146
// **RESOURCE** https://en.wikipedia.org/wiki/Dependency_injection
if(!(self::$con instanceof PDO)) {
// Makes connection
$dbEngine = new \Database();
self::$con = $dbEngine->connect();
}
// Creates a bind array
// **RESOURCE** http://php.net/manual/en/pdostatement.bindvalue.php
// **RESOURCE** http://php.net/manual/en/pdostatement.execute.php (Example #2)
// **RESOURCE** http://php.net/manual/en/pdostatement.bindparam.php
if(!empty($bind)) {
$bArray = false;
foreach($bind as $key => $value) {
$bKey = ":{$key}";
$bArray[$bKey] = $value;
}
}
// If there is a bind array, it will run a prepare
if(!empty($bArray)) {
$this->query = self::$con->prepare($sql);
$this->query->execute($bArray);
}
// If no bind, it will run a straight query
else {
$this->query = self::$con->query($sql);
}
// This returns the object for method chaining
// **RESOURCE** http://stackoverflow.com/questions/3724112/php-method-chaining
return $this;
}
public function getResults()
{
// This will check that a query has been made
if(empty($this->query))
return 0;
// This will loop through the results and save to 1D array
while($result = $this->query->fetch(PDO::FETCH_ASSOC))
$row[] = $result;
// This will return either the array or a "0"
return (!empty($row))? $row : 0;
}
}
/core/functions/getListByDate.php
<?php
/*
** #description This function will query your database safely
** #param $date [string] Receives a date by string
*/
function getListByDate($date)
{
$bind = array('%'.$date.'%','%'.$date.'%');
return (new \qEngine()) ->query("SELECT `ID`,`data`,`laikas`,`laikas2`
FROM `vizitai4`
WHERE `darb_stat`
NOT LIKE 'Atlikta'
AND `data`
LIKE :0
OR `darb_stat`
IS NULL AND `data`
LIKE :1
GROUP BY `laikas`",$bind)
->getResults();
}
/page2.php
<?php
// Include our config file
require_once(__DIR__.DIRECTORY_SEPARATOR.'config.php');
// Include the function to query the database
include_once(FUNCTION_DIR.DS.'getListByDate.php');
// This is the page that the AJAX queries from page1.php
// See if the post has been made
if(!empty($_POST['name'])) {
// Fetch data from database
$vizitai4 = getListByDate($_POST['name']);
?>
<table id="t01">
<tr>
<th>Data</th>
<th>Remonto pradžia</th>
<th>Remonto pabaiga</th>
</tr>
<?php
if($vizitai4 != 0) {
foreach($vizitia4 as $row) {
?> <tr>
<td><?php echo $row['data']; ?></td>
<td>Remontas prasideda nuo <?php echo $row['laikas']; ?></td>
<td>Numatomas remonto baigimo laikas <?php echo $row['laikas2']; ?> </td>
<td style="display: none;"><input name="id[]" type="hidden" value="<?php echo $row['id']; ?>" /></td>
</tr>
<?php
}
}
else {
?>
<script>
alert('Šios dienos įrašų nėra');
</script>
<?php
}
?>
</table>
<?php
}
Here is the basic construct of what is happening:
Related
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...
So, I'm trying to create a very basic form using HTML/PHP. Yes, I am a beginner.
I'm going for something along the lines of this.
But instead, I'm getting this.
The form has text input for a few fields such as "Name", "Username", "Email", and then a drop down list to select a browser of your choice. Very basic stuff. I'm trying to return the user input to the screen. The only problem is that when the page loads, I have an empty drop-down box with no browsers to choose from.
I created a PHP class called "Select" that is very simple. It has a few basic functions. I also created two other files, postInfo.php (used to return user info) and userForm.php (the file to create the form itself).
I've tried debugging and testing and I'm almost certain there is nothing wrong the Select class, and the two other files have been run through code validators and nothing comes up. Everything should be fine, but this is starting to give me a headache.
Here's my Select class:
<?php
$browsers = array ("Firefox", "Chrome", "Internet Explorer", "Safari", "Opera", "Konqurer", "Other");
class Select {
private $name;
private $value;
#Getter & Setter methods
public function setName($name) {
$this -> name = $name;
}
public function getName() {
return $this -> name;
}
public function setValue($value){
if (!is_array($value)){
echo ("No array values found.");
}
$this->value = $value;
}
public function getValue() {
return $this -> value;
}
#Method to implement browsers
private function createBrowserList($value){
foreach($value as $val){
echo "<option value=\"$val\">" . $val . "</option>\n";
}
}
#Method to create the selection field
public function createSelections(){
echo "<select name=\"" . $this->getName() . "\">\n";
$this -> makeOptions ($this->getValue());
echo "</select>" ;
}
}
?>
My postInfo.php file:
<?php
$name = $_POST["name"];
$username = $_POST["username"];
$email = $_POST["email"];
$browser = $_POST["browser"];
echo "$name <br>";
echo "$username <br>";
echo "$email <br>";
echo "$browser <br>";
?>
And my userForm.php file (used to create the actual form)
<html>
<body>
<form action ="postInfo.php" method="post" id="form">
Name:<input type ="text" name="name"> <br>
Username:<input type ="text" name="username"> <br>
Email:<input type ="email" name="email"> <br>
<?php
include "selectClass.php";
$selection = new Select();
$selection -> setName("Select Browser");
$selection -> setValue($browsers);
$selection -> createSelections();
?>
<input type = "submit" name = "submit" value = "Go!">
</form>
</body>
</html>
public function createSelections(){
echo "<select name=\"" . $this->getName() . "\">\n";
$this -> createBrowserList ($this->getValue());
echo "</select>" ;
}
You could use something like this:
<?php
$browservalue=array();
$browsers = array ("Firefox", "Chrome", "Internet Explorer", "Safari",
"Opera", "Konqurer", "Other");
foreach ($browsers as $x){
$browservalue[]=strtolower($x);
}
$browsersqnty=sizeof($browsers);
?>
and then inside the html where you want to echo browsers you can do this:
Browsers:<select name='browsers'><?php
for($i=0;$i<$browsersqnty;$i++){
echo "<option value='$browservalue[$i]'>$browser[$i]</option>";
}
?></select>
I'm getting this annoying error and haven't been able to fix it yet.
<b>Fatal error: Class 'Console' not found in /home/serellyn/public_html/HEIM/php/nieuwbeheer/console_overview.php on line 45.</b>
Let's first start with the hierarchy which is like this.
index (main page)
console_overview (section of page)
include/connect (connect to DB)
include/console.class (the class)
The index.php requires the connect.php and the console.class.php and loads the console_overview.php. Here's the code:
<?php
require_once('include/connect.php');
require_once('include/console.class.php');
var_dump(file_exists('include/connect.php'));
var_dump(file_exists('include/console.class.php'));
?>
<div id="mainpage" class="main-container inner">
<?php
if (isset($_GET['page'])) {
$page = $_GET['page'];
} else {
$page = "console_overview";
}
?>
</div>
<!-- end: MAIN CONTAINER -->
<script>
var page = "<?php echo $page;?>";
$( "#mainpage" ).load( page + ".php" );
</script>
I've used var_dumps to check if both file exists (and they do). The console_overview.php loads correctly. Now in the console_overview.php I'm trying to get data from the Console class, as following:
<?php
foreach(Console::getAllConsoles() as $aConsole) {
$consoleID= $aConsole->getID();
$consoleName = $aConsole->getName();
$consoleHostname = $aConsole->getHostname();
$consoleGameID = $aConsole->getGameID();
$consolePowerState = $aConsole->getPowerState();
echo "<tr>";
echo "1";
}
?>
The error I'm getting is caused by the foreach... but I can't find out what's wrong...
The Console class looks like this (I'm pasting the most important parts, otherwise the code would be too long).
<?php
class Console{
private $ID, $hostname, $mac, $ip, $roomID, $gameID, $register, $powerState, $dateUpdated;
public function Console($tID, $tHostname, $tMac, $tIp, $tRoomID, $tGameID, $tRegister, $tPowerState, $tDateUpdated) {
$this->ID = $tID;
$this->hostname = $tHostname;
$this->mac = $tMac;
$this->ip = $tIp;
$this->roomID = $tRoomID;
$this->gameID = $tGameID;
$this->register = $tRegister;
$this->powerState = $tPowerState;
$this->dateUpdated= $tDateUpdated;
}
...
public static function getAllConsoles() {
$sql = "SELECT * FROM `console` ORDER BY `hostname` ASC";
$result = mysql_query($sql);
$theResults = array();
while ($row = mysql_fetch_array($result)) {
$theResults[] = new Console($row[0],$row[1],$row[2],$row[3],$row[4],$row[5],$row[6],$row[7],$row[8],$row[9],$row[10]);
}
return $theResults;
}
}
?>
So can anyone see what the problem is?
Thank you for your help.
Edit: O and yes, I know MySQL is deprecated and will change this whenever the issue of not finding the console is fixed =).
Your console_overview.php does not include the required files. When you make an AJAX call with JavaScript from the client it is a separate HTTP request to the server, so you have to add the require() call again there:
<?php
require_once('include/connect.php');
require_once('include/console.class.php');
foreach(Console::getAllConsoles() as $aConsole) {
$consoleID= $aConsole->getID();
$consoleName = $aConsole->getName();
$consoleHostname = $aConsole->getHostname();
$consoleGameID = $aConsole->getGameID();
$consolePowerState = $aConsole->getPowerState();
echo "<tr>";
echo "1";
}
?>
I have two innoDB tables in my database named customers and vessels. I also have a form with 2 select boxes one having the column: company_name of table: customers as options, and the other having the column: vessel_name of table: vessels.
What i want to do is make the options of the 2nd select box populate according to the customer's company_name chosen in the 1st select box.
Finally please take into consideration that i am a complete newbie in Javascript and jQuery and thats why i am asking here how can i achieve the above result.
The form:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form name="ypo" method="post">
<select name="company_name">
<?php
foreach($pelates as $pelend) {
?>
<option value="<?php echo $pelend->company_name; ?>"><?php echo $pelend->company_name; ?></option>
<?php
}
?>
</select>
<select name="vessel">
<?php
foreach($ploia as $end) {
?>
<option value="<?php echo $end->vessel_name; ?>"><?php echo $end->vessel_name; ?></option>
<?php
}
?>
</select>
</form>
</body>
</html>
The php to make the above form work :
<?php
// For customers
$sqlpelates = "SELECT * FROM customers ORDER BY company_name";
if($pelat = $db->query($sqlpelates)) {
$pelates = array();
while($pelate = $pelat->fetch_object()) {
$pelates[] = $pelate;
}
$pelat->free();
}
// For vessels
$sqlploia = "SELECT * FROM vessels ORDER BY vessel_name";
if($plo = $db->query($sqlploia)) {
$ploia = array();
while($ploi = $plo->fetch_object()) {
$ploia[] = $ploi;
}
$plo->free();
}
?>
UPDATE: Below is the single .php page where i am trying to achieve the above result:
<?php
require 'db/connect.php';
//check if this is an ajax call
$ajax = isset($_POST['ajax']) ? $_POST['ajax'] : false;
if (!$ajax) {
// if not then this is a fresh page that needs everything
$sqlpelates = "SELECT * FROM customers ORDER BY company_name";
if ($pelat=$db->query($sqlpelates)) {
$pelates = array();
while($pelate=$pelat->fetch_object()) $pelates[] = $pelate;
$pelat->free();
}
}
// modify the query to filter out only what your ajax request wants
$where = $ajax ? ' WHERE company_name="'.$_POST['companyName'].'"' : '';
// you need to make sure to escape the incoming variable $_POST['company_name']
$sqlploia = 'SELECT * FROM vessels'.$where.' ORDER BY vessel_name';
if ($plo=$db->query($sqlploia)) {
$ploia = array();
while($ploi=$plo->fetch_object()) $ploia[] = $ploi;
$plo->free();
}
// the secret sauce... and some very bad programming, this should be done some other way
if ($ajax) {
// set the type, so the client knows what the server returns
header('Content-Type: application/json');
// output what the client asked for: an array of vessels in JSON format
echo json_encode($ploia);
// kill the script, this is all the client wants to know
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script src="jquery.js">
// Your code goes here.
// jQuery must be loaded already
$(function(){
var
// put the target php script
url = 'http://prinseapals-marine.com/filing/drop_down.php',
form=$('form[name="ypo"]'), company, vessels;
company = {
// I prefer using native DomElements sometimes
selectBox : $(form).find('select[name="company_name"]')[0],
onSelect : function () {
var
idx = company.selectBox.selectedIndex,
data;
// if user selected an empty option, clear and return
if (idx === -1) {vessels.clearBox();return;}
// setup the data
data = {"ajax":1,"company_name":company.selectBox[idx].value};
// your script now has $_GET['ajax'], $_GET['company_name']
$.post(url,data,vessels.fillBox,'json');
// vessels.fillbox will be executed when your php script returns
}
};
vessels = {
// I prefer using native DomElements sometimes
selectBox : $(form).find('select[name="vessel"]')[0],
// a handy method for clearing options
clearBox : function () {$(this.selectBox).empty()},
// called upon completion of the ajax request
fillBox : function (arrayOfVessels) {
// clear current contents
$(this.selectBox).empty();
// for each element in the array append a new option to the vessel selector
arrayOfVessels.forEach(function(v){
$(vessels.selectBox).append('<option value="'+v+'">'+v+'</option>');
});
}
};
// add a listener to the company selector
$(company.selectBox).change(company.onSelect);
});
</script>
<form name="ypo" method="post">
<select name="company_name">
<?php
foreach($pelates as $pelend) {
?>
<option value="<?php echo $pelend->company_name; ?>"><?php echo $pelend->company_name; ?></option>
<?php
}
?>
</select>
<select name="vessel">
<?php
foreach($ploia as $end) {
?>
<option value="<?php echo $end->vessel_name; ?>"><?php echo $end->vessel_name; ?></option>
<?php
}
?>
</select>
</form>
</body>
FINAL-UPDATE :
test.php:
<?php
require 'db/connect.php';
$cus = array();
if($cterm = $db->query("SELECT * FROM `customers`")) {
while($cterm2 = $cterm->fetch_object()) {
$cus[] = $cterm2;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<form id="form1" name="myform">
<select name="selection" onchange="load('bdiv', 'test2.php');">
<?php
foreach($cus as $c) {
?>
<option value="<? echo $c->company_name ?>"><? echo $c->company_name ?></option>
<?php
}
?>
</select>
<div id="bdiv"></div>
</form>
</body>
</html>
test.js:
function load (thediv, thefile) {
// body...
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById(thediv).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', thefile+'?selection='+document.myform.selection.value, true);
xmlhttp.send();
}
test2.php:
<?php
require 'db/connect.php';
if (isset($_GET['selection'])) {
# code...
$selection = $_GET['selection'];
}
$ves = array();
if ($vterm = $db->query(
"SELECT `vessel_name` FROM `vessels` WHERE `company_name` = '$selection'")) {
while ($vterm2 = $vterm->fetch_object()) {
$ves[] = $vterm2;
}
} else {
echo 'Please type a customer name.';
}
?>
<select>
<?php
foreach($ves as $v) {
?>
<option value="<?php echo $v->vessel_name ?>" ><?php echo $v->vessel_name ?></option>
<?php
}
?>
</select>
This is not the first time I see this asked but I will dive in
Warning: this answer has javascript, with jQuery. I will also append a php file afterwards with some changes to allow the same script to be called for the ajax request
// jQuery must be loaded already
$(function(){
var
// put the target php script
url = 'http://localhost/test/stackoverflow.php',
form=$('form[name="ypo"]'), company, vessels;
company = {
// I prefer using native DomElements sometimes
selectBox : $(form).find('select[name="company_name"]')[0],
onSelect : function () {
var
idx = company.selectBox.selectedIndex,
data;
// if user selected an empty option, clear and return
if (idx === -1) {vessels.clearBox();return;}
// setup the data
data = {"ajax":1,"company_name":company.selectBox[idx].value};
// your script now has $_GET['ajax'], $_GET['company_name']
$.post(url,data,vessels.fillBox,'json');
// vessels.fillbox will be executed when your php script returns
}
};
vessels = {
// I prefer using native DomElements sometimes
selectBox : $(form).find('select[name="vessel"]')[0],
// a handy method for clearing options
clearBox : function () {$(this.selectBox).empty()},
// called upon completion of the ajax request
fillBox : function (arrayOfVessels) {
// clear current contents
$(this.selectBox).empty();
// for each element in the array append a new option to the vessel selector
arrayOfVessels.forEach(function(v){
$(vessels.selectBox).append('<option value="'+v+'">'+v+'</option>');
});
}
};
// add a listener to the company selector
$(company.selectBox).change(company.onSelect);
});
The logic behind the js code is to allow user interaction. When the user makes a selection a request is fired to the server and the response is processed in the client and populates your 2nd <select>
Now, a modified version of your php script (warning: this works with the template I append next)
<?php
// your model, check for whitespaces outside php tags, do not allow output yet
require 'db/connect.php';
// check if this is an ajax call
$ajax = isset($_POST['ajax']) ? $_POST['ajax'] : false;
if (!$ajax) {
// required for the template
$pelates = array();
// if not then this is a fresh page that needs everything
$sqlpelates = "SELECT * FROM customers ORDER BY company_name";
if ($pelat=$db->query($sqlpelates)) {
while($pelate=$pelat->fetch_object()) $pelates[] = $pelate;
$pelat->free();
}
} else {
// modify the query to filter out only what your ajax request wants
$where = ' WHERE company_name="'.$_POST['companyName'].'"';
// required for the ajax request
$ploia = array();
// you need to make sure to escape the incoming variable $_POST['company_name']
$sqlploia = 'SELECT * FROM vessels'.$where.' ORDER BY vessel_name';
if ($plo=$db->query($sqlploia)) {
while($ploi=$plo->fetch_object()) $ploia[] = $ploi;
$plo->free();
}
// the secret sauce... and some very bad programming, this should be done some other way
// set the type, so the client knows what the server returns
header('Content-Type: application/json');
// output what the client asked for: an array of vessels in JSON format
echo json_encode($ploia);
// kill the script, this is all the client want's to know
exit;
}
?>
Next comes a modified version of your html template
<!DOCTYPE html>
<html>
<head>
<title>Your title</title>
</head>
<body>
<form name="ypo" method="post">
<select name="company_name"><?php
foreach($pelates as $p) echo '<option value="'.$p->company_name.'">'.$p->company_name.'</option>';
?></select>
<!-- leave empty, we will populate it when the user selects a company -->
<select name="vessel"></select>
</form>
<!-- add jQuery lib here, either your own or from a CDN; this is google's version 2.0.3 -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<!-- The code should be in a seperate file, load here if you want (but after jQuery lib) -->
<script src="your/javascript/file.js"></script>
</body>
</html>
Ok, now some pointers
you should be carefull with the php script I left there, there are other ways of doing what I intended which are cleaner and easier to maintain
the javascript is not the best, there are better solutions out there so be sure to check those out as well
If you do not understand parts of any of the scripts don't hesitate to ask
Beware any whitespace, do not allow any output before the php script, this is very important. All output should be left to the template
I hope this has been helpfull
Use ajax for this, Pass your company id to the javascript
<script>
function showCustomer(str)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myresult").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php?q="+str,true); // Pass value to another page Here->test
xmlhttp.send();
}
</script>
<select name="company_name" onchange="showCustomer(this.value)">
<?php
foreach($pelates as $pelend) {
?>
<option value="<?php echo $pelend->company_name; ?>"><?php echo $pelend->company_name; ?></option>
<?php
}
?>
</select>
<div id="myresult">
</div>
Now On test.php Simply Call Value & put select box,
<?php
$q = $_GET['q'];
// Here fetch values for particular q(company name)
// put select box
I've done some searches and I've come up with no clear answer. I'm not a javascript person at all and am pretty clueless. PHP I understand however, and to me this should work. I should also note, that this script used to use document.all for it's javascript, which I've tried to update to getElementById() when possible (since document.all was throwing an error in firebug).
Now for the most part, the page displays fine, albeit without the javascript changes that are supposed to happen.
I must also apologize for the archaic nature of the code, I inherited this code when I took over as internet guy for our gaming club. This code is for the purchase of fictional items using fictional credits.
When I click an item to "buy" it (or maybe not whichever) The background of that row is supposed to turn green, and the credits are supposed to be subtracted from my total account (or reverse if I uncheck the box). Clicking the submit button adds this stuff I clicked to another sheet, and subtracts the actual amount from my account.
Currently I get a "tr615 is undefined" error This is the PHP generated code for the element as shown below.
If someone can help me figure this out it would fantastic. I just can't seem to find an answer after a few days of searching google and here.
PHP Snippet of relevent code: (we use custom functions on our site ie: entry)
For instance say $id=615
<?php
while (list ($id, $name, $class, $desc, $range, $damage, $cost,$hide) = entry ($items) )
{
if ($hide =='0')
{
$JavaScriptArrayParms .= '"' . $id . '",';
$list .= $id . ',';
?>
<tr id="tr<?php echo $id; ?>"> //Thus tr615 for this example
<td>
<input type="checkbox" name="chk<?php echo $id; ?>" onclick="updateStoreTable(this.form, this, <?php echo $id; ?>)" />
<input type="hidden" name="cost<?php echo $id; ?>" value="<?php echo $cost; ?>" />
</td>
<td><?php echo $name; ?></td>
<?php if (! in_array($catid, $noclass)){ echo "<td>$class</td>";}?>
<td><?php echo $desc; ?></td>
<?php if (! in_array($catid, $norange)){ echo "<td>$range</td>";}?>
<td><?php echo $damage; ?></td>
<td><?php echo $cost; ?></td>
</tr>
<?php
}
}
?>
</table>
<input type="hidden" name="list" value="<?php echo $list; ?>" />
<input type="button" value="Purchase!" onclick='validatePurchase(this)' />
<input type="reset">
</form>
Relevant JS: (which used to be document.all.store... or just document.all.. in some cases. I hope I fixed it the right way)
<script language="javascript">
var startmoney = <?php echo $currMoney; ?>;
function canAfford(t,id)
{
if(t.checked) return;// don't touch if checked for buying.
//alert("canAfford("+t+","+id+");");
//t.disabled = false;
eval("document.store.getElementByID(foo).disabled = false;");
eval("document.store.getElementByID(foo).checked = false;");
eval("document.getElementByID(tr"+id+").style.background = '#000000';");
}
function cantAfford(t,id)
{
//alert("cantAfford("+t.disabled+","+id+")-- "+t+";");
//alert("before disable");
//t.disabled = true;
eval("document.store.getElementByID(chk"+id+").disabled = "+true+";");
//alert("After disable");
eval("document.store.getElementByID(chk"+id+").checked = false;");
eval("document.getElementByID(tr"+id+").style.background = '#555555';");
}
function getCost(id)
{
return eval("document.store.getElementByID(cost"+id+").value");
}
function buying(t,id)
{
eval("document.getElementByID(tr"+id+").style.background = 'green';");
document.store.credits.value -= getCost(id);
}
function notbuying(t,id)
{
eval("document.getElementByID(tr"+id+").style.background = '#000000';");
var creds = new Number(document.store.credits.value);
var cost = new Number(getCost(id));
document.store.credits.value = (creds + cost);
}
function updateStoreTable(f,t,id)
{
var ids = new Array(<?php echo $JavaScriptArrayParms; ?>);
if(t.checked)
buying(t,id);
else
notbuying(t,id);
for(i = 0; i<ids.length; i++)
{
cost = new Number(getCost(ids[i]));
creds = new Number(f.credits.value);
//alert("COST: " +(cost)+"\nCREDITS: "+creds+"\nID: "+ids[i]);
// alert("'"+ (cost) + "' > '" + (creds) +"'\n"+(eval(cost > creds)));
// alert("f.chk"+ids[i]+".checked");
if(eval("f.chk"+ids[i]+".checked")) { continue; } //ignore already carted items
if(eval(cost > creds))
cantAfford(eval("f.chk"+id),ids[i]);
else
canAfford(eval("f.chk"+id),ids[i]);
}
}
1st issue:
it has to be getElementById()
(a lower-case d at the end)
2nd:
When using eval, the code will be evaluated as:
document.getElementById(tr615).style.background = '#000000';
..what will force the error, because the tr615 is not enclosed by quotes, so javascript expects a variable tr615.
the line must look like this:
eval("document.getElementById('tr"+id+"').style.background = '#000000';");
But: Why do you use eval here, this can be done without eval:
document.getElementById('tr'+id).style.background = '#000000';