No records displayed in PHP search form - php

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'] ;
}

Related

how to split the variable input by users to an array

A variable $irn input by the users, I need to pass the variable $irn one by one to a SQL and display the result in GR textbox after clicking the button
Generate Result, I want to split the $irn to an array so I can pass it one by one to the SQL query.
I tried mb_split and preg_split
<?php
include "big2gb.php";
ini_set('default_charset', 'utf-8');
$result = $_GET["listIRN"];
$irn = $_POST["irn"];
$serverName = "192.168.4.75";
$connectionInfo = array( "Database"=>"SAFHKG", "UID"=>"sa1", "PWD"=>"Azsxdc11", "CharacterSet" => "UTF-8");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if($conn){
//echo "connect DB success!!!<br />";
}
else
{
//echo "successfully failed!!!<br />";
die(print_r(sqlsrv_errors(),true));
}
//find irn
$sql="Select Top 1
[Expression] = CONCAT(OFFICIALNUMBER, ' for ', TITLE, ' in Class ', LOCALCLASSES)
From CASES
INNER JOIN OFFICIALNUMBERS On CASES.CASEID = OFFICIALNUMBERS.CASEID
Where NUMBERTYPE IN ('R', 'A') and CASES.IRN = ('".$array[$i]."')
Order By
CASE
When NumberType = 'R' then -2
When Numbertype = 'A' then -1
End";
echo"
<table>
<form action='test22.php' method='post'>
<tr>
<td>IRN:</td>
<td>
<input type='text' id='txtIRN' value='' style='text-transform:uppercase' >
<input type='button' value='Add IRN' onClick='addIRN()' name=''/>
<input type='submit' value='Genarate Result' id='GR' name=''/>
</td>
</tr>
<tr><tr><tr>
<td><td>
<textarea id='listIRN' name='irn' rows='40' cols='30' >
</textarea><textarea id='GR' rows='40' cols='80' ></textarea>
</td></td>
</tr></tr></tr>
</form>
</table><br/>";
echo"
<script type='text/javascript'>
function addIRN(irn) {
var IRNText = document.getElementById(\"txtIRN\").value;
var IRNList = document.getElementById(\"listIRN\").value;
var irn = IRNList + '\\n' + IRNText;
document.getElementById(\"listIRN\").value = irn.trim().toUpperCase();
}
</script>";
//////////////////your entered//////////////////*
echo "<p>You entered:<p>";
$array = mb_split('\\n', $irn);
foreach($array as $line)
{
$array = explode('\s', $irn);
echo "$line\n";
}
//////////////////////////////////////////////
print_r ($array);
//echo $array[3];
//echo $array[0];
for ($i = 0; $i <= 20; $i++)
{
$result = sqlsrv_query($conn, $sql );
while( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOc) )
{
echo " ". $row["Expression"] ." <br />";
}
}
$conn->close();
?>
strong text
User input will be like TM1150CN31 TM2846CN35 TM2855CN35 TM2865CN35 TM2874CN43 TM3367CN05
You can use explode function like below
$var = 'TM1150CN31 TM2846CN35 TM2855CN35 TM2865CN35 TM2874CN43 TM3367CN05';
$array = explode(' ', $var);
Out put will be like
Array
(
[0] => TM1150CN31
[1] => TM2846CN35
[2] => TM2855CN35
[3] => TM2865CN35
[4] => TM2874CN43
[5] => TM3367CN05
)

How to show message or data only one time while select multiple checkbox in jquery?

code:
<script>
$(document).ready(function(){
$(".choose").click(function(){
job_type = $(':checked').map(function() {
return this.value;
}).get().join(',');
category = $("#cat_gory").val();
$.ajax({
type:"POST",
data:{"job_type":job_type,"category":category},
url:"type-jobs.php",
success:function(data){
$(".success").html(data);
}
});
});
});
</script>
<input type="hidden" name="cat_gory" id="cat_gory" value="<?php echo $job_category; ?>" />
<p class="flchek">
<input type="checkbox" name="choosetype" value="freelance" class="choose" id="33r">
<label for="33r">Freelance</label>
</p>
<p class="ftchek">
<input type="checkbox" name="choosetype" value="full time" class="choose" id="dsf">
<label for="dsf">Full Time</label>
</p>
<p class="ischek">
<input type="checkbox" name="choosetype" value="internship" class="choose" id="sdd">
<label for="sdd">Internship</label>
</p>
<div class="success"></div>
type-jobs.php
<?php
include("config.php");
$job_category = mysqli_real_escape_string($con,$_POST['category']);
$job_type = mysqli_real_escape_string($con,$_POST['job_type']);
$tag = explode(",",$job_type);
foreach($tag as $type)
{
$sql_job = mysqli_query($con,"select p.job_title,c.state,c.city from company c inner join jobs p on p.company_name = c.company_name where p.category = '".$job_category."' and job_type='".$type."'");
$result_job = mysqli_num_rows($sql_job);
if($result_job > 0)
{
while($row_jobs = mysqli_fetch_array($sql_job))
{
echo '<h3>'.$row_jobs['job_title'].'</h3>';
}
}
else
{
echo '<p id="c_mm">record not found</p>';
}
}
?>
In this code I have multiple checkbox. Now, When I click on checkbox to get data through jquery/ajax it return data to me but the problem is if I click on freelance checkbox it show me record not found again when I click on full time then it showing record not found as well as jobs. Now, I want if data was not found in my database it will show single message to me and if data found then hide message and show database record. So, How can I do this? Please help me.
Thank You
NO need to explode the $jobtype Use 'jobtype IN('.$jobtype.') '
<?php
include("config.php");
$job_category = mysqli_real_escape_string($con,$_POST['category']);
$job_type = mysqli_real_escape_string($con,$_POST['job_type']);
$sql_job = mysqli_query($con,"select p.job_title,c.state,c.city from company c inner join jobs p on p.company_name = c.company_name where p.category = '".$job_category."' and job_type IN('".$jobtype."') ');
$count = mysqli_num_rows($sql_job);
$row_data = mysqli_fetch_array($chek_result);
if($count > 0){
foreach($row_data as $data){
$message = '<h3>'.$data['job_title'].'</h3>';
}
}else{
$message = "No Data found";
}
echo $message;exit;
?>
If you want to show record not found message only if you don't find any record then you can use a flag in php something like this:
<?php
include("config.php");
$job_category = mysqli_real_escape_string($con,$_POST['category']);
$job_type = mysqli_real_escape_string($con,$_POST['job_type']);
$found = 0;
$message = '';
$tag = explode(",",$job_type);
foreach($tag as $type)
{
$sql_job = mysqli_query($con,"select p.job_title,c.state,c.city from company c inner join jobs p on p.company_name = c.company_name where p.category = '".$job_category."' and job_type='".$type."'");
$result_job = mysqli_num_rows($sql_job);
if($result_job > 0)
{
$found = 1;
while($row_jobs = mysqli_fetch_array($sql_job))
{
$message .= '<h3>'.$row_jobs['job_title'].'</h3>';
}
}
}
if(found == 0) {
$message = '<p id="c_mm">record not found</p>';
}
echo message;
?>
Notice $found flag here in code. HTH.

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

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

PHP : Variable does not show value in Function while shows directely

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: &nbsp &nbsp <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
}

PHP or HTML Form Validation

I want to validate an HTML form in either HTML or PHP. By validate, I mean ensuring there is at least 1 character of text entered into each of the 2 textboxes. And either only alpha numeric characters entered, or have something that ensures that any punctuation doesn't end up with "/" before it.
At the moment my form is made up of 2 php pages (copied below), and then posted to a txt file.
I'm either after some (very basic) instructions on how to do it, or suggestions on my script below.
//HTML
<form style="" method="post" action="addtopic2.php">
Topic:<input name="topic" id="topicbox" maxlength="100" type="text"><br>
Outline: <textarea input wrap="nowrap" rows="10" cols="120"
name="outline"></textarea>
<br><input name="submit" value="Submit" type="submit">
</form>
//HTML
<?php
$t = "Topic:";
$o = "Outline:";
$topic = $_POST['topic'];
$outline = $_POST['outline'];
$data = "$t $topic | $o $outline |\n";
$fh = fopen("users.txt", "a");
fwrite($fh, $data);
fclose($fh);
?>
//ATTEMPTED TO USE FOLLOWING, BUT DOESNT SEEM TO WORK WHEN INSERTING INTO EITHER PAGES.
<?php
if($_POST['Submit'] == "submit")
{
$errorMessage = "";
if(empty($_POST['topic']))
{
$errorMessage .= "<li>A topic needs to be entered</li>";
}
if(empty($_POST['outline']))
{
$errorMessage .= "<li>An outline needs to be entered</li>";
}
$vartopic = $_POST['formtopic'];
$varoutline = $_POST['formoutline'];
if(!empty($errorMessage))
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
}
?>
<?php
if (isset($_POST['topic']) && isset($_POST['outline'])) {
$topic = trim($_POST['topic']);
$outline = trim($_POST['outline']);
}
else {
echo '<p>Fill the form</p>';
}
?>
Try
$file = "users.txt";
$errorMessage = array ();
if ($_POST ['Submit'] == "submit") {
if (empty ( $_POST ['topic'] )) {
$errorMessage [] = "A topic needs to be entered<";
}
if (empty ( $_POST ['outline'] )) {
$errorMessage [] = "An outline needs to be entered";
}
if (count ( $errorMessage ) == 0) {
$data = $_POST ['topic'] . "|" . $_POST ['outline'] . "\n";
$fh = fopen ( $file, "a" );
fwrite ( $fh, $data );
fclose ( $fh );
} else {
print ("<p>There was an error with your form:</p>\n") ;
print ("<ul>") ;
foreach ( $errorMessage as $error ) {
print "<li>" . $error . "<li>";
}
print ("</ul>") ;
}
}
// To Read Your File
$content = file ( $file );
print ("<p>File Details</p>\n") ;
foreach ( $content as $info ) {
list ( $topic, $outline ) = explode ( "|", $info );
print ("<ul>") ;
print "<li>Topic: " . $topic . "<li>";
print "<li>Outline:" . $outline . "<li>";
print ("</ul>") ;
}
Try this (single file) solution:
<form style="" method="post">
Topic:<input name="topic" id="topicbox" maxlength="100" type="text" value='<?= $_REQUEST['topic'] ?>><br>
Outline: <textarea input wrap="nowrap" rows="10" cols="120" name="outline"><?= $_REQUEST['outline'] ?></textarea>
<p/>
<input name="submit" value="Submit" type="submit">
</form>
<?php
if ($_REQUEST['submit'] !== 'submit')
{
exit;
}
if ($_REQUEST['topic'] == '')
{
echo "<p>Missing Topic.</p>\n";
exit;
}
if ($_REQUEST['outline'] == '')
{
echo "<p>Missing Outline.</p>\n";
exit;
}
$t = "Topic:";
$o = "Outline:";
$topic = $_POST['topic'];
$outline = $_POST['outline'];
$data = "$t $topic | $o $outline |\n";
$fh = fopen("users.txt", "a");
fwrite($fh, $data);
fclose($fh);
?>

Categories