Im in this page: website.php?page=5 and in this page I have this form:
<form method="POST" action="website.php?page=<?php echo $pagenumber; ?>">
<input type="text" name="goto" />
<input type="submit" name="submit" value="goto" />
</form>
If I write something like 3 into the text field and press the goto button (if isset.... my php code get the number and upload into the $pagenumber var)
But the new page isn't the website.php?page=3 what I want. The new page is website.php?page= (there is no number) .and if I press again then goes it to the right page.
I think in the first press when i do the $pagenumber isn't declared. Only when i press second.
How can I fix it? I must use this way i cant use session, cookie etc.
<?php if(isset($_POST['submit']))
{
$kitkeresek = $_POST['goto'];
$becsuletemw = "SELECT * FROM adatok WHERE nev = '$kitkeresek'";
$becsuletem2w = mysql_query($becsuletemw);
while( $becsuletem3w = mysql_fetch_array($becsuletem2w))
$becsuletemw = $becsuletem3w["becsulet"];
$valllamiw = mysql_query("SELECT becsulet FROM adatok WHERE becsulet > '$becsuletemw' ");
$rowsw = mysql_num_rows( $valllamiw );
$kitkeresekw = $rowsw + 1 ;
$intvizsgalat= $kitkeresekw/10;
if (is_int($intvizsgalat))
{ $pagenumber = $intvizsgalat - 1 ; }
else
{$pagenumber = floor($kitkeresekw/10); } ;
}
?>
When you do this :
$intvizsgalat= $kitkeresekw/10;
$intvizsgalat is float, even if the result is int, because it is the result of a division.
You can try var_dump($intvizsgalat) to confirm
try something like this:
$floatParts = $intvizsgalat - floor(intvizsgalat);
if ($floatParts == 0) {
//
} else {
//
}
Related
Consider this markup:
<?php
$drill = 0;
$result = '';
$dynamicD = rand(5,15);
$num01 = $dynamicD-4;
$placeholder = $num01.'+4';
if($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["drill"])){
$humanErr = "Empty";
}
else {
$drill = $_POST["drill"];
if($drill !== $dynamicD) {
$result = "No";
}
else {
$result = "Yes";
}
};
};
?>
<!doctype html>
<html>
<body>
<p>Correct Answer: <?php echo $dynamicD ?></p>
<p>Does this work? <?php echo "$result";?></p>
<form method="post">
<fieldset>
<label for="drill">Can you solve it?</label>
<input type="text" name="drill" id="drill" maxlengh="2" placeholder="<?php echo $placeholder ?>" required="true" />
</fieldset>
<button type="submit" name="check">Check</button>
</form>
</body>
</html>
Basically it generates "random" number, insert it as a drill, and then let the user submit his answer. The problem is that the answer is always "NO"*.
I tried to separate the condition to this:
if($drill > $dynamicD) { $result = "bigger" }
elseif ($drill < $dynamicD) { $result = "smaller" }
and so on - but can't understand the logic of the $result (sometime bigger, sometime smaller, but i ALWAYS enter $dynamicD...).
What am i doing wrong here???
EDIT:
As the comments points, every time the page submit it generates new numbers. The first time the code execute is the only time that correct answer would be equal to the numbers that display. After the first submit there is a gap.
Note for future readers: The above code extracted and simplified from bigger and much complex system. Not something that anyone would want to just copy-paste.
The solution i choose was to store the dynamically created vars on a session and re-declare if the answer is correct.
Would love to hear about other ways (not client side).
I am new at some things and I need help about my store page.
For each item you wanna add to the cart or remove from the cart, the page refreshs and it is really annoying if you wanna buy several items.
I have read that I could use AJAX, I have read a lot of methods and nothing worked for me.
What do I need to do in order to make it work?
These are my add / remove:
<form action="" method="post">
<input type="hidden" name="item_id" value="{sid}">
<input type="hidden" name="parent" value="{parent_category}">
<input type="submit" name="atc" value="Añadir" class="sub-link">
</form>
<form action="" method="post">
<input type="hidden" name="item_id" value="{cid}">
<input type="hidden" name="parent" value="{parent_category}">
<input type="submit" name="rfc" value="Remover" class="sub-link">
</form>
And this is the function handling the submit:
function add_to_cart() {
global $db, $db_data, $db_acc, $login;
if (!empty($_POST['atc']) || !empty($_POST['rfc'])
&& isset($_GET['page']) && isset($_GET['data'])
&& $_GET['page'] == "store_shop") {
$data = $_GET['data'];
$pos = strpos($data, "-");
if ($pos == TRUE) {
$ndt = explode("-", $data);
$d1 = clean($ndt[0]);
$d2 = clean($ndt[1]);
if ($d1 == FALSE) {
$d1 = 0;
}
} else {
$d1 = 0;
$d2 = 0;
}
$sqli = $db->query("SELECT id, rname, char_db FROM $db_data.realms WHERE id='$d1'");
$numi = $db->num($sqli);
$geti = $db->get($sqli);
$cdb = $geti['char_db'];
$sqla = $db->query("SELECT id, username FROM $db_acc.account WHERE username='$login'");
$geta = $db->get($sqla);
$acid = $geta['id'];
if ($numi == 1) {
$sqlc = $db->query("SELECT guid, account, name FROM $cdb.characters WHERE account='$acid' AND guid='$d2'");
$numc = $db->num($sqlc);
$getc = $db->get($sqlc);
if ($numc == 1) {
$item = clean($_POST['item_id']);
$parent = clean($_POST['parent']);
if (!empty($_POST['atc'])) {
$sqll = $db->query("INSERT INTO $db_data.cart (`realm`, `account`, `character`, `item`, `parent`) VALUES ('$d1', '$acid', '$d2', '$item', '$parent')");
} else if (!empty($_POST['rfc'])) {
$sqll = $db->query("DELETE FROM $db_data.cart WHERE id='$item'");
}
header("Location: ?page=store_shop&data={$data}");
} else {
header("Location: ?page=store_shop&data={$data}");
}
} else {
header("Location: ?page=store_shop&data={$data}");
}
}
}
Edit: I think I am missing some details:
After clicking "add" ("Añadir" in Spanish) o "remove" ("Remover" in Spanish), the page reloads and the item is added to the cart div.
When I try the solutions I have read in stackoverflow or in other website, most of them does not work for my store and the only thing I can get is to prevent the page from reloading but the cart does not update.
Maybe should I use a iframe in the cart div?
I am still reading about ajax but I can not get it by myself.
Try this out
Remove the submit button and call the function Add to cart and same for Remove from cart using onclick="addtocart()" in anchor tag
function addtocart(){
get 'sid' and 'parent' value from anchor tag using jquery
$.ajax({
type: 'POST',
url: '/cart/add.php',
data:{ 'sid':sid, 'parent':parent }
success : function(data) { alert('success'); }
});
}
This is a form when generally causes a page load unless the default onsubmit action is overridden and the override function causes a stopPropagation on the event object. AJAX requires JS in which an XMLHttpRequest object is created (or ActiveX for IE) and communicates with server without a refresh by default ( although it can be done programatically). Then your server could return JSON for example or some indicator as to whether the call was successful and erroneous and the client side can handle it accordingly
I have a single page php application to generate an 8 digit number, user inputs a value and page generates another value, both values are inserted into mysql db and displaying the generated value in an input box at a single button click. Insertion is happening, but generated value is not displaying in the inputbox at the first time, I also tried session its not helping too.
here is my php code,
<?php
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<div>
<?php
if(isset($_POST['luckyButton']) && $_POST['myLuckyNumber'] != ""){
//sleep(20);
$myLuckyNum = $_POST['myLuckyNumber'];
$resultmyLuckyNum = mysql_query("SELECT * FROM lucky where luckyNum='$myLuckyNum'") or die(mysql_error());
if (mysql_num_rows($resultmyLuckyNum) > 0) {
while ($rowmyLuckyNum = mysql_fetch_array($resultmyLuckyNum)) {
$generatedNumber = $rowmyLuckyNum["generatedNum"];
}
}else{
$gen = getGen();
$resultGenNum = mysql_query("INSERT INTO lucky (slno, luckyNum, generatedNum) VALUES ( NULL, '$myLuckyNum', '$gen')");
if (mysql_num_rows($resultGenNum) > 0) {
$generatedNumber = $gen;
}
}
}
?>
<form action="" method="post">
<input type="text"class="inputs" name="myLuckyNumber" onClick="this.select();" placeholder="Enter You Lucky Number" value="<?php echo $myLuckyNum; ?>" />
<input type="submit" class="css_button" name="luckyButton" value="Check"/>
</form>
</div>
<br><br><br>
<?php
if($generatedNumber != ""){
echo '<input type="text" name="myLuckyNumber" onClick="this.select();" id="generatedNumber" readonly="true" value="' . $generatedNumber . '" />';
}
echo '<p id="errText"> ' . $err . ' </p>';
function random_string($length) {
$key = '';
$keys = array_merge(range(0, 9));
for ($i = 0; $i < $length; $i++) {
$key .= $keys[array_rand($keys)];
}
return $key;
}
function getGen(){
$gen1 = random_string(8);
$result = mysql_query("SELECT * FROM lucky where generatedNum='$gen1'") or die(mysql_error());
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
if($row["generatedNum"] == $gen1){
getGen();
}
}
}else{
//echo $gen1;
return($gen1);
}
}
?>
</body>
</html>
my table,.
CREATE TABLE `lucky` (
`slno` int(11) NOT NULL,
`luckyNum` text NOT NULL,
`generatedNum` text NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
The problem with your code is that mysql_num_rows will return either 0 or 1, use it like
if($resultGenNum === 1){
$generatedNumber = $gen;
}
You are using mysql_num_rows in a wrong way. When you run insert query, it does not return rows, it returns true or false (Boolean). When it will return true, you will get 1 (as $resultGenNum).
use this instead:
if ($resultGenNum === 1){
$generatedNumber = $gen;
}
Instead of using if ( $generatedNumber != "" ), perhaps you should try something like if ( isset( $generatedNumber ) ).
If $generatedNumber doesn't exist (which it doesn't if nothing was posted to the script), then the comparison will fail (in fact, you're probably getting a PHP error).
Of course, that leads us to the next problem - if nothing is posted to the script, you don't generate a number. So of course, if you don't generate a number, there is no number to display. So you should structure your code in such a way that a random number is always generated - regardless of whether a post variable was received or not.
I want to get the introducer5 code for the employee code from that introducer5 code need to get the introducer4 code who introduce introducer4 like wise i want to get all their codes.
I have 7 levels of employee: 1) xxxx-7000
2) yyyy-6000
3)....
7) eeee -1000
<?php
if(isset($_POST['submit'])){
$introducer_code=$_POST['intro_code'];
function getOneLevel($intro_code)
{
$get_intro_code="SELECT * FROM `emp_details` WHERE `emp_code` = '".$intro_code."' ";
// echo $get_intro_code."</br>";
$exe_code=mysql_query($get_intro_code);
//$introducer_code=array();
$rows=mysql_num_rows($exe_code);
// echo $rows;
if($rows>0)
{
$get_role=mysql_fetch_array($exe_code);
$introducer_code= $get_role['intro_code'];
$compare_role1=" SELECT * FROM emp_details WHERE `emp_code` = '".$introducer_code."' ";
// echo $compare_role1."</br>";
$exe_role1=mysql_query($compare_role1);
$get_pos1=mysql_fetch_array($exe_role1);
//echo $get_pos1['emp_role'];
if($row_c=mysql_num_rows($exe_role1) > 0){
$compare_role="SELECT * FROM user_role WHERE `emp_role_id` = '".$get_pos1['emp_role']."' ";
echo $compare_role."</br>";
$exe_role=mysql_query($compare_role);
$get_pos=mysql_fetch_array($exe_role);
$id=$get_pos['id'];
}
}
$res=$id.','.$introducer_code;
echo $res."</br>";
return $res;
}
$compare_role2="SELECT * FROM emp_details WHERE `intro_code` = '".$introducer_code."'";
// echo $compare_role2 ."</br>";
$exe_role2=mysql_query($compare_role2);
if (mysql_num_rows($exe_role2)>0) {
//$n=7;
while ($get_pos=mysql_fetch_array($exe_role2)) {
//echo $get_pos['emp_code'];
// $c=$n-$id;
/* for($i=0;$i<$c;$i++){
echo "hi";*/
getOneLevel($get_pos['emp_code']);
// }
}
}
getOneLevel($introducer_code);
}
?>
<form method="post">
<div class="form-group">
<label>Introducer Code</label>
<input type="text" placeholder="Enter Introducer Code" id="intro_code" required="required" name="intro_code" class="form-control" />
</div>
<button value="Submit" type="submit" name="submit" >Submit</button>
</form>
The above code only returns the immediate introducer4 code for the value entered in the text box.It does not returning the introducer3 code who refers introducer4 and so on...
Please Help!!
Struggling more than 4 days!!
Try this may be useful
function getIntroducer($intro_code)
{
//Write your code to get introudcer and return it's Interducer id only
return $introudcer;
}
$finalInterducer = $intro_code //start
for($i=0;$i<5;$i++){ // If its 7 loop 7 time's
$finalInterducer = getIntroducer($finalInterducer)
}
//After loop you get last finalInterducer
Change the SQL Query, try this:
SELECT ED4.emp_code AS 'introducer4',
ED3.emp_code AS 'introducer3',
ED2.emp_code AS 'introducer2',
ED1.emp_code AS 'introducer1'
FROM emp_details ED1,emp_details ED2,emp_details ED3,emp_details ED4
WHERE ED4.emp_code = '".$introducer_code."'
AND ED3.emp_code = ED4.intro_code
AND ED2.emp_code = ED3.intro_code
AND ED1.emp_code = ED2.intro_code
All the best :)
I have a script wher users can find exercise from a database, I have checkboxes for the user to find specific exercises the script works fine when a least 1 checkbox is selected from each checkbox group however I would like it that if no checkboxes was selected then it would the results of all checkboxes.
my checkbox form looks like this
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="criteria">
<p><strong>MUSCLE GROUP</strong></p>
<input type="checkbox" name="muscle[]" id="abdominals" value="abdominals"/>Abdominals<br />
<input type="checkbox" name="muscle[]" id="biceps" value="biceps" />Biceps<br />
<input type="checkbox" name="muscle[]" id="calves" value="calves" />Calves<br />
ect...
<br /><p><strong>EQUIPMENT (please select a least one)</strong></p>
<input type="checkbox" name="equipment[]" id="equipment" value="bands"/>Bands<br />
<input type="checkbox" name="equipment[]" id="equipment" value="barbell" />Barbell<br />
<input type="checkbox" name="equipment[]" id="equipment" value="dumbbell" />Dumbbell<br />
ect....
<input type="submit" name="sub" value="Generate Query" />
</form>
and here is my script
<?php
if(isset($_POST['muscle']) && !empty($_POST['muscle'])){
if(isset($_POST['equipment']) && !empty($_POST['equipment'])){
//get the function
include ($_SERVER['DOCUMENT_ROOT'] .'/scripts/functions.php');
$page = (int) (!isset($_GET["page"]) ? 1 : $_GET["page"]);
$limit = 14;
$startpoint = ($page * $limit) - $limit;
// Runs mysql_real_escape_string() on every value encountered.
$clean_muscle = array_map('mysql_real_escape_string', $_REQUEST['muscle']);
$clean_equipment = array_map('mysql_real_escape_string', $_REQUEST['equipment']);
// Convert the array into a string.
$muscle = implode("','", $clean_muscle);
$equipment = implode("','", $clean_equipment);
$options = array();
if(array($muscle))
{
$options[] = "muscle IN ('$muscle')";
}
if(array($equipment))
{
$options[] = "equipment IN ('$equipment')";
}
$fullsearch = implode(' AND ', $options);
$statement = "mytable";
if ($fullsearch <> '') {
$statement .= " WHERE " . $fullsearch;
}
if(!$query=mysql_query("SELECT * FROM {$statement} LIMIT {$startpoint} , {$limit}"))
{
echo "Cannot parse query";
}
elseif(mysql_num_rows($query) == 0) {
echo "No records found";
}
else {
echo "";
while($row = mysql_fetch_assoc($query)) {
echo "".$row['name'] ."</br>
".$row['description'] ."";
}
}
echo "<div class=\"new-pagination\">";
echo pagination($statement,$limit,$page);
echo "</div>";
}
}
Im new with php so my code may not be the best. If anyone can help me or point me in the right direction I would be very greatful.
OK - I think I have figured it all out. You were right - the main problem was in your isset and isempty calls. I created some variations on your file, and this shows what is going on. Note - since I don't have some of your "other" functions, I am only showing what is going wrong in the outer parts of your function.
Part 1: validating function
In the following code, I have added two JavaScript functions to the input form; these were loosely based on scripts you can find when you google "JavaScript validation checkbox". The oneBoxSet(groupName) function will look through all document elements; find the ones of type checkBox, see if one of them is checked, and if so, confirms that it belongs to groupName. For now, it returns "true" or "false". The calling function, validateMe(formName), runs your validation. It is called by adding
onclick="validateMe('criteria'); return false;"
to the code of the submit button. This basically says "call this function with this parameter to validate the form". In this case the function "fixes" the data and submits; but you could imagine that it returns "false", in which case the submit action will be canceled.
In the validateMe function we check whether at least one box is checked in each group; if it is not, then a hidden box in the "all[]" group is set accordingly.
I changed the code a little bit - it calls a different script (muscle.php) instead of the <?php echo $_SERVER['PHP_SELF']; ?> you had... obviously the principle is the same.
After this initial code we will look at some stuff I added in muscle.php to confirm what your original problem was.
<html>
<head>
<script type="text/javascript">
// go through all checkboxes; see if at least one with name 'groupName' is set
// if so, return true; otherwise return false
function oneBoxSet(groupName)
{
var c=document.getElementsByTagName('input');
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].checked) {
if (c[i].name == groupName) {
return true; // at least one box in this group is checked
}
}
}
}
return false; // never found a good checkbox
}
function setAllBoxes(groupName, TF)
{
// set the 'checked' property of all inputs in this group to 'TF' (true or false)
var c=document.getElementsByTagName('input');
// alert("setting all boxes for " + groupName + " to " + TF);
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].name == groupName) {
c[i].checked = TF;
}
}
}
return 0;
}
// this function is run when submit is pressed:
function validateMe(formName) {
if (oneBoxSet('muscle[]')) {
document.getElementById("allMuscles").value = "selectedMuscles";
//alert("muscle OK!");
}
else {
document.getElementById("allMuscles").value = "allMuscles";
// and/or insert code that sets all boxes in this group:
setAllBoxes('muscle[]', true);
alert("No muscle group was selected - has been set to ALL");
}
if (oneBoxSet('equipment[]')) {
document.getElementById("allEquipment").value = "selectedEquipment";
//alert("equipment OK!");
}
else {
document.getElementById("allEquipment").value = "allEquipment";
// instead, you could insert code here that sets all boxes in this category to true
setAllBoxes('equipment[]', true);
alert("No equipment was selected - has been set to ALL");
}
// submit the form - function never returns
document.forms[formName].submit();
}
</script>
</head>
<body>
<form action="muscle.php" method="post" name="criteria">
<p><strong>MUSCLE GROUP</strong></p>
<input type="checkbox" name="muscle[]" id="abdominals" value="abdominals"/>Abdominals<br />
<input type="checkbox" name="muscle[]" id="biceps" value="biceps" />Biceps<br />
<input type="checkbox" name="muscle[]" id="calves" value="calves" />Calves<br />
<input type="hidden" name="all[]" id="allMuscles" value="selectedMuscles" />
etc...<br>
<br /><p><strong>EQUIPMENT (please select a least one)</strong></p>
<input type="checkbox" name="equipment[]" id="equipment" value="bands"/>Bands<br />
<input type="checkbox" name="equipment[]" id="equipment" value="barbell" />Barbell<br />
<input type="checkbox" name="equipment[]" id="equipment" value="dumbbell" />Dumbbell<br />
<input type="hidden" name="all[]" id="allEquipment" value="selectedEquipment" />
<br>
<input type="submit" name="sub" value="Generate Query" onclick="validateMe('criteria'); return false;" />
</form>
</body>
</html>
Part 2: what's wrong with the PHP?
Now here is a new start to the php script. It checks the conditions that you were testing at the start of your original script, and demonstrates that you never get past the initial if statements if a check box wasn't set in one of the groups. I suggest that you leave these tests out altogether, and instead get inspiration from the code I wrote to fix any issues. For example, you can test whether equipmentAll or muscleAll were set, and create the appropriate query string accordingly.
<?php
echo 'file was called successfully<br><br>';
if(isset($_POST['muscle'])) {
echo "_POST[muscle] is set<br>";
print_r($_POST[muscle]);
echo "<br>";
if (!empty($_POST['muscle'])) {
echo "_POST[muscle] is not empty!<br>";
}
else {
echo "_POST[muscle] is empty!<br>";
}
}
else {
echo "_POST[muscle] is not set: it is empty!<br>";
}
if(isset($_POST['equipment'])) {
echo "_POST[equipment] is set<br>";
print_r($_POST['equipment']);
echo "<br>";
if (!empty($_POST['equipment'])) {
echo "_POST[equipment] is not empty!<br>";
}
else {
echo "_POST[equipment] is empty!<br>";
}
}
else {
echo "_POST[equipment] is not set: it is empty!<br>";
}
if(isset($_POST['all'])) {
echo "this is what you have to do:<br>";
print_r($_POST['all']);
echo "<br>";
}
// if(isset($_POST['muscle']) && !empty($_POST['muscle'])){
// if(isset($_POST['equipment']) && !empty($_POST['equipment'])){
If you call this with no check boxes selected, you get two dialogs ('not OK!'), then the following output:
file was called successfully
_POST[muscle] is not set: it is empty!
_POST[equipment] is not set: it is empty!
this is what you have to do:
Array ( [0] => allMuscles [1] => allEquipment )
If you select a couple of boxes in the first group, and none in the second:
file was called successfully
_POST[muscle] is set
Array ( [0] => abdominals [1] => calves )
_POST[muscle] is not empty!
_POST[equipment] is not set: it is empty!
this is what you have to do:
Array ( [0] => selectedMuscles [1] => allEquipment )
I do not claim to write beautiful code; but I hope this is functional, and gets you out of the fix you were in. Good luck!