PHP/MYSQL Query Print Results in HTML Form Field - javascript

Recently I have been assigned a group project for a college class and I will need to query a customers name from a database and then print out the rest of the row in form fields. I have the select menu working correctly and it will print to the form field. However, the problem occurring is the query results will only show the last row in the MYSQL table I selected. Any help here would be greatly appreciated. I have been spinning my wheels for a few days on this issue. I am only a beginner coder, so it might be a little messy.
Thanks,
Connection.PHP File
<?php
function Connect()
{
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "medley";
// Create connection
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die($conn->connect_error);
return $conn;
}
?>
My Query Page
<?php
require 'connection.php';
$conn = Connect();
$sql = "SELECT * FROM cust_info";
$result = $conn->query($sql);
echo "<select id='firstName' name='firstname' onchange=populatesecondbox()>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['F_Name'] . "', '" . $row['L_Name'] . "'> " . $row['F_Name'] . " " . $row['L_Name'] . "</option>";
$pphone = $row['P_Phone'];
}
echo "</select>";
?>
<input id="secondinputbox" type="text" />
<script type="text/javascript">
function populatesecondbox(val) {
var dropdown = document.getElementById("firstName");
var pphone = document.getElementById("secondinputbox");
var secondfname = document.getElementById("thirdinputbox");
var str = "<?php echo $pphone ?>";
var sfname = "<?php echo $sfname ?>";
pphone.value = str;
secondfname.value = sfname;
}
</script>
​

Instead of using
$row = mysqli_fetch_array($result)
on line 10, use
$row = $result->fetch_assoc()
or
$row = $result->fetch_array()
The difference between fetch_assoc and fetch_array is that fetch_array contains both numeric indices and named indices. For example echo $row[0] will output as same as echo $row['id']. Whereas, fetch_assoc only contains named indices.

Based on the provided loop statement
$pphone = $row['P_Phone'];
$pphone is getting assigned to the last row on termination of the loop because each iteration is overriding $pphone with the current row until at which point in the loop $pphone gets the last value.
Instead of using
$pphone = $row['P_Phone'];
Try the following in the loop.
$pphone[] = $row['P_Phone'];
Your concatenated phones should be provided after the loop.
$pphones = "['".join("','" , $pphone)."']";
In your js script tag just get $pphones as a string;
var pphones = <?php echo $pphones; ?>;
ddl = document.getElementById('firstname');
pphone.value = pphones[ddl.selectedIndex];

Related

Pass array from javascript to page in wordpress

I have a page in wordpress, that uses an jquery and ajax to get information from an external api. The form sends the array generated in javascript back to the same page with another variable that the php in the page uses to determine which page to display. Outside of wordpress, the code works fine. Inside Wordpress the first portion runs, but then instead of loading the same page again it goes to a search page and says nothing found.
The url on the output is:
http://kltools.net/?s=&post_type%5B%5D=portfolio&post_type%5B%5D=post&post_type%5B%5D=page
Which seems odd considering I'm using post not get.
The javascript that generates the array and submits the form:
function submitchans(){
for (var i=0;i<chans.length;i++)
{ var newHidInp = document.createElement('input');
newHidInp.type = 'hidden';
newHidInp.name = 'chans[]';
newHidInp.value = chans[i];
form.appendChild(newHidInp);
}
}
function livearray(input){
if (input != null) {
chans.push(input);
}
if (Y === cSize){
submitchans();
document.forms[0].submit();
}
}
Previously the array was outArray[] instead of chans[], I changed it thinking that may be triggering the result, but no luck.
This is the PHP portion of the code:
<?php
$page_to_load = $_POST[view];
switch($page_to_load) {
case '':
echo "<script src=\"../scripts/jquery-3.2.0.min.js\"></script>";
echo "<script type=\"application/javascript\" src=\"../scripts/raid.js\"></script>";
echo "<font size=\"+3\" color=\"#FFFFFF\">Who should I host?<br>Please wait while channel is selected<br></font>";
echo "<font size=\"+2\">";
echo "<br><br>";
echo "<img src=\"../_images/ajax_loader_blue_350.gif\">";
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$chanarray[] = null;
$offline = 0;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT `TwitchNames` FROM TK_Members WHERE Validated='1' AND RaidMe='1'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
array_push($chanarray, $row['TwitchNames']);
}
} else {
echo "0 results";
}
array_splice($chanarray, 0, 1);
$conn->close();
echo "<script type=\"application/javascript\">";
echo "var channels = ". json_encode($chanarray);
echo "</script>";
echo "</font>";
echo "<form id=\"form\" method=\"post\">";
echo "<input type=\"hidden\" name=\"view\" value=\"page2\">";
echo "</form>";
break;
case 'page2':
echo "<font size=\"+3\" color=\"#FFFFFF\">Who should I host?<br>";
echo "Your channel to host is:<br></font>";
echo "<font size=\"+2\">";
echo "<br><br>";
$chans[] = null;
$test = $_POST['chans'];
foreach ($test as $chan) {
$temparray = array(rand(),$chan);
array_push($chans, $temparray);
}
array_splice($chans,0,1);
sort($chans);
echo "".$chans[0][1]."";
echo "<br><br><br>";
echo "See All Live Channels";
echo "</font>";
break;
}
?>
After working with what blokeish has suggested I've modified the javascript file working out where the problem is.
The new javascript file is:
// JavaScript Document
var chans = ["test1","test2","test3"];
function submitchans(){
for (var i=0;i<chans.length;i++)
{ var newHidInp = document.createElement('input');
newHidInp.type = 'hidden';
newHidInp.name = 'chans[]';
newHidInp.value = chans[i];
document.getElementById('chansform').appendChild(newHidInp);
}
}
jQuery(function ($) {
submitchans();
document.getElementById('chansform').submit();
});
Using only the javascript clicking submit, it passes to the next page. When adding in the array pass is when it fails. This is the page log that is returning during the execution. !!--CORRECTION--!! there was a typo in the code, after correcting ID to Id the code is working as intended.
document.forms[0].submit() is likely submitting the wp search form as that could be the first form in the DOM. I see "http://kltools.net/?s=" in the URL where "s" is the search term.
Using document.getElementById('idOfForm').submit() should get you around that problem if there are multiple forms in a page and you cant be sure of its index.

How to store js variable into php without using $_SESSION["name"] = "<script>document.write(name)</script>";?

I tried using $_SESSION["name"] = "document.write(name)"; and it works if i echo it out. But if i were to show this SESSION variable into a textbox or use it to do SQL, it shows document.write(name). How can i properly store it into a php variable? I've search and many people say you cant convert it. But surely there is someways where i can use the Javascript variable(name) to show it in a textbox or use it in SQL.
javascript code with the variable name.
<script>
var name;
$(document).ready(function()
{
$('#info tr #name').click(function()
{
name = $(this).text();
alert(name);
window.location = 'CV.php';
});
});
</script>
For SQL my code is this,
<?php $_SESSION["name"] = "<script>document.write(name)</script>";
echo $_SESSION["name"];
$connect = mysqli_connect("localhost", "root", "","test1");
$sql = "SELECT Name, Number, Expertise, Status, Remarks FROM particulars WHERE Name ='". $_SESSION["name"]."'";
$result = mysqli_query($connect, $sql);
while($row= mysqli_fetch_array($result))
{
$name = $row['Name'];
$number =$row['Number'];
$Expertise =$row['Expertise'];
$status =$row['Status'];
$remarks =$row['Remarks'];
}
?>
And below is my code to try to show the variable that i have stored in session into textbox.
<input type='text' value='" .htmlspecialchars($_SESSION['name']) . "'/>
<script>
var name;
$(document).ready(function()
{
$('#info tr #name').click(function()
{
name = $(this).text();
alert(name);
window.location = 'CV.php?name=' + name; // send in link
});
});
</script>
Inside CV.PHP
if(isset($_GET['name']))
{
$name = $_GET['name']; // Get it from URL
$_SESSION["name"] = $name;
}
else
{
$name = $_SESSION['name']; // Get it from session
}
$connect = mysqli_connect("localhost", "root", "","test1");
$sql = "SELECT Name, Number, Expertise, Status, Remarks FROM particulars WHERE Name ='". $_SESSION["name"]."'";
$result = mysqli_query($connect, $sql);
while($row= mysqli_fetch_array($result))
{
$name = $row['Name'];
$number =$row['Number'];
$Expertise =$row['Expertise'];
$status =$row['Status'];
$remarks =$row['Remarks'];
} ?>
To show it in input box:
<input type='text' value='" .$name . "'/> // echo value as string
<input type='text' value='" .$_SESSION['name']. "'/> // if it's a page that is not CV.php

Dropdown box to insert value to MYSQL db OnChange using AJAX and PHP

I am having trouble executing SQL via AJAX when a dropdown box is changed and would like some help if possible.
Background Info
I have been tasked with creating a daily calendar that shows all the classes ran at a gym, which at its maximum is 5 x classes of 6 (30) people per hour for 14 hours.I'm no pro and I may have created a convoluted way around this issue, please let me know if i have.
I have managed to create the view which consists of 14 columns of 30 drop down boxes (5 x classes of 6 per hour for 14 hours). Each drop down box polls the db and if an entry resides it will populate the box with the name of the bookinguser. If no booking is found it will create a drop downbox that polls the members table and presents all the members of the gym, which when changed, will hopefully book that person in. - herein lies my current issue!
Each drop down box's name corresponds to the time, group and headcount which I intend on passing to javascript function and eventually to the SQL statement. Each option's value corresponds with the memberid which will also be passed giving all the information needed to construct the SQL.
The code I have so far
HTML - snipped generated from php loops
<div id="results">
<div id="07" class="column">07:00<br/>
<div id="group1">
<select name="07:00-1-0" onchange="getda(this.value,this)">
<option value="none">---------------</option>
<option value="2">John Doe</option>
<option value="1">Joe Bloggs</option>
</select>
<select name="07:00-1-1" onchange="getda(this.value,this)">
<option value="none">---------------</option>
<option value="2">John Doe</option>
<option value="1">Joe Bloggs</option>
</select>
PHP
<?php
$mysqli = new mysqli("localhost", "root", "", "gym");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
function hyphenate($str) {
return implode("-", str_split($str, 2));
}
function getmembers($time,$group,$iteration)
{
$date=$_GET["date"];
$date=hyphenate($date);
$date = explode('-', $date);
$new_date = $date[2].'-'.$date[1].'-'.$date[0];
$mysqli = new mysqli("localhost", "root", "", "gym");
if ($iteration == 0){
$result = $mysqli->query("select members.memberid, members.firstname, members.lastname from bookings inner join members on bookings.memberid = members.memberid where bookings.date = '$new_date' and time = '$time' and bookings.groupnumber = '$group' order by bookings.bookingid ASC limit 1");
}
else {$result = $mysqli->query("select members.memberid, members.firstname, members.lastname from bookings inner join members on bookings.memberid = members.memberid where bookings.date = '$new_date' and time = '$time' and bookings.groupnumber = '$group' order by bookings.bookingid ASC limit 1,$iteration");
}
$rowcount=mysqli_num_rows($result);
if ($rowcount==$iteration && $iteration == 0)
{
$result = $mysqli->query("select firstname, lastname,memberid from members order by firstname ASC");
echo '<select name="'.$time.'-'.$group.'-'.$iteration.'" onchange="getda(this.value,this)"><option value="---------------">---------------</option>';
while ($row = $result->fetch_assoc()) {
unset($firstname, $lastname);
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$memberid = $row['memberid'];
echo '<option value="'.$memberid.'">'.$firstname . ' ' . $lastname .'</option>';
}
echo "</select>";
}
else if ($rowcount>=$iteration){
echo '<select name="'.$time.'-'.$group.'-'.$iteration.'" onchange="getda(this.value,this)">';
while ($row = $result->fetch_assoc()) {
unset($firstname, $lastname);
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$memberid = $row['memberid'];
echo '<option value="'.$memberid.'">'.$firstname . ' ' . $lastname .'</option><option value="cancel">Cancel</option>';
}
echo "</select>";
}
else{
$result = $mysqli->query("select firstname, lastname, memberid from members order by firstname ASC");
echo '<select name="'.$time.'-'.$group.'-'.$iteration.'" onchange="getda(this.value,this)"><option value="---------------">---------------</option>';
while ($row = $result->fetch_assoc()) {
unset($firstname, $lastname);
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$memberid = $row['memberid'];
echo '<option value="'.$memberid.'">'.$firstname . ' ' . $lastname .'</option>';
}
echo "</select>";
}
}
?>
JS
function getda(id,booking){
$.ajax({
type: 'post',
url: 'samefile.php',
data: {
get_option:id
},
success: function (response) {
document.getElementById("result").innerHTML=response;
}
});
}
samefile.php
<?php
if(isset($_POST['get_option']))
{
inlude 'config/config.php';
$name=$_POST["get_option"];
echo "<SCRIPT>
alert('$name');
</SCRIPT>";
$sql = "insert into bookings (memberid,date,time,groupnumber) values (1,'2016-04-14','09:00',3)";
$query = mysqli_query($sql);
$mysqli->close();
?>
The console in chrome looks fine (below) but no records are inserted and the php alert doesn't show. I havent passed any of the variable to the SQL as I was first testing that a query executed properly
jquery.min.js:4 XHR finished loading: POST "http://localhost/gym/samefile.php".send # jquery.min.js:4n.extend.ajax # jquery.min.js:4getda # cal.php?date=140416:42onchange # cal.php?date=140416:36ListPicker._handleMouseUp # about:blank:535
Might want to look into jQuery's .change(). I think that it would work with something like below for your code. You could also have it call your function that has ajax in it as well
$( ".class" ).change(function() { //can use #id here too
$.ajax({
type: 'post',
url: 'samefile.php',
data: {
get_option:this.value
},
success: function (response) {
document.getElementById("result").innerHTML=response;
}
});
});
I see three problems in samefile.php - include spelled incorrectly, an extra semicolon, and a missing closing bracket:
<?php
if(isset($_POST['get_option']))
{
include 'config/config.php';
$name = $_POST["get_option"];
//this should be converted to parameterized queries
$sql = "insert into bookings (memberid,date,time,groupnumber) values (1,'2016-04-14','09:00',3)";
$query = mysqli_query($sql);
if(is_object($query)){
echo 'successfully inserted';
} else {
echo 'insert failed';
}
$mysqli->close();
} else {
echo 'no data to process!';
}
?>

HighChart for PHP 5.1 lower

I am new to PHP and Highchart. Currently, I am trying to:
1. Query my data from MySQL using PHP.
2. To display HighChart :: Javascript, get data from json_encode in PHP.
Problem now, my PHP is 5.1.6 (I have a few applications running since few years back, try not to upgrade the php). I cannot use the json_numeric_check.
Help Needed :
Question 1: is there any alternative way to get the value without json_numeric_check?
Question 2: Is there any package I can add in to php 5.1.6 to use json_numeric_check?
This is the code I want to use ::
print json_encode($result,json_numeric_check);
My Full Code
<?php
header("Content-Type:application/json");
include_once "shift.php";
list($s1,$e1,$shift) = shift_frame();
$servername = 'localhost';
$username = "";
$password = "";
$select = "SELECT EH_CELLNUM, COUNT(EH_SERIALID)";
$table = " FROM T_EEDATA";
$rule1 = " WHERE (EH_END_DT between ".$s1." and ".$e1.") group by EH_CELLNUM";
$conn = mysql_connect($servername,$username,$password) or die("Connection failed: " . mysqli_connect_error());
mysql_select_db("eedata",$conn) or die(mysql_error());
$sql = $select.$table.$rule1;
$query = mysql_query( $sql, $conn );
$category = array();
$category['name'] = 'Cellnum';
$series1 = array();
$series1['name'] = 'SerialID';
while($row = mysql_fetch_array($query)){
$category['data'][] = $row['EH_CELLNUM'];
$series1['data'][] = $row['COUNT(EH_SERIALID)'];
}
////////////code add here???/////////////////////////////
$result = array();
array_push($result,$category);
$result2 = array();
array_push($result,$series1);
print json_encode($result,json_numeric_check);
mysql_close($conn);
?>
you can do someting to $result before json_encode
for example:
$result = array("1", "2", "3", "4");
$result = array_str_to_int($result);
// only for simple array,you can optimize the code
function array_str_to_int($array){
$tmp_arr = array();
foreach( $array as $k => $v ){
$tmp_arr[] = intval($v);
}
return $tmp_arr;
}

Change the value of external Javascript with PHP in foreach loop

How can I change the value of a js variable in a PHP foreach loop?
The js needs to be external.
This is a piece of the index.php here I want to get the output $prozent in the javascript, I don't know how to get a PHP variable to execute a js every time in a loop, the js is a chart. I get the chart in the loop in the echo'<div class="chart-wrapper"> with a this chart js.
<?php
$sql = //SQL query
$res = mysql_query($sql);
$i = 0;
$survey = array();
while ($row = mysql_fetch_assoc($res)) {
$survey[$i]['label'] = $row['Label'];
$i++;
}
foreach ($survey as $survey) {
echo '<div class="col-md-4">';
echo '<div class="front face">';
echo "<h3> ".$survey['label']."<br>";
$sql = //SQL Query
$res = mysql_query($sql) ;
$sql = //SQL Query
$resSum = mysql_query($sql) ;
while ($row = mysql_fetch_array($resSum)) {
$survey['ausgabe'] = $row['sum(a.answer)'];
}
$anzahlreihen = mysql_num_rows($res);
if ($anzahlreihen > 0) {
$prozent = $anzahlreihen * $survey['ausgabe'];
//bunch of ifelse statements
//This is the variable i want to get in the js
echo (round( $prozent, 2));
echo '</font>';
}
}
echo '</div>';
echo '<div class="back face center">';
echo'<div class="chart-wrapper">
}
There are two ways PHP and Javascript can interact.
Use AJAX to request a PHP script which returns JSON or have PHP output the following example HTML;
<script type="text/javascript">
var variable = value;
</script>

Categories