How I can do remember text in input - php

I have two problems with the following code, i.e.
I would like saved values in input to be remembered, because now it returns the value " Notice : Undefined variable: name_check in".
If the domain length is shorter than 5 characters, it returns an error but only at the first input, and I would like the validation error to be at each of the inputs.
<?php
require_once "connect.php";
$connect = #new mysqli($host, $db_user, $db_password, $db_name);
if(isset($_POST['send']))
{
$all_ok=true;
$id = $_POST['id'];
$domain_name = $_POST['domain_name'];
foreach ($domain_name as $value)
{
if (strlen($value)<5)
{
$all_ok=false;
$_SESSION['e_name']="Wpisana domena jest zbyt króka.";
}
}
$_SESSION['fr_name'] = $value;
if ($all_ok==true)
{
$count = count($id);
for($i=0;$i<$count;$i++) {
$connect->query('UPDATE domains SET domain_name="'.$domain_name[$i].'" WHERE id='.(int)$id[$i].'');
}
$_SESSION['well_done']=true;
echo "udana walidacja";
}
}
?>
<style>
.error
{
color:#cc0000;
margin-top: 5px;
margin-bottom: -5px;
font-size:12px;
}
</style>
<form method="POST" action="">
<table>
<?php
$result = $connect->query("SELECT * FROM domains");
$how_nick = $result->num_rows;
if ($how_nick != 0) {
while($data = $result->fetch_assoc())
{
?>
<tr>
<td>Nazwa Domeny:<br> <input type="text" value="<?php
if (isset($_SESSION['fr_name']))
{
echo $_SESSION['fr_name'];
unset($_SESSION['fr_name']);
}
else
{
echo $data['domain_name'];
}
?>" name="domain_name[]"><br /><?php
if (isset($_SESSION['e_name']))
{
echo '<div class="error">'.$_SESSION['e_name'].'</div>';
unset($_SESSION['e_name']);
}
?></td>
<td><input type="hidden" name="id[]" value="<?php echo $data['id'];?>"/></td>
</tr>
<?php
}}
?>
</table>
<br /><center><input class="button" type="submit" name="send" value="Zapisz"></center>
</form>

Related

Increment score only when the user's answer is correct

Im a student and new to php. Im currently working on a skill test project where scores in different categories (which are ABM, HUMSS, STEM, GAS, TVL) are counted. The problem is the scores still increment even when the user's answer is wrong. I hope someone can help me fix my codes..
results.php
if(isset($_POST['submit'])) {
$ans = $_POST['ans'];
$abmscore = 0;
$humssscore = 0;
$stemscore = 0;
$gasscore = 0;
$tvlscore = 0;
if( !empty($ans)):
foreach($ans as $qID => $qVal) {
$qID = (int) $qID;
$qVal = (int) $qVal;
$query1= "SELECT COUNT(*) AS rightAnswer FROM tquestions WHERE test_id = $qID AND correctanswer = $qVal";
$result1= mysqli_query($conn, $query1);
$row1 = mysqli_fetch_array($result1, MYSQLI_ASSOC);
$query2 = "SELECT strand FROM tquestions WHERE test_id = $qID";
$result2 = mysqli_query($conn, $query2);
$row2 = mysqli_fetch_array($result2, MYSQLI_ASSOC);
$strand = $row2['strand'];
if (!$result2) {
printf("Error: %s\n", mysqli_error($conn));
exit();
}
if($row1['rightAnswer']) {
if($strand == 'ABM' ) {
$abmscore++;
}
elseif ($strand == 'HUMSS' ) {
$humssscore++;
}
elseif ($strand == 'STEM' ) {
$stemscore++;
}
elseif ($strand == 'GAS' ) {
$gasscore++;
}
elseif ($strand == 'TVL' ) {
$tvlscore++;
}
}
}
endif;
}
test.php
$sql = "SELECT test_id, question, optiona, optionb, optionc, optiond FROM tquestions ORDER BY RAND() LIMIT 0, 50";
$result = mysqli_query ($conn, $sql);
if (!$result) {
printf("Error: %s\n", mysqli_error($conn));
exit();
}
<form action="results.php" method="POST">
<?php if (mysqli_num_rows($result) > 0): ?>
<?php $index = 1; $num = 1; ?>
<?php foreach ($result as $results):
$question = $results['question'];
$optiona = $results['optiona'];
$optionb = $results['optionb'];
$optionc = $results['optionc'];
$optiond = $results['optiond'];
$test_id = $results['test_id'];
?>
<div id="q<?php echo ($index++); ?>" class="tabcontent">
<table class="table table-hover">
<tbody>
<tr class="form-group">
<h3 name="ques[<?php echo $test_id;?>]" style="text-indent: 40px;"> <?php echo $num,'. ', $question; ?> </h3>
</tr>
<tr class="form-group">
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="ans[<?php echo $test_id;?>]" value="<?php echo $optiona;?>"><?php echo $optiona;?>
</label>
<br>
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="ans[<?php echo $test_id;?>]" value="<?php echo $optionb;?>"><?php echo $optionb;?>
</label>
<br>
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="ans[<?php echo $test_id;?>]" value="<?php echo $optionc;?>"><?php echo $optionc;?>
</label>
<br>
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="ans[<?php echo $test_id;?>]" value="<?php echo $optiond;?>"><?php echo $optiond;?>
</label>
<br>
</tr>
</tbody>
</table>
</div>
<?php $num++; ?>
<?php endforeach ?>
<?php endif ?>
<br>
<div class="form-group"><center>
<input class="btn btn-success" type="submit" name="submit" value="Submit" onclick="return confirm('Are you sure you want to submit your answers?')"></center>
</div>
Here is my database table of test questions:
There is a lot packed in here and I have tested it to be successful, but if anyone finds a flaw, let me know and I'll fix it up.
This is the database table data that I am working with: http://sqlfiddle.com/#!9/036c06/1/0
This is my test.php code:
if (!$conn=new mysqli($host,$user,$pass,$db)) {
echo "Database Connection Error: " , $conn->connect_error; // don't show error messages to the public
} elseif (!$result = $conn->query('SELECT test_id, question, optiona, optionb, optionc, optiond FROM tquestions ORDER BY RAND() LIMIT 50')) {
echo "Syntax Error: " , $conn->error; // don't show error messages to the public
} elseif (!$result->num_rows) {
echo "Logic Error: No Rows # Questions Query";
} else {
echo "<form action=\"results.php\" method=\"POST\">";
$i = 0;
while ($row=$result->fetch_assoc()) {
echo "<div id=\"q",++$index,"\" class=\"tabcontent\">";
echo "<table class=\"table table-hover\">";
echo "<tbody>";
echo "<tr class=\"form-group\">";
echo "<h3 name=\"ques{$row['test_id']}\" style=\"text-indent:40px;\"> " , ++$i , ". {$row['question']} </h3>"; // can't see a reason to have a name attribute here
echo "</tr>";
$options = [$row['optiona'],$row['optionb'],$row['optionc'],$row['optiond']];
shuffle($options); // shuffle the options to improve test structure
echo "<tr class=\"form-group\">";
foreach ($options as $option) {
echo "<label class=\"radio-inline\" style=\"text-indent:70px;font-size:18px;\"> ";
echo "<input style=\"font-size:18px;\" type=\"radio\" name=\"ans[{$row['test_id']}]\" value=\"$option\">$option";
echo "</label><br>";
}
echo "</tr>";
echo "</tbody>";
echo "</table>";
echo "</div>";
}
echo "<div class=\"form-group\">";
echo "<center><input class=\"btn btn-success\" type=\"submit\" name=\"submit\" value=\"Submit\" onclick=\"return confirm('Are you sure you want to submit your answers?')\"></center>";
echo "</div>";
echo "</form>";
}
Some notes:
I don't like to bounce in and out of php, so I just stay inside php and echo everything out (personal preference).
I have elected to use object-oriented mysqli syntax (personal preference).
I have removed the name attribute on the <h3> tag because I don't see the benefit. If you have a reason, just re-add it.
I have shuffled the options for each question so that the test seems "fresh" each time.
I have displayed the options in a loop to make the code more DRY.
This is my results.php code:
if (!isset($_POST['submit']) && !empty($_POST['ans'])) {
echo "Insufficient Submission Data Received";
} elseif (!$conn=new mysqli($host,$user,$pass,$db)) {
echo "Database Connection Error: ",$conn->connect_error;
} else {
$params = array_keys($_POST['ans']); // collect test_ids from submission data
$results = array('ABM'=>0,'HUMSS'=>0,'STEM'=>0,'GAS'=>0,'TVL'=>0); // init / zero-out the categories
$count = count($params); // number of fullstring matches
$csph = implode(',',array_fill(0,$count,'?')); // comma-separated placeholders
if (!$stmt=$conn->prepare("SELECT test_id,strand,correctanswer FROM tquestions WHERE test_id IN ($csph);")) {
echo "Syntax Error # prepare: " , $conn->error; // don't show error messages to the public
} else {
array_unshift($params, str_repeat('s', $count)); // prepend the type values string
$ref = []; // add references
foreach ($params as $i=>$v) {
$ref[$i] = &$params[$i]; // pass by reference as required/advised by the manual
}
call_user_func_array([$stmt, 'bind_param'], $ref);
if (!$stmt->execute()) {
echo "Error # bind_param/execute: ",$conn->error;
} elseif (!$stmt->bind_result($test_id,$strand,$correctanswer)) {
echo "Error # bind_result: " , $stmt->error; // don't show error messages to the public
} else {
while ($stmt->fetch()) {
if (isset($_POST['ans'][$test_id], $results[$strand]) && $_POST['ans'][$test_id] == $correctanswer) {
++$results[$strand];
}
}
$stmt->close();
var_export($results);
}
}
}
Some notes:
I am only doing some basic submission checking at the start of the script. you can make additional refinements if you are so inclined.
As a matter of database protection, I use a prepared statement to query the database with user-provided data. Unfortunately, the process of generating a "safe" IN clause is rather verbose. You don't need to "understand" all of the components involved with call_user_func_array() if you are just beginning your journey with php. You may just trust it for now, and research it later when you want to wrap your head around it.
I decided to store the categorical correct answer tally as an array of data, rather than individual variables since it is a set of data with the same uniform structure.
If you wonder about the data assigned to particular values in my scripts, just write some strategically placed echos or var_export()s on the variables.
When I submit a "perfect" form to result.php, this is the $_POST data:
array ( 1 => '1 and 0', 8 => 'Marcelo del Pilar', 7 => 'Marcelo del Pilar', 3 => 'Liability', 5 => 'Variable', 4 => 'Crisis', 6 => 'Marcelo del Pilar', )
and this is the $results data:
array ( 'ABM' => 1, 'HUMSS' => 1, 'STEM' => 1, 'GAS' => 3, 'TVL' => 1, )
edited:
Okay, this may need some explanation afterward, but I believe I've found a solution for you. Your code, as you have it now, gives all of your radio options the same name: ans<?php echo $test_id ?>. By doing this, you're passing all 4 options at once to the same variable. That's an issue.
Change the names of your inputs to be unique, and also pass test_id to results.php in a hidden input:
<tr class="form-group">
<input type="hidden" name="test_id" value="<?php echo $test_id ?>">
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="option_a" value="<?php echo $optiona;?>"><?php echo $optiona;?>
</label>
<br>
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="option_b" value="<?php echo $optionb;?>"><?php echo $optionb;?>
</label>
<br>
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="option_c" value="<?php echo $optionc;?>"><?php echo $optionc;?>
</label>
<br>
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="option_d" value="<?php echo $optiond;?>"><?php echo $optiond;?>
</label>
<br>
</tr>
Then update your test.php like to check WHICH radio was selected and grab the test_id from that hidden field:
if(isset($_POST['submit'])) {
if (isset($_POST['option_a'])) $ans = $_POST['option_a'];
if (isset($_POST['option_b'])) $ans = $_POST['option_b'];
if (isset($_POST['option_c'])) $ans = $_POST['option_c'];
if (isset($_POST['option_d'])) $ans = $_POST['option_d'];
if (isset($_POST['test_id'])) $id = $_POST['test_id'];
Then remove your foreach loop and fix your SQL query to "SELECT correctanswer FROM tquestions WHERE test_id = $id", because we have all of the other info, we only need the correct answer based on the ID of the question we passed from test.php
$query1= "SELECT correctanswer AS rightAnswer FROM tquestions WHERE test_id = $id";
In the end, results.php should look like this:
if(isset($_POST['submit'])) {
if (isset($_POST['option_a']) $ans = $_POST['option_a'];
if (isset($_POST['option_b']) $ans = $_POST['option_b'];
if (isset($_POST['option_c']) $ans = $_POST['option_c'];
if (isset($_POST['option_d']) $ans = $_POST['option_d'];
if (isset($_POST['test_id'])) $id = $_POST['test_id'];
$abmscore = 0;
$humssscore = 0;
$stemscore = 0;
$gasscore = 0;
$tvlscore = 0;
$query1= "SELECT correctanswer AS rightAnswer FROM tquestions WHERE test_id = $id";
$result1= mysqli_query($conn, $query1);
$row1 = mysqli_fetch_array($result1, MYSQLI_ASSOC);
$query2 = "SELECT strand FROM tquestions WHERE test_id = $id";
$result2 = mysqli_query($conn, $query2);
$row2 = mysqli_fetch_array($result2, MYSQLI_ASSOC);
$strand = $row2['strand'];
if (!$result2) {
printf("Error: %s\n", mysqli_error($conn));
exit();
}
if($ans == $row1['rightAnswer']) {
if($strand == 'ABM') {
$abmscore++;
}
elseif ($strand == 'HUMSS') {
$humssscore++;
}
elseif ($strand == 'STEM') {
$stemscore++;
}
elseif ($strand == 'GAS') {
$gasscore++;
}
elseif ($strand == 'TVL') {
$tvlscore++;
}
}
}
Your test.php had some unnecessary things in it. You don't need to use for every line of PHP code. You only need to open it and close it between parsing other languages like HTML. If you'd like me to explain further I'd be happy, but for now, I've tweaked test.php:
$sql = "SELECT test_id, question, optiona, optionb, optionc, optiond FROM tquestions ORDER BY RAND() LIMIT 0, 50";
$result = mysqli_query ($conn, $sql);
if (!$result) {
printf("Error: %s\n", mysqli_error($conn));
exit();
}
<form action="results.php" method="POST">
<?php if (!mysqli_num_rows($result) > 0) die('No data');
foreach ($result as $results) {
$question = $results['question'];
$optiona = $results['optiona'];
$optionb = $results['optionb'];
$optionc = $results['optionc'];
$optiond = $results['optiond'];
$test_id = $results['test_id'];
} ?>
<div id="q<?php echo ($index++); ?>" class="tabcontent">
<table class="table table-hover">
<tbody>
<tr class="form-group">
<h3 name="ques[<?php echo $test_id;?>]" style="text-indent: 40px;"> <?php echo $num,'. ', $question; ?> </h3>
</tr>
<tr class="form-group">
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="ans[<?php echo $test_id;?>]" value="<?php echo $optiona;?>"><?php echo $optiona;?>
</label>
<br>
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="ans[<?php echo $test_id;?>]" value="<?php echo $optionb;?>"><?php echo $optionb;?>
</label>
<br>
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="ans[<?php echo $test_id;?>]" value="<?php echo $optionc;?>"><?php echo $optionc;?>
</label>
<br>
<label class="radio-inline" style="text-indent: 70px; font-size: 18px;">
<input style="font-size: 18px;" type="radio" name="ans[<?php echo $test_id;?>]" value="<?php echo $optiond;?>"><?php echo $optiond;?>
</label>
<br>
</tr>
</tbody>
</table>
</div>
<br>
<div class="form-group"><center>
<input class="btn btn-success" type="submit" name="submit" value="Submit" onclick="return confirm('Are you sure you want to submit your answers?')"></center>
</div>
For my sake, I hope this works out for you.

Add-to-cart coding is that correct with form?

<?php
session_start();
include("conn.php");
$action = $_POST['action'];
$user = $_SESSION['username'];
if(empty($user)){
echo"<script>alert('Please log in!');window.location='Log In.php';</script>";
exit;
}
if($action == 'add'){
$cart_arr = array(
'foodID'=>$_POST['foodID'],
'order_num'=>$_POST['order_num'],
'food_type'=>$_POST['food_type'],
);
$cart_session = $_SESSION['cart_'.$user];
if(empty($cart_session)){
$cart_session[$cart_arr['foodID']] = $cart_arr;
} else if(!empty($cart_session[$cart_arr['foodID']])){
$cart_session[$cart_arr['foodID']]['order_num']+=$cart_arr['order_num'];
} else {
echo $cart_session[$cart_arr['foodID']] = $cart_arr;
}
$_SESSION['cart_'.$user] = $cart_session;
} else if($action == 'clear'){
$_SESSION['cart_'.$user]=array();
echo"<script>alert('Shopping cart is empty, return home!');window.location='homepage.php';</script>";
exit;
} else if($action == 'change'){
$temp_cart = $_SESSION['cart_'.$user];
foreach($temp_cart as $k=>$v){
if($_POST['goods_'.$k]!= $v['order_num']){
$temp_cart[$k]['order_num'] = $_POST['goods_'.$k];
}
if($_POST['goods_'.$k] == 0){
unset($temp_cart[$k]);
}
}
$_SESSION['cart_'.$user] = $temp_cart;
}
if(empty($_SESSION['cart_'.$user])){
echo"<script>alert('Shopping cart is empty, please add some orders!');window.location = 'homepage.php';</script>";
exit;
}
$goods_id = array();
$cart = $_SESSION['cart_'.$user];
$v['food_type'] = $_POST['food_type'];
foreach($cart as $k=>$v){
$goods_id[$v['foodID']] = $v['foodID'];
}
$goods_id_str = implode(",",$goods_id);
mysql_query("set names utf8");
$sql = "select * from foodmenu where foodID IN (".$goods_id_str.")";
$query = mysql_query($sql);
$cart_goods = array();
while($arr = mysql_fetch_array($query)){
$cart_goods[$arr['foodID']] = $arr;
}
foreach($cart as $k=>$v){
$cart[$k]['food_name'] = $cart_goods[$k]['food_name'];
$cart[$k]['food_img'] = str_replace("../","",$cart_goods[$k]['food_img']);
$cart[$k]['food_price'] = $cart_goods[$k]['food_price'];
$cart[$k]['food_description'] = $_POST['food_description'];
}
?>
May I know is that this coding correct?
Because it shows blank page when it click on the button on previous php for add-to-cart purpose and it just shows normal header at the top.
I will attach form to access this php.
<div class="detailtop">
<?php
$result = mysql_query("SELECT * FROM foodmenu where foodID = '$foodID'");
while($row=mysql_fetch_array($result)){
?>
<dl>
<dt>
<img src="<?php echo $row["food_img"];?>" /> </dt>
<dd>
<form action="order.php" method="get" name="send" onSubmit="return Check()" enctype="multipart/form-data">
<h3><?php echo $row["food_name"];?></h3>
<div class="detailtips">
<?php echo $row["food_description"];?>
</div>
<p><span>Restaurant:</span><strong><?php echo $row["restaurant_name"];?></strong></p>
<p><span>Type :</span><strong><?php echo $row["food_type"];?></strong></p>
<p><span>Price :</span>RM <strong><?php echo $row["food_price"];?><input name="num" type="hidden" class="num" value="<?php echo $row["food_price"];?>" /></strong></p>
<div class="order" style=" padding-top:20px; padding-left:20px;">
<input name="id" type="hidden" value="<?php echo $row["foodID"];?>" />
<input name="" type="submit" value="" class="ordersubmit" style=" margin-left:30px; margin-top:20px;">
</div>
</form>
</dd>
</dl>
<?php }?>
</div>

how can i display values from table according to a column between two dates and time?

I have two tables floattable(dateandtime,mitm,tagindex,value,status,marker) and tagtable(tagname,tagindex,tagtype,tagdatatype).i want to display output as
<form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
<p>REPORT</p>
Select AI Type:
<select name="AI-Types" id="AI-Tpes">
<option value="select">--Select--</option>
<option value="DTP4">DTP4</option><option value="FT1">FT1</option><option value="FT2">FT2</option><option value="FT3">FT3</option><option value="LT1">LT1</option><option value="LT2">LT2</option><option value="PT1">PT1</option><option value="PT2">PT2</option>
<option value="PT3">PT3</option><option value="TE1">TE1</option><option value="TE2">TE2</option><option value="TE4">TE4</option><option value="VFD">VFD</option><option value="XT3">XT3</option><option value="XT4">XT4</option><option value="PT2">PT2</option>
</select><br><br>
<b>From Date:</b>
<input type="date" id="fromdate" name="fromdate" value="<?php if(isset($fromdate)) echo $fromdate;?>" size="20" />
<b>To Date:</b>
<input type="date" id="todate" name="todate" value="<?php if(isset($todate)) echo $todate;?>" size="20"/><br><br>
<b>From Time:</b>
<input type="time" id="fromtime" name="fromtime" value="<?php if(isset($fromtime))echo $fromtime;?>" size="30" />
<b>To Time:</b>
<input type="time" id="totime" name="totime" value="<?php if(isset($totime)) echo $totime;?>" size="30"/><br><br>
<input type="submit" id="submit" name="submit" value="GENERATE"/> <input type="reset" id="reset" name="reset" value="RESET"/><br><br>
</div>
</body>
</html>
<?php
if(isset($_POST["submit"]))
{
$fromdate=$_POST['fromdate'];
$todate=$_POST['todate'];
$fromtime=$_POST['fromtime'];
$totime=$_POST['totime'];
if(!$fromdate || !$todate ||!$fromtime||!$totime)
echo " please provide all the fields";
global $conn;
// Create connection
$conn = mysqli_connect('localhost', 'root', '','test');
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
$sql ="SELECT * FROM floattable WHERE TagIndex=$tagindex AND (DateAndTime between '$fromdate .' '. $fromtime' AND '$todate .' '. $totime') ORDER BY DateAndTime ASC;";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
function fill_data($tagindex)
try{
function fill_data($tagindex)
{//for IP
if (($tagindex=0)||($tagindex=1)||($tagindex=2)||($tagindex=3)||($tagindex=4)||($tagindex=5)||($tagindex=6)||($tagindex=7)||($tagindex=8)||($tagindex=10)||($tagindex=11)||($tagindex=12)||($tagindex=13)||($tagindex=14)||($tagindex=14)||($tagindex=15)||
($tagindex=16)||($tagindex=17)||($tagindex=18)||($tagindex=19)||($tagindex=20)||($tagindex=21)||($tagindex=22)||($tagindex=23)||($tagindex=24)||($tagindex=25)||($tagindex=26)||($tagindex=27)||($tagindex=28)||($tagindex=29)||($tagindex=30)||($tagindex=31)||($tagindex=32)||
($tagindex=33)||($tagindex=34)||($tagindex=35)||($tagindex=36)||($tagindex=37)||($tagindex=38)||($tagindex=39)||($tagindex=40)||($tagindex=41)||($tagindex=42)||($tagindex=43)||($tagindex=44)||($tagindex=45)||($tagindex=46)||($tagindex=47)||($tagindex=48)||($tagindex=49))
{
// to display output
echo "<table border='1' cellspacing='3' align='centre'>
<tr>
<th>DateAndTime</th>
<th>Millitm</th>
<th>TagIndex</th>
<th>Value</th>
<th>Status</th>
<th>Market</th>
</tr>";
while ($row = mysqli_fetch_array($result))
{
echo " <tr>
<td>".$row['DateAndTime']."</td>
<td>".$row['Millitm']."</td>
<td>".$row['TagIndex']."</td>
<td>".$row['Val']."</td>
<td>".$row['Status']."</td>
<td>".$row['Marker']."</td>
</tr>";
}
echo "</table>";
}
}
}
catch (Exception $e)
{
echo $e->getmessage();
exit(1);
}
if(isset($_POST['submit']))
{
$selected_val = $_POST['AI-Types'];
try{
$currentSheet = "DTP4";
fill_data(0);
fill_data(1);
fill_data(2);
$currentSheet = "FT1";
fill_data(3);
$currentSheet = "FT2";
fill_data(4);
$currentSheet = "FT3";
fill_data(5);
fill_data(6);
$currentSheet = "LT1";
fill_data(7);
$currentSheet = "LT2";
fill_data(8);
fill_data(9);
$currentSheet = "PT1";
fill_data(10);
$currentSheet = "PT2";
fill_data(11);
fill_data(12);
fill_data(13);
fill_data(14);
$currentSheet = "PT3";
fill_data(15);
fill_data(16);
$currentSheet = "TE1";
fill_data(17);
fill_data(18);
fill_data(19);
$currentSheet = "TE2";
fill_data(20);
fill_data(21);
fill_data(22);
fill_data(23);
$currentSheet = "TE4";
fill_data(24);
fill_data(25);
fill_data(26);
fill_data(27);
fill_data(28);
fill_data(29);
$currentSheet = "VFD";
fill_data(30);
fill_data(31);
fill_data(32);
fill_data(33);
fill_data(34);
fill_data(35);
fill_data(36);
$currentSheet = "XT3";
fill_data(37);
fill_data(38);
$currentSheet = "XT4";
fill_data(39);
$currentSheet = "PT2";
fill_data(40);
}
catch (Exception $e)
{
echo $e->getmessage();
exit(1);
}
}
mysqli_close($conn);
}
?>
but the issue is that in floattable tagindexes are in 0-81 indexes and I want to get all records which are having their tagindex eg. 1 but conditions are like I have to sort data according to tagnames from tag table eg.DTP4_xxxx/IP(its a tagname).I have written a method fill_data($tagindex).
I am new at PHP.plz help me.Thanks in advance
Try this..
$date="2012-12-25";
$time="00:00:00";
$date1="2012-12-25";
$time1="23:59:59";
$firstdatetime=$date." ".$time;
$seconddatetime=$date1." ".$time1;
$data=mysql_query("SELECT * FROM floattable
WHERE DateAndTime BETWEEN '$firstdatetime AND '$seconddatetime'");

function running in foreach loop

thank you for taking time to look at this. I have been dealing with this annoying foreach loop. Here is what I am trying to do.
I have the first page "form.php".
On this page I have check boxes. Each check box is generated from a database table. Here is the code:
<?php
include("config.php");
$mysqli = new mysqli($host, $db_uname, $db_pass, $db);
$query = "SELECT * FROM `plugins` WHERE 1";
if ($result = $mysqli->query($query)) {
echo '<form action="test.php" method="post">
<input name="gname" placeholder="Group Name..."/>
<table width="200">
';
while ($row = $result->fetch_assoc()) {
echo '<tr><td>
<label>
<input type="checkbox" value="'.$row["plugin"].'" name="checkbox[]">
'.$row["plugin"].'
</label>
</td></tr>';
}
echo '
</table>
<select name="permplugin">
<option>Select One...</option>';
$query2 = "SELECT * FROM `permission_types` WHERE 1";
if ($result2 = $mysqli->query($query2)) {
echo '<h3>Select Permission format below</h3><hr />';
while ($row2 = $result2->fetch_assoc()) {
echo '
<option value="'.$row2["plugin_name"].'">'.$row2["plugin_name"].'</option>';
}
echo '
</select>
<br />
<input name="" type="reset"><input name="" type="submit">
</form>';
}
}
?>
Now after that it sends the checked boxes to "test.php"
here is the code for that:
<?php
if(!empty($_POST['checkbox']) || !empty($_POST['select']) || !empty($_POST['gname'])) {
echo '<h1>'.$_POST['gname'].'</h1>';
$check1 = $_POST['checkbox'];
foreach($check1 as $check) {
include "functions.php";
checkboxes($check);
}
echo '<h3>Selected Permission format below</h3><hr />';
echo $_POST['permplugin'];
} else {
echo "please select atleast one plugin.";
}
?>
The functions page code looks like this:
<?php
//all functions are here.
function checkboxes($check){
$mysqli_perm = new mysqli("localhost", "uname", "pword", "tcordero_permnodes");
$query_perm = "SELECT * FROM permission_nodes WHERE plugin = `$check`";
if ($result_perm = $mysqli_perm->query($query_perm)) {
echo $check;
/* fetch associative array */
while ($row_perm = $result_perm->fetch_assoc()) {
echo $row_perm['node'].'<br />';
}
unset($check);
}
}
When I run the test.php I get this error:
Fatal error: Cannot redeclare checkboxes() (previously declared in C:\xampp\htdocs\TPYC\functions.php:3) in C:\xampp\htdocs\TPYC\functions.php on line 15
What am I doing wrong?
You need to take the include out of the foreach loop. Try this:
include "functions.php";
foreach($check1 as $check) {
checkboxes($check);
}

HREF link calls out php function [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have two files. index.php and cart.php. All my functions, connection to database, etc. are located at file cart.php. There are functions that I want to call out if user clicks on a HREF link.
my index.php:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<div id="wrapper" align="center" style="width:90%; height:auto; margin-left:auto; margin-right:auto;">
<?php cart(); ?>
<br><br>
<div id="sidebar" align="left" style="width:15%; height:auto; background-color:#999999; float:left;">
<ul style="list-style-type:none;">
<li>ALL</li>
<li>SHIRTS</li>
<li>HOODIES</li>
</ul>
</div>
<div id="products" style="width:85%; height:auto; background-color:#888888; float:left;">
<?php
products_all();
?>
</div>
</div>
</body>
</html>
Then, How can I make that a HREF link calls out a specific function(which is located in cart.php) and displays it inside a div tag(in my case, in div id="products")?
It's probably easy, I am just a beginner.
Here's my cart.php just in case.
<?php
session_start();
$page = 'index.php';
// ***
/*
$mysql_host = "***";
$mysql_database = "***";
$mysql_user = "***";
$mysql_password = "***";
*/
// localhost
$mysql_host = "localhost";
$mysql_database = "cartt";
$mysql_user = "root";
$mysql_password = "";
mysql_connect($mysql_host, $mysql_user, $mysql_password) or die(mysql_error());
mysql_select_db($mysql_database) or die(mysql_error());
if (isset($_GET['add'])) {
$quantity = mysql_query('SELECT id, quantity FROM products WHERE id='.mysql_real_escape_string((int)$_GET['add']));
while ($quantity_row = mysql_fetch_assoc($quantity)) {
if ($quantity_row['quantity']!=$_SESSION['cart_'.(int)$_GET['add']]) {
$_SESSION['cart_'.(int)$_GET['add']]+='1';
}
}
header('Location: '.$page);
}
if (isset($_GET['remove'])) {
$_SESSION['cart_'.(int)$_GET['remove']]--;
header('Location: '.$page);
}
if (isset($_GET['delete'])) {
$_SESSION['cart_'.(int)$_GET['delete']]='0';
header('Location: '.$page);
}
function products_all() {
$get_all = mysql_query('SELECT id, name, description, price FROM products ORDER BY id DESC');
if (mysql_num_rows($get_all)==0) {
echo "There are no products to display!";
}
else {
echo '<table width="900px" allign="center" cellpadding ="5" style="background-color:transparent;">
<tr align="center" valign="middle">';
$i = 0;
while ($get_row = mysql_fetch_assoc($get_all)) {
echo '<td><img src="./cartimages/'.$get_row['id'].'.jpeg" alt=" " height="225px" align="center"><br />'.$get_row['name'].'<br />'.$get_row['description'].'<br />&pound'.number_format($get_row['price'], 2).'<br />Add</td>';
$i++;
if ($i == 4) {
echo '</tr>
<tr align="center" valign="middle">';
$i = 0;
}
}
}
}
function products_shirts() {
$get_shirts = mysql_query('SELECT id, name, description, price FROM products WHERE type = "shirt" ORDER BY id DESC');
if (mysql_num_rows($get_shirts)==0) {
echo "There are no products to display!";
}
else {
echo '<table width="900px" allign="center" cellpadding ="5" style="background-color:transparent;">
<tr align="center" valign="middle">';
$i = 0;
while ($get_row = mysql_fetch_assoc($get_shirts)) {
echo '<td><img src="./cartimages/'.$get_row['id'].'.jpeg" alt=" " height="225px" align="center"><br />'.$get_row['name'].'<br />'.$get_row['description'].'<br />&pound'.number_format($get_row['price'], 2).'<br />Add</td>';
$i++;
if ($i == 4) {
echo '</tr>
<tr align="center" valign="middle">';
$i = 0;
}
}
}
}
function products_hoodies() {
$get_hoodies = mysql_query('SELECT id, name, description, price FROM products where type = "hoodie" ORDER BY id DESC');
if (mysql_num_rows($get_hoodies)==0) {
echo "There are no products to display!";
}
else {
echo '<table width="900px" allign="center" cellpadding ="5" style="background-color:transparent;">
<tr align="center" valign="middle">';
$i = 0;
while ($get_row = mysql_fetch_assoc($get_hoodies)) {
echo '<td><img src="./cartimages/'.$get_row['id'].'.jpeg" alt=" " height="225px" align="center"><br />'.$get_row['name'].'<br />'.$get_row['description'].'<br />&pound'.number_format($get_row['price'], 2).'<br />Add</td>';
$i++;
if ($i == 4) {
echo '</tr>
<tr align="center" valign="middle">';
$i = 0;
}
}
}
}
function paypal_items() {
$num = 0;
foreach($_SESSION as $name => $value) {
if ($value!=0) {
if (substr($name, 0 , 5)=='cart_') {
$id = substr($name, 5, strlen($name)-5);
$get = mysql_query('SELECT id, name, price, shipping FROM products WHERE id='.mysql_real_escape_string((int)$id));
while ($get_row = mysql_fetch_assoc($get)) {
$num++;
echo '<input type="hidden" name="item_number_'.$num.'" value="'.$id.'">';
echo '<input type="hidden" name="item_name_'.$num.'" value="'.$get_row['name'].'">';
echo '<input type="hidden" name="amount_'.$num.'" value="'.$get_row['price'].'">';
echo '<input type="hidden" name="shipping_'.$num.'" value="'.$get_row['shipping'].'">';
// echo '<input type="hidden" name="shipping2_'.$num.'" value="'.$get_row['shipping'].'">';
echo '<input type="hidden" name="quantity_'.$num.'" value="'.$value.'">';
}
}
}
}
}
function cart() {
$total = 0;
foreach($_SESSION as $name => $value) {
if ($value>0) {
if (substr($name, 0, 5)=='cart_') {
$id = substr($name, 5, (strlen($name)-5));
$get = mysql_query('SELECT id, name, price FROM products WHERE id='.mysql_real_escape_string((int)$id));
while ($get_row = mysql_fetch_array($get)) {
$sub = $get_row['price']*$value;
echo $get_row['name'].' x '.$value.' # £'.number_format($get_row['price'], 2).' = £'.number_format($sub, 2).'[-] [+] [Delete]<br />';
}
}
$total += $sub;
}
}
if ($total==0) {
echo "Your cart is empty.";
}
else {
echo '<p>Total: £'.number_format($total, 2).'</p>';
?>
<p>
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="upload" value="1">
<input type="hidden" name="business" value="*************">
<?php paypal_items(); ?>
<input type="hidden" name="currency_code" value="GBP">
<input type="hidden" name="amount" value="<?php echo $total; ?>">
<input type="image" src="http://www.paypal.com/en_US/i/btn/x-click-but03.gif" name="submit" alt="Make payments with PayPal - it's fast, free and secure!">
</form>
</p>
<?php
}
}
?>
If you want a php function to run when you do something on the client, you have to make an AJAX request that calls that function, then you insert the HTML dynamically when your AJAX request returns.
Remember that PHP only generates text that is sent over the wire as HTML,CSS,JavaScript,JSON, XML,... There is no way for PHP to interact directly with your page, it can only generate new content
Here's a basic AJAX example you could use; I'll use jQuery and some simplified PHP code
ajax.php
function doit() { echo "anything"; }
doit();
page.html
Load stuff
<div id="products"></div>
page.js
$("#mylink").click(function() {
$('#products').load("/ajax.php");
})
That code loads the result of doit in ajax.php into the div with id "products" when you click on the link with ID "page.html"
http://api.jquery.com/load/
You need to use client-side javascript AJAX. Look up and read about AJAX requests.
Once you know AJAX works, you could call cart.php?runcommand=xyz on the click button and in cart.php you could check if $_GET['runcommand'] == 'xyz' then do x. You'll find jQuery javascript library has good AJAX support.
Preferably you would not having everything in one php file, then you can just make AJAX request to different files for different purposes. In your case, listproducts.php, for example.
I think you are looking for something like this:
<script type="text/javascript" language="javascript">
function showHide() {
var ele = document.getElementById("showHideDiv");
if(ele.style.display == "block") {
ele.style.display = "none";
}
else {
ele.style.display = "block";
}
}
</script>
<form method="post" action="">
<p><input type="button" value="Show-Hide" onclick="return showHide();" /></p>
</form>
<div id="showHideDiv" style="display:none;">hello!</div>

Categories