how to split the variable input by users to an array - php

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
)

Related

PHP, comparing a value from an Select field (HTML) to a value from an array not working

I'm trying to compare a value that I get from a select (HTML) to a value that is already in an array but for some reason its not working
if(isset($_POST['submit1'])) {
$selectOption = $_POST['answers'];
$correctAnswer = $filearray[$question][6];
$a=(string)$selectOption;
$b=(string)$correctAnswer;
echo $a;
echo $b;
if ( $a=== $b){
echo 'Nice answer';
}else{
echo 'you failed';
}
}
When I compare $a with $b I always get 'you failed' even tho they are equal (eg answer is A and correct answer is A as well) I tried to make both a String and to compare them with double equals and also triple equals but I always get the wrong result.
edit:
here is the whole code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Beat the L</title>
</head>
<body>
<h1>Beat the L</h1>
<!--<div id="indexFormDiv">
<form method="post">
<label for="Username">Username: </label><input id="Username" name="Username" type="text" value="" required><br>
<button name="submit" id="submit" >Let's go</button>
</form>
</div> -->
<?php
$question = 0;
$dataText = file('test.txt');
$arrayAnswers = array(
2=> 'A',
3=> 'B',
4=> 'C',
5=> 'D'
);
$filearray = array();
$file = fopen("test.txt", "r");
if ($file) {
$i = 0;
while (($line = fgets($file)) !== false) {
$data = explode(":", $line);
$filearray[$i] = array(
1 => $data[0],
2 => $data[1],
3 => $data[2],
4 => $data[3],
5 => $data[4],
6 => $data[5]
);
$i++;
}
fclose($file);
} else {
echo "Couldn't load the questions";
}
echo "Question: " . $filearray[$question][1] . "<br>";
echo "<form method='post' action='". $_SERVER['PHP_SELF']."'>";
echo "Choose your answer: <select name='answers'>";
for ($i = 2; $i <= count($filearray[$question])-1; $i++) {
echo "<option value='".$arrayAnswers[$i]."'>" . $filearray[$question][$i] . "</option>";
}
echo "</select><br>";
echo "<input type='submit' name='submit1' id='submit1' ></form>";
if(isset($_POST['submit1'])) {
$selectOption = $_POST['answers'];
$correctAnswer = $filearray[$question][6];
$a=(string)$selectOption;
$b=(string)$correctAnswer;
echo $a;
echo $b;
if ( $a=== $b){
echo 'Nice answer';
} else {
echo 'you failed';
}
}
?>
</body>
</html>
Here is my test website: https://students.btsi.lu/oliwi/Jose/login.php
To make it more generic for future use:
Notice that when reading data from text file and assign to variable there may be a following "" (white-space) or \n therefor it is recommend to use trim before doing any comparison.
Small hint - if your compare fails use var_dump before the if statement to check the actual values

No records displayed in PHP search form

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

Php: Group and add missed field

I have in a array a table like this:
cid plugin lang_id name father
1 Newspage 1 Actualidad 1
1 Newspage 2 News 1
2 Newspage 1 Tecnologia 1
2 Newspage 2 Tech 1
3 Newspage 1 Deportes 1
3 Newspage 2 Sports 1
4 Newspage 1 Ocio 1
In this example there are two languages (1:Spanish and 2:English) but admin can add more languages
I want do a "modify category" section and group it by CID with input boxes for each language if language its missed i want display a empty input for add the missed language.
Something like this:
http://i.imgur.com/fGCUgKc.png
My actual bad code its this:
$content = "<div class='catlist'>";
$content .= "<p>{$LANGDATA['L_NEWS_MODIFIED_CATS']}</p>";
$query = $db->select_all("categories", array ("plugin" => "Newspage", "lang_id" => 1));
while ($cat_grouped = $db->fetch($query)) {
$content .= "<form id='cat_mod' method='post' action=''>";
$content .= "<div>";
foreach ($langs as $lang) {
if ($lang['lang_id'] == $cat_grouped['lang_id']) {
$content .= "<label>{$lang['lang_name']}</label> <input type='text' name='{$lang['lang_id']}' value='{$cat_grouped['name']}' />";
} else {
$query2 = $db->select_all("categories", array ("plugin" => "Newspage", "cid" => "{$cat_grouped['cid']}", "lang_id" => "{$lang['lang_id']}"));
if($db->num_rows($query2) <= 0) {
$content .= "<label>{$lang['lang_name']}</label> <input type='text' name='{$lang['lang_id']}' value='' />";
} else {
$other_lang_cat = $db->fetch($query2);
$content .= "<label>{$lang['lang_name']}</label> <input type='text' name='{$lang['lang_id']}' value='{$other_lang_cat['name']}' />";
}
}
}
$content .= "<input type='hidden' name='cid' value='{$cat_grouped['cid']}' />";
$content .= "<input type='submit' name='ModCatSubmit' value='{$LANGDATA['L_NEWS_MODIFY']}' />";
$content .= "</div></form>";
}
$content .= "</div>";
This:
$db->select_all(...);
mean
$db->select_all("table", $WHERE, ...)
I want to retrieve all content in one query and do the work in php
My actual code its clearly very bad and assumed lang_id=1 exists for each entry and do few query's huh!
My old code use "GROUP BY cid" for the first query and not need to use "lang_id=1" but after a system upgrade that line give the error:
reported: Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column
and not want to use again that.
any idea the best way for do that?
I don't know what your database library is, so I'm writing a pseudo like code.
First, I would use a pagination to limit the database queries, for example 10/20 phrases for each page. So the query would be:
SELECT * FROM language_phrases WHERE cid IN (
SELECT DISTINCT cid FROM language_phrases WHERE plugin = 'Newspage'
LIMIT 0,10
)
then I would use the data from database first to get the cid values:
$cid = array();
$strings = array();
while($row = $db->fetch($result))
{
if(!in_array($cid,$row["cid"]))
{
$cid[] = $row["cid"];
}
$strings[]= array(
"cid" => $row["cid"],
"lang_id" => $row["lang_id"],
"name" => $row["name"],
"father" => $row["father"]
);
}
Then I would have the table and the distinct cid's in this page in my buffer. Then PHP will do the rest:
foreach($cid as $idx=>$key)
{
$values = array_filter($strings,function($d) use ($key) {
return $d["cid"] == $key;
});
// build the form with the $values array.
}
This problem give a headache but i made another version that work and only one query.
I will check later the Taha Paksu version/way (thanks!)
$content = "<div class='catlist'>";
$content .= "<p>{$LANGDATA['L_NEWS_MODIFIED_CATS']}</p>";
$query = $db->select_all("categories", array ("plugin" => "Newspage"), "ORDER BY cid");
$cats = [];
$catsids = [];
while ($cats_row = $db->fetch($query)) {
$cats[] = $cats_row;
$catsids[] = $cats_row['cid'];
}
$catsids = array_unique($catsids);
$foundit = 0;
foreach ($catsids as $catid) {
$content .= "<form id='cat_mod' method='post' action=''>";
$content .= "<div>";
foreach ($langs as $lang) {
foreach ($cats as $cat) {
if (($catid == $cat['cid']) && ($cat['lang_id'] == $lang['lang_id'])) {
$content .= "<label>{$lang['lang_name']}</label> <input type='text' name='{$lang['lang_id']}' value='{$cat['name']}' />";
$foundit = 1;
}
}
if ($foundit == 0) {
$content .= "<label>{$lang['lang_name']}</label> <input type='text' name='{$lang['lang_id']}' value='' />";
}
$foundit = 0;
}
$content .= "<input type='hidden' name='cid' value='$catid' />";
$content .= "<input type='submit' name='ModCatSubmit' value='{$LANGDATA['L_NEWS_MODIFY']}' />";
$content .= "</div></form>";
}

Getting all array values in loop

So here's my code in getting an input from a user on how many questions (multiple choice) he/she would like to make:
Multiple choice: <input type = "text" name="MC"><br>
<input type = "submit" name = "confirm" value = "Confirm">
After that, this is the code of how many questions the system will generate:
<?php
if(isset($_POST['confirm'])){
$MC = $_POST['MC'];
echo "<form method = 'POST' name = 'items' action ='createquestions.php'>";
$items = 1;
for ($x = 1; $x <= $MC; $x++) {
echo "Question Number $items:"; echo "<input type = 'text' name = 'questions[]' style='width: 500px'><br><br>";
echo "A. "; echo "<input type = 'text' name = 'ans1[]'>";
echo "B. "; echo "<input type = 'text' name = 'ans2[]'><br>";
echo "C. "; echo "<input type = 'text' name = 'ans3[]'>";
echo "D. "; echo "<input type = 'text' name = 'ans4[]'><br>";
echo "Correct Answer: "; echo "<input type = 'text' name ='cans[]'><br><br>";
$items++;
}
echo "<input type ='submit' name = 'save' value = 'Save'>";
echo "</form>";
}
?>
<?php
The problem is that it will only save the last input of the user.
For example, I have inputted 2 in the Multiple choice: --textbox here--
This code will generate 2 questions, 8 choices, 2 cans = correct answer but it will only save the 2nd question, answers, and the correct answer. the system won't get the record of the 1st question, answer, and the correct answer.
Here is the code where I would insert it on the database:
<?php
if(isset($_POST['save'])){
$user_id = $_SESSION['id'];
$questions = $_POST['questions'];
$ans1 = $_POST['ans1'];
$ans2 = $_POST['ans2'];
$ans3 = $_POST['ans3'];
$ans4 = $_POST['ans4'];
$cans = $_POST['cans'];
foreach($questions as $q){
echo "<input type = 'hidden' value = '$q'>";
}
require_once('xcon.php');
$query = "INSERT INTO mcq (mc_id, user_id, questions, ans1, ans2, ans3, ans4, cans)
VALUES ('NULL','$user_id','$q','$ans1','$ans2','$ans3','$ans4','$cans')";
$result = mysql_query($query);
if($result){
echo 'Insert Success!';
}
else{
echo 'Error';
}
}
?>
When you save you should be running through a loop again. Try this maybe?
<?php
if(isset($_POST['save'])){
$user_id = $_SESSION['id'];
require_once('xcon.php');
foreach ($_POST['questions'] as $key => $question){
$ans1 = $_POST['ans1'][$key];
$ans2 = $_POST['ans2'][$key];
$ans3 = $_POST['ans3'][$key];
$ans4 = $_POST['ans4'][$key];
$cans = $_POST['cans'][$key];
echo "<input type = 'hidden' value = '$question'>";
$query = "INSERT INTO mcq (mc_id, user_id, questions, ans1, ans2, ans3, ans4, cans)
VALUES ('NULL','$user_id','$question','$ans1','$ans2','$ans3','$ans4','$cans')";
$result = mysql_query($query);
if($result){
echo 'Insert Success!<br>';
}else{
echo 'Error<br>';
}
}
}
?>
According to this post you should use:
echo "Question Number $items:"; echo "<input type = 'text' name = 'questions' style='width: 500px'><br><br>";
echo "A. "; echo "<input type = 'text' name = 'ans[]'>";
echo "B. "; echo "<input type = 'text' name = 'ans[]'><br>";
echo "C. "; echo "<input type = 'text' name = 'ans[]'>";
echo "D. "; echo "<input type = 'text' name = 'ans[]'><br>";
echo "Correct Answer: "; echo "<input type = 'text' name ='cans'><br><br>";
And this:
$ans1 = $_POST['ans'][0];
$ans2 = $_POST['ans'][1];
$ans3 = $_POST['ans'][2];
$ans4 = $_POST['ans'][3];
Explanation
You only need to post ans[] repeatedly , and not
ans1[], ans2[], ans3[]... in order to get an array like
$_POST['ans'][0], $_POST['ans'][1]...
or you can use
ans1, ans2, ans3
(without brackets []) to read as
$_POST['ans1'], $_POST['ans2'], $_POST['ans3']...
You are using element naming in a strange way, you are using array, but still use numbers. Try generating like this:
for ($x = 0; $x <= $MC; $x++) {
echo "<input type = 'text' name = 'questions[$i]'>";
echo "A. <input type = 'text' name = 'ans[$i][A]'>";
echo "B. <input type = 'text' name = 'ans[$i][B]'><br>";
echo "C. <input type = 'text' name = 'ans[$i][C]'>";
echo "D. <input type = 'text' name = 'ans[$i][D]'><br>";
echo "Correct Answer: <input type = 'text' name ='cans[$i]'><br><br>";
}
Then you'll get the following results in your $_POST:
[
"questions" => [
0 => "question1",
...
]
"ans" => [
0 => [
"A" => "answer A",
"B" => "answer B",
"C" => "answer C",
"D" => "answer D",
]
...
]
"cans" => [
0 => "A",
....
]
]
Which is easily processed with a foreach:
foreach ($_POST['questions'] as $key => $question) {
// $question == 'question1';
$answers = $_POST['ans'][$key]; // array of answers
$solution = $_POST['cans'][$key];
}

Pulling Data in PHP from SQL Server

I have an issue with my script somewhere but do not know exactly where it is incorrect. Here is the code:
<title>Log</title>
</head>
<h1> Log </h1>
<form method="get" action="getlog.php">
<table width="300" border="0">
<tr>
<td> Forte ID:</td>
<td><select id="ForteID" name="ForteID">
<option value="nc4682">nc4682</option>
<option value="bs1441">bs1441</option>
<option value="sp3212">sp3212</option>
</select></td>
</tr>
</table>
<input type="submit" name="getLog" value="Get Log">
</form>
</head>
<body>
</body>
</html>
<?php
/*print_r($_POST);*/
$serverName = 'SRB-Nick_Desktop\SQLEXPRESS';
$connectionInfo = array('Database'=>'cslogs', 'UID'=>'cslogslogin', 'PWD'=>'123456');
$connection = sqlsrv_connect($serverName, $connectionInfo);
$query = 'SELECT ForteID, Disposition, appNumber, Finance_Num, Num_Payments, ACH_CC, Notes from logs';
$result = sqlsrv_query($connection,$query);
if (!$result)
{
$message = 'ERROR: ' . sqlsrv_errors();
return $message;
}
else
{
$i = 0;
echo '<html><body><table><tr>';
while ($i < sqlsrv_num_rows($result))
{
$meta = sqlsrv_fetch($result, $i);
echo '<td>' . $meta->name . '</td>';
$i = $i + 1;
}
echo '</tr>';
while ( ($row = sqlsrv_fetch_array($result)))
{
$count = count($row);
$y = 0;
echo '<tr>';
while ($y < $count)
{
$c_row = current($row);
echo '<td>' . $c_row . '</td>';
next($row);
$y = $y + 1;
}
echo '</tr>';
}
sqlsrv_free_stmt ($result);
echo '</table></body></html>';
}
sqlsrv_close( $connection);
?>
And this is what I get in result, no matter what is selected in the drop down box and hit the button get log.
nc4682 nc4682 Save Save asdf asdf fdas fdas 1 1 cc cc asdf asdf
bs1441 bs1441 LOC LOC AN00336862 AN00336862 None None 0 0 ach ach Backout Backout
nc4682 nc4682 Save Save AN00336862 AN00336862 easdf easdf 2 2 ach ach asdf asdf
sp3212 sp3212 Sale Sale NCXXXXXX1 NCXXXXXX1 none none 1 1 cc cc asdfasdfasdf asdfasdfasdf
Each column is duplicated. There are supposed to be 7 columns.
To only show the results from the drop down list you would append something like
WHERE ForteID = {$_GET['ForteID']}
to the end of your SQL statement.
sqlsrv_fetch_array() returns both a numeric array and an associative array by default.
Try specifying only one type of array
while ( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC ))
To use your dropdpwn in the query.
$query = 'SELECT ForteID, Disposition, appNumber, Finance_Num, Num_Payments, ACH_CC, Notes FROM logs WHERE ForteID =' . $_GET['ForteID'];
Please be aware that without sanitizing the $_GET variable this query is vulnerable to sql injection.

Categories