I have a problem in my code. I post some field data for addsms.php file.
<form id="signup" Name="signup" method="post" action="addsms.php?act=add"> <h1>SMS Detail Here!</h1>
User Refrence Code:<input name="rfcd" type ="text" class="a" id="rfcd" placeholder="Enter Refrence Code" /><br>
Total SMS Count:     <input name="smsc" type ="text" class="a" id="smsc" placeholder="Enter SMS Count" /><br>
Total SMS Amount: <input name="amnt" type ="text" class="a" id="amnt" placeholder="Enter SMS Amount" /><br>
<input type ="submit" Name="submit" value="Submit" class="outset" />
</form>
addsms.php
<?php
require_once("./include/connect.php");
require_once("./include/fg_membersite.php");
if($_GET['act'] == 'add')
{
$rf_cd = $_POST['rfcd'];
$sms_c = $_POST['smsc'];
$am_nt = $_POST['amnt'];
// echo $rf_cd;
// exit;
//I can Get value of variable "$rf_cd" at above line. while not able to get value in any function,
if ($rf_cd == NULL || $sms_c == NULL || $am_nt == NULL )
{
header("Location:sms.php?field=miss");
}
else
if(checkref_id_from_user() == true && checkref_id_from_user_data() == true )
{
$get_detail = "select total_sms, total_sms_amount from user_data where ref_id = '$rf_cd'";
$res1 = Run($get_detail);
if(mysql_num_rows($res1) > 0){
while ($rows = mysql_fetch_object($res1)) {
$srn++;
$sms_oldcont = $rows->total_sms;
$sms_amnt_oldcont = $rows->total_sms_amount;
}
}
$inqry = "UPDATE user_data SET total_sms = '$sms_c' + '$sms_oldcont', total_sms_amount ='$am_nt'+ '$sms_amnt_oldcont' where ref_id = '$rf_cd' ";
$resinqry = Run($inqry);
if(!$resinqry)
{
echo $resinqry;
}
else
{
header("Location:sms.php?add=done");
}
}
else
if(checkref_id_from_user() == true && checkref_id_from_user_data() == false)
{
$inqry = "Insert into user_data (ref_id,total_sms,total_sms_amount) VALUES('$rf_cd','$sms_c','$am_nt')";
$resinqry = Run($inqry);
if(!$resinqry)
{
echo $resinqry;
}
else
{
header("Location:sms.php?add=done");
}
}
// if($result && mysql_num_rows($result) > 0 && )
else
{
header("Location:sms.php?refid=notavailable");
}
}
else
{
echo 'oh';
//header("Location:sms.php?refid=notavailable");
}
function checkref_id_from_user(){
$qry = "select ref_id from user where ref_id='".$rf_cd."'";
echo $qry;
$result = Run($qry);
echo $result;
exit;
if($result && mysql_num_rows($result) > 0)
{
return true;
}
return false;
}
function checkref_id_from_user_data()
{
$checkrefid = "select ref_id from user_data where ref_id = '$rf_cd'";
$res = Run($checkrefid);
if(mysql_num_rows($res) > 0)
{
return true;
}
return false;
}
?>
I can Get value of variable "$rf_cd" at any where in if condition. while not able to get value in any function, "$rf_cd" I wanna use this value in my functions to get info from database.
$checkrefid = "select ref_id from user_data where ref_id = '$rf_cd'";
echo $checkrefid;
exit
Above query shows the result that "Select ref_id from user_data where ref_id = '' ".
while this should show the value of variable $rf_cd.
Close your if statement } before your functions are read. And for good form, I always list functions at the top of my scripts.
You can just declare $rf_cd as argument of those functions and pass it when calling them (best solution).
Also you can use "global" keyword to get an access to a $rf_cd variable from global scope.
function checkref_id_from_user(){
global $rf_cd;
...
}
function checkref_id_from_user_data() {
global $rf_cd;
...
}
Have you tried using global in the function?
If you wish for a function to have access to passive variables, you need to define them.
fx
myFunction() {
global $LoggedUser, $OtherGlobalVars
}
Related
can anyone tell me why this code doesn't give me any records and display my "else" error message instead ? table which I'm trying to get data from( attached) uses two foreign keys ( emp number ,and project code) from two other tabels
( Please note I'm new to PHP )
$emp_no="";
$project_code="";
$p_hours="";
require_once 'connect.php';
function getposts()
{
$posts= array();
if (isset($_POST['EMPNo']))
{
$posts[0] = $_POST['EMPNo'];
}
if (isset($_POST['ProjectCode']))
{
$posts[1] = $_POST['ProjectCode'];
}
if (isset($_POST['Hours']))
{
$posts[2] = $_POST['Hours'];
}
return $posts;
}
if(isset($_POST['search']))
{
#$data = getposts();
#$searchquery = "SELECT * FROM `enrolment` WHERE `EMPNo`='$data[0]' AND
`ProjectCode`='$data[1]'";
#$search_Result =mysqli_query($connect, $searchquery);
if($search_Result)
{
if(mysqli_num_rows($search_Result))
{
while($raw = mysqli_fetch_array($search_Result))
{
$emp_no = $raw ['EMPNo'] ;
$project_code = $raw ['ProjectCode'] ;
$p_hours = $raw ['Hours'] ;
}
}else {
echo 'Unable to find the record please check input data!';
}
}else {
echo ' Result Error ';
}
}
//html part
<Form action="updateenrolment.php" method="post" style="color:blue;margin-
left:500px;">
<input type="text" name ="empno" placeholder="Employee No" value="<?php
echo $emp_no;?>"><br><br>
<input type="text" name ="pcode" placeholder="Project Code" value="<?php
echo $project_code;?>"><br><br>
<input type="number" name ="hours" placeholder="Hours" value="<?php echo
$p_hours;?>"><br><br>
<div>
<input type="submit" name ="search" value="Find" >
mysqli_fetch_array print the array result but you are fetching result using string element. you need to change this.
while($raw = mysqli_fetch_array($search_Result))
{
$emp_no = $raw [1] ;
$project_code = $raw [2] ;
$p_hours = $raw [3] ;
}
To replace it.
while($raw = mysqli_fetch_array($search_Result))
{
$emp_no = $raw ['EMPNo'] ;
$project_code = $raw ['ProjectCode'] ;
$p_hours = $raw ['Hours'] ;
}
I'm posting a select option from one page to another, on my actual server code (PHP), I'm wanting to firstly, get the POST name, for example, $_POST['selection_value'] and secondly, check if it's equal to a value from the selection, like : if($_POST['selection_value'] == 'time') {} . (time is the value of a selection option). How would I go about doing this ?
My code for the POST grab :
The markup
<div class="form-group" style="padding-left: 4%;">
<div class="form-group m-r-12">
<label class="col-sm-12 control-label";">Add User</label>
</div>
<input type="text" name="username" id="username" placeholder="Username" class="form-control" required />
<input type="text" name="email" id="email" placeholder="Email" class="form-control" required />
<input type="text" name="cpukey" id="cpukey" placeholder="CPUKey" class="form-control" required />
<button onclick="addUser()" class="btn btn-success"><i class="fa fa-user-plus"></i> Add User</button>
<select class="form-control" id="selection_value" name="selection_value">
<option value="account_credits">Account Credits</option>
<option value="free_gifted_credits">Free Gifted Credits</option>
<option value="time">Member Server Days</option>
</select>
<input type="text" name="add_to_all_value" id="add_to_all_value" placeholder="Value to add to current" class="form-control" required />
<button id="button1" onclick="add_to_all()" class="btn btn-primary"><i class="fa fa-user-plus"></i> Add To All Users</button>
The AJAX
function add_to_all() {
myOutput = document.getElementById('add_user_result');
var member_selection = $('#selection_value :selected').text()
var member_value = $('#add_to_all_value').val();
if(member_selection != "" & member_value != "") {
$.ajax ({
type: "POST",
url: 'includes/ajax_data_add_to_all.php',
data: { selection: member_selection, value: member_value },
success:function(response) {
$("#add_user_result").show();
$('#add_user_result').fadeOut(3000).html(response);
header('Location: admin_members.php');
},
error: function() {
$("#add_user_result").show();
$('#add_user_result').fadeOut(3000).html(response);
header('Location: admin_members.php');
}
});
} else {
$("#add_user_result").show();
$('#add_user_result').fadeIn(3000).fadeOut(3000);
myOutput.innerHTML = "<font style='color: red;'>You must fill in all the blanks.</font>";
}
return false;
}
Now my code for the add time (server code) :
function grab_all_time() {
global $con;
$usersTime = "SELECT time FROM users";
$result = $con->query($usersTime) or die("Error");
while ($row = mysqli_fetch_assoc($result)) {
return $row['time'];
}
}
$AllusersTime = grab_all_time();
if(!empty($_POST) && isset($_POST)) {
$selection = mysqli_real_escape_string($con, $_POST['selection']);
$value = mysqli_real_escape_string($con, $_POST['value']);
$membersDate = new DateTime($AllusersTime);
$membersDate->add(new DateInterval('P'.$value.'D'));
$finishedDT = $membersDate->format('Y-m-d') . "\n";
if($selection == 'Member Server Days') {
$insert_query = mysqli_query($con, "UPDATE users SET '".$selection."' + '".$value."'");
if($insert_query) {
echo '<font style="color: green;">Successfully Added to all users</font>';
echo '<META HTTP-EQUIV="Refresh" CONTENT="3; URL=admin_members.php">';
}
else {
echo '<font style="color: red;">Failed to add to all users</font>';
echo '<META HTTP-EQUIV="Refresh" CONTENT="3; URL=admin_members.php">';
}
} else {
$insert_query = mysqli_query($con, "UPDATE users SET time = '".$finishedDT."'");
if($insert_query) {
echo '<font style="color: green;">Successfully Added to all users</font>';
echo '<META HTTP-EQUIV="Refresh" CONTENT="3; URL=admin_members.php">';
}
else {
echo '<font style="color: red;">Failed to add to all users</font>';
echo '<META HTTP-EQUIV="Refresh" CONTENT="3; URL=admin_members.php">';
}
}
To return all records for the query in your function grab_all_time you could use an array, add each result to it and return that array:
function grab_all_time() {
global $con;
$usersTime = "SELECT time FROM users";
$result = $con->query($usersTime) or die("Error");
$results = array();
while( $row = mysqli_fetch_assoc($result) ) {
$results[]=$row['time'];
}
return $results;
}
That obviously returns an array so you can't simply assign the return value as a DateTime object which you later go on to do. If it is just the one result from the query you need to process then why fetch all rows?
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['selection'], $_POST['value'] ) ){
$selection = mysqli_real_escape_string( $con, $_POST['selection'] );
$value = mysqli_real_escape_string( $con, $_POST['value'] );
$AllusersTime = grab_all_time();
foreach( $AllusersTime as $i => $time ){
$membersDate = new DateTime( $time );
$membersDate->add( new DateInterval('P'.$value.'D') );
$finishedDT = $membersDate->format('Y-m-d') . "\n";
/* .... the rest of you code .... */
/* dont add the `meta refresh` */
}
}
Still a trifle confused with what you actually wish to do - hopefully I have understood correctly in that you wish to update each user's record according to values and options selected. To update each record individually using pre-existing content in each of their records using a where clause for the update statement would seem logical.
I think my confusion stems from the sql that retrieves data from the users table in your function. The way it was originally structured meant that despite selecting all records you returned only the first one in the recordset and used that as the basis for the remaining code. If, and I say IF, you intended to return ALL records and process them individually then returning an array from your function seems the best option.
You will note I modified ( again ) your function to also get the user_id associated with each record - substitute that for the correct column name.
function grab_all_time() {
global $con;
/* NOTE: assumed a column `user_id` !! */
$usersTime = "SELECT `user_id`,`time` FROM `users`;";
$result = $con->query($usersTime) or die("Error");
$results = array();
while( $row = mysqli_fetch_assoc($result) ) {
/* NOTE: assumed column `user_id` !! */
$results[ $row['user_id'] ]=$row['time'];
}
return $results;
}
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['selection'], $_POST['value'] ) ){
$selection = mysqli_real_escape_string( $con, $_POST['selection'] );
$value = mysqli_real_escape_string( $con, $_POST['value'] );
$AllusersTime = grab_all_time();
$results = array();
foreach( $AllusersTime as $user_id => $time ){
$membersDate = new DateTime( $time );
$membersDate->add( new DateInterval('P'.$value.'D') );
$finishedDT = $membersDate->format('Y-m-d');
/* .... the rest of you code .... */
if( $selection == 'Member Server Days' ) {
$sql='update `users` set `'.$selection.'`=`'.$selection.'` + '.$value.' where `user_id`="'.$user_id.'";';
} else {
$sql='update `users` set `time`="'.$finishedDT.'" where `user_id`="'.$user_id.'";';
}
$results[ $user_id ]=mysqli_query( $con, $sql ) ? 'Success' : 'Fail';
}
echo '<pre>',print_r( $results, true ),'</pre>';
echo '<META HTTP-EQUIV="Refresh" CONTENT="3; URL=admin_members.php">';
}
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 am having a rather strange issue and for the likes of me, cannot figure it out!
Basically, I have users who are allowed to upload documents, which are then associated with their profile.
If the user decides to delete a document, the only thing that gets deleted here, is the document, but not the content included, e.g. comments, title, etc - it's as if nothing ever happened - except of course - the physical document has been deleted - sql entries however have not.
mydocs.php:
if ($_SESSION['USERID'] != "" && $_SESSION['USERID'] >= 0 && is_numeric($_SESSION['USERID']))
{
if($_REQUEST['submitdelete']!="")
{
$deletedoc = $_POST['deletedoc'];
$svcount = count($deletedoc);
for ($i = 0; $i < $svcount; $i++)
{
if ($deletedoc[$i] != "" && $deletedoc[$i] >= 0 && is_numeric($deletedoc[$i]))
{
$query = "SELECT * FROM docs WHERE DID='".mysql_real_escape_string($deletedoc[$i])."'";
$executequery = $conn->execute($query);
$theuserid = $executequery->fields['USERID'];
$doc_name = $executequery->fields['doc_name'];
if(mysql_affected_rows()>=1)
{
$docpath = $config['docdir']."/".$doc_name;
#chmod($docpath, 0777);
if (file_exists($docpath))
{
#unlink($docpath);
}
if($theuserid == $_SESSION['USERID'])
{
$deletefrom[] = "docs";
$deletefrom[] = "docs_comments";
$deletefrom[] = "docs_favorited";
for($j=0;$j < count($deletefrom);$j++)
{
$query = "DELETE FROM ".$deletefrom[$j]." WHERE DID='$deletedoc[$i]'";
$conn->Execute($query);
}
$tempthumbs = $config['thumbdir']."/".$deletedoc[$i].".jpg";
if(file_exists($tempthumbs))
{
#unlink($tempthumbs);
}
if ($svcount > 1)
{
$message = $lang['643'];
}
else
{
$message = $lang['644'];
}
}
else
{
if ($svcount > 1)
{
$error = $lang['645'];
}
else
{
$error = $lang['646'];
}
}
}
}
}
}
mydocs.tpl:
<form id="deleteform" name="deleteform" action="{$baseurl}/mydocs.php" method="post">
{section name=i loop=$docs}
{insert name=seo_clean_titles assign=title value=a title=$docs[i].title}
<div class="column {if $smarty.section.i.iteration % 6 == 0}last{/if}">
<div class="image"><img src="{$vthumburl}/{$docs[i].doc_name|truncate:-4:"":true}.jpg" alt="{$docs[i].title|stripslashes|truncate:25:"...":true}" ></div>
<h3>{$docs[i].title|stripslashes|truncate:17:"...":true}
<br />{$lang485}: <input type="checkbox" name="deletedoc[]" value="{$docs[i].DID}">
<br />{$lang318}</h3>
</div>
{/section} <div class="btndelete">
<input type="submit" value=" " name="submitdelete"></div>
</form>
Urgently awaiting a solution / assistance.
Many thanks in advance!
There is nothing wrong with the code.
For some reason, the connect.php was using write only permissions to the sql db.
Change it to All Privileges and now it works.
Now to secure it.
I'm new to programming language. I want to know can i get value from other field and pass to other field in same form without using javascript ? Can someone explain to me ? Thank u.
This my form page
<form id="leave_form">
<table><tr>
<td width="70"><b>*</b> Date From:</td>
<td width="120"><span id="lv_date_from_btn"><input readonly class="field_required control" onchange="validateLeave('from')" id="lv_date_from" name="date_from" value="<?php echo $start_date?>" size="10" maxlength="10"/> <img src="images/calendar.gif"/></span></td>
</tr>
<tr>
<td width="70"><b>*</b> Date To:</td>
<td width="120"><span id="lv_date_to_btn"><input readonly class="field_required control" onchange="validateLeave('to')" id="lv_date_to" name="date_to" value="<?php echo $end_date?>" size="10" maxlength="10"/> <img src="images/calendar.gif"/></span></td>
</tr>
<?php if ($userid == '609'):?>
<tr>
<td><b>*</b> Relief Staff: </td>
<td>
<select name="userid" id="frm_userid2" class="field_required control" onchange="validateLeave('relief')" >
<?php
$leavefrom = $_REQUEST['from'];
$leaveto = $_REQUEST['to'];
if (empty($leavefrom))
{
echo '<option value="" selected disabled>Select...</option>';
}
else{
echo '<option value="" selected disabled>Select...</option>';
$sql = "
SELECT distinct fullname FROM core_user LEFT JOIN lms_tran ON lms_tran.userid = core_user.userid where core_user.userid NOT IN (SELECT userid FROM lms_tran WHERE date_from BETWEEN '$leavefrom' AND '$leaveto' AND app_status = 'Approved') AND core_user.userid != 609 AND core_user.status = 'Y' ORDER by fullname ASC
";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result))
{
echo '<option value="'.$row["userid"].'">'.$row["fullname"].'</option>';
}
}?>
</select>
</td>
</tr>
<?php endif; ?>
</table>
</form>
and this is javascript
function validateLeave(type)
{
var days= jQuery('#frm_days').val();
var from = jQuery('#lv_date_from').val();
var to = jQuery('#lv_date_to').val();
var relief = jQuery('#frm_userid2').val();
if (type != 'check')
{
days_incorrect = true;
}
if (type == 'days' || type == 'from')
{
to = '';
relief = '';
}
if (type == 'to')
{
days = '';
}
if (
(
(days == '' ? 0 : 1) +
(to == '' ? 0 : 1) +
(from == '' ? 0 : 1)
) < 2
)
{
days_correct = false;
return;
}
days = parseFloat(days);
jQuery('#frm_days').val(days);
jQuery('.control').attr('disabled', true);
jQuery('#lv_loading').show();
jQuery.post('index.php?_m=lms&_a=leave_validate&from='+from+'&to='+to, {from:from,to:to,days:days}, function(res){
eval('var r = '+res+';');
if (r.status == 'OK')
{
days_incorrect = false;
if (r.to)
{
jQuery('#lv_date_to').val(r.to);
}
if (r.from)
{
jQuery('#lv_date_from').val(r.from);
}
if (r.days)
{
jQuery('#frm_days').val(r.days);
}
}
else if (r.status == 'HOLIDAYERROR')
{
alert('Incorrect leave start date. Leave start date can not fall into Weekend or Public Holidays');
days_incorrect = true;
}
else
{
alert('Incorrect leave period. Please check back Leave Start, Leave End and Leave Days')
days_incorrect = true;
}
jQuery('.control').attr('disabled', false);
jQuery('#lv_loading').hide();
});
}
and i could'nt get the value return in php code as i hv pass value via jQuery.
No, you can't. The only way to do something interactive is to do it with javascript if you the to see it. If it doesn't matter you can do this on the server by assigning the second variable with the value of the first.