many elements of a listbox to another - javascript

This is the first time I use this medium to ask for help. I wanted to know how , in my code , include two listbox . One that makes querying the database and , through a button , send it to the other, and to do so with more than one option , and then , as in the php code to put the data from the second listbox on a table database. Thank you.
<?php
include("server.php");
$conexion = mysql_connect($server,$user, $pass) or die ("<br> No se puede conectar con la base de datos");
$conectarbase = mysql_select_db ($bd);
$consulta = mysql_query("SELECT * FROM modalidad")
?>
<html lang = "es">
<head>
<meta charset = "iso-8859-1"/>
<meta name = "description" content = "Ejemplo de HTML5"/>
<meta name = "keywords" content = "HTML5, CSS3, Javascript"/>
<title>PRECEPTORÍA</title>
<link rel="shortcut icon" href="./style/favicon.png" />
<link rel = "stylesheet" href = "./style/style.css">
</head>
<body class = "body">
<section class = "section">
<div class = "div">
<form>
<fieldset id = "fieldsetalum">
<legend id = "legendalum">Registro de nuevos alumnos</legend>
<select name="combo1" multiple size="8">
<?php
while ($fila = mysql_fetch_row($consulta))
{
echo "<option value='".$fila['0']."'>".$fila['1']."</option>";
}
?>
</select>
<select name="combo2" multiple size=></select>
</fieldset>
</form>
</div>
</section>
</body>
</html>

Your form needs an action to submit to itself:
<form name="form" id="form" action="<?php echo echo htmlspecialchars($_SERVER["REQUEST_URI"]); ?>" method="post">
You could add an onChange(); event to your select1 dropdown
<select name="combo1" multiple size="8" onChange="submit_this();">
and have a JavaScript script in your <head>
<script language="javascript"> function submit_this(){ this.form.submit();}</script>
Then you would have to use php to collect the values from the submitted page
$combo1 = mysqli_real_escape_string( $_POST['combo1'] );
and then you could return the page with the second dropdown, constructed in much the same way as you made the first one, using the data you get back from the first one to set up the second one. You could wrap the first dropdown in an isset():
if( !isset( $combo1 ) ){
// make your first select boxes
}
and the second one in
if( isset( $combo1 ) ){
// make your second select boxes if combo1 returned a value
}
so that they will only appear when needed.
As #NanaPartykar says, mysqli is the only way to go.
It will be dependent on JavaScript, so, if you prefer, you could have a submit button instead of the JavaScript function:
<input type="submit" name="submit" value="Pick Sizes" />
This looks a handy referenc e for how to use select boxes: PHP code to get selected text of a combo box
I hope this will give you an idea of how it could be done - the SESSION variables remain to be properly defined in the loop for the second dropdown but they will probably come directly from your database at that point rather than from the session array used for demo purposes.
All values are set as numbers;
intval(); converts whatever is submitted to an integer to clean it up.
Then you can get back the corresponding value of what was submitted from the session variable you set from your database originally.
That way you will only be getting a single number value from your dropdowns which you can use to look up to get the answer you want
<?php session_start(); ?>
<!DOCTYPE html>
<html lang = "es">
<head>
<title>PRECEPTORÍA</title>
</head>
<body>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="post">
<?php
$main_opt = array();
$_SESSION['opt_vals'] = array();
$main_opt[0] = "Select Item";
$main_opt[1] = "Ice Cream";
$main_opt[2] = "Trousers";
$main_opt[3] = "Tee Shirts";
$_SESSION['opt_vals'][1][0] = "Select Flavour";
$_SESSION['opt_vals'][1][1] = "Vanilla";
$_SESSION['opt_vals'][1][2] = "Chocolate";
$_SESSION['opt_vals'][1][3] = "Strawberry";
$_SESSION['opt_vals'][1][4] = "Tuttifrutti";
$_SESSION['opt_vals'][2][0] = "Select Colour";
$_SESSION['opt_vals'][2][1] = "Black";
$_SESSION['opt_vals'][2][2] = "Red";
$_SESSION['opt_vals'][2][3] = "Green";
$_SESSION['opt_vals'][2][4] = "Blue";
$_SESSION['opt_vals'][3][0] = "Select Size";
$_SESSION['opt_vals'][3][1] = "Small";
$_SESSION['opt_vals'][3][2] = "Medium";
$_SESSION['opt_vals'][3][3] = "Large";
$_SESSION['opt_vals'][3][4] = "X Large";
$i = 0;
if(!isset($_POST['combo1']) && !isset($_POST['combo2'])){
echo '<select name="combo1" onChange="submit();">' . "\n";
//while ($fila = mysqli_fetch_row($consulta)){
while($i < count($main_opt)){
echo "<option value='".$i."'>".$main_opt[$i]."</option>\n";
$o = 0;
// load your sub options array here
if(!$_SESSION['opt_vals'][$i]) $_SESSION['opt_vals'][$i] = array();
while($i < count($_SESSION['opt_vals'][$i])){
$_SESSION['opt_vals'][$i] = $o;
if(!$_SESSION['opt_vals'][$i]) $_SESSION['opt_vals'][$i] = array();
$_SESSION['opt_vals'][$i][$o] = $_SESSION['opt_vals'][$i][$o];
$o++;
}
$i++;
}
echo '</select>' . "\n";
}else{
if(intval($_POST['combo1']) >= 1) $_SESSION['combo1_val'] = $combo1_val =intval($_POST['combo1']);
if(intval($_POST['combo1']) >=1){
$i = 0;
echo '<select name="combo2" onChange="submit();">' . "\n";
while($i < count($_SESSION['opt_vals'][$combo1_val])){
echo "<option value='".$i."'>".$_SESSION['opt_vals'][$combo1_val][$i]."</option>\n";
$i++;
}
}
echo '</select>' . "\n";
}
if(intval($_POST['combo2']) >= 1) $_SESSION['combo2_val'] = $combo2_val =intval($_POST['combo2']);
if($_SESSION['combo1_val'] >=1 && $_SESSION['combo2_val'] >=1){
// use the result to do whatever you want
echo 'Thank you! You have selected ' . $_SESSION['opt_vals'][$_SESSION['combo1_val']][$_SESSION['combo2_val']] . " " . $main_opt[$_SESSION['combo1_val']] . '.';
}
// Do any mysqli adjustments to your database here
// reset to go again
if($_SESSION['combo2_val'] >= 1){
$_SESSION['combo1_val'] = 0;
$_SESSION['combo2_val'] = 0;
}
?>
</form>
Click to start a new selection
</body>
</html>
You could remove onChange="submit();" and replace it with a normal submit button on the form if you prefer.

Related

Is there a way to pass value of a Button on click to another php file?

My aim is to get the lec_id which is the Button value when the button is clicked and pass it to chapters.php where I use the button value for a SQL query.
Below is part of my code for index.php
<?php
$con = mysqli_connect("localhost", "root", "", "lectureHub");
if(!$con) {
die("Could not connect to MySql Server:" . mysqli_error());
}
$query = "select * from lectures";
$result = mysqli_query($con, $query);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$lec_id = $row['lec_id'];
$lec_name = $row['lec_name'];
$lec_number = $row['lec_number'];
$lec_views = $row['lec_views'];
echo "<button id=linkButton name={$row['lec_name']} value={$row['lec_id']} type='button' class='btn btn-outline-primary lecture' onclick='buttonClicked(this)'>
{$row['lec_name']}
</button> ";
}
} else {
echo "0 results";
}
?>
my button onclick function
function buttonClicked(btn) {
btn.click_counter = (btn.click_counter || 0) + 1;
document.getElementById("num_clicks_feedback").textContent = `btn ${btn.getAttribute('name')} has been clicked ${btn.click_counter} times`;
localStorage.setItem("lecId", btn.getAttribute('value'));
location.href = 'index.php?action=lec_hub/chapters';
}
I want to use the Button value here in chapters.php for a SQL query.
<html>
<head></head>
<body>
<?php
echo "<p id='lecId'></p>";
$con = mysqli_connect("localhost", "root", "", "lectureHub");
if(!$con) {
die("Could not connect to MySql Server:" . mysqli_error());
}
$query = "select * from chapters where <<this is where i want to use lecId>> ";
?>
<script>
function getValue(){
var lecId = localStorage.getItem("lecId");
document.getElementById("lecId").innerHTML = lecId;
var resetValue= 0;
localStorage.setItem("lecId", resetValue)
}
getValue()
</script>
</body>
</html>
Welcome to Stack Overflow! As Barmar stated in their comment, you can pass data to a PHP file using URL parameters, or more commonly known as GET parameters. Here's how you do it.
From your file with your button in it, you can create a form like this one:
<form action="chapters.php" method="get">
<input type="text" name="data" /> <!-- This is the value that will be passed -->
<input type="submit" value="Button" /> <!-- This is your button -->
</form>
And then from your PHP file, you can get that passed data like this:
echo $_GET["data"]
$_GET is a global PHP array that contains all of the URL parameters sent to the file. you can pass multiple values as GET parameters to a file. You can read all about the $_GET variable here. I hope this helps!

Not being able to perform MySQL query with PHP in a dynamic select element

Context: I'm retrieving a bunch of Stock tickers from my database and putting those as options in a select element. Now, I'd like for the selected tickers by the user to be passed onto a MySQL query with PHP to retrieve the stock data (such as the open price). Even though I'm creating the select options dynamically, I feel like that should be enough to allow the query to be done successfully (referring to this SO topic - How to pass the selected value in dropdown (HTML) to PHP).
Minimally reproducible code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<select id="selectStock" name="selectStock">
</select>
<input class="button1" type="submit" name="submit" id="btnAdd"></input>
<select id="list" name="list" multiple>
</select>
</form>
</body>
<script type="text/javascript">
var dropdown = document.getElementById("selectStock");
var selected = []
//let options = <?php echo json_encode($tickerArray) ?>; //get data from MySQL tickers
let options = [
["AAPL"],
["TSLA"],
["HOOD"],
["GOOGL"]
];
var btnAdd = document.querySelector('#btnAdd');
var sb = document.querySelector('#list');
const name = document.querySelector('#selectStock');
//var open = <?php echo json_encode($openPrices) ?>; This is the variable that I want to retrieve the open prices, but the query isn't working
//Insert list of tickers in the options
for (var i = 0; i < options.length; i++) {
var list = options[i]; //save every option as opt
var opt = document.createElement("option");
opt.innerHTML = list; //change the HTML so that the newly added element for a select option is equal to the tickers in opt
opt.value = list; //give the value of the element created as the ticker name
dropdown.appendChild(opt); //append the latest element created to the select options
}
//Function to add the selected tickers in the list box
btnAdd.onclick = (e) => {
e.preventDefault();
// validate the option
if (name.value == '') {
alert('Please enter the name.');
return;
}
// create a new option
option = new Option(name.value, name.value);
// add it to the list
sb.add(option, undefined);
selected.push({
x: option.value,
y: Math.random(), //percentualIncrease, //openCalc
});
// reset the value of the input
name.value = '';
name.focus();
console.log(selected)
console.log(open)
console.log(option.value)
};
</script>
</html>
This is the PHP:
<?php
$servername = "...";
$username = "...";
$password = "...";
$dbname = "...";
$tickerChosen = "";
$openPrices = array();
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset($_POST["submit"])) {
$tickerChosen = $_POST["option"];
echo $tickerChosen;
$stmt = $conn->prepare("SELECT Open FROM symbolsv2 WHERE ticker=? ORDER BY Date DESC LIMIT 2");
$stmt->bind_param("s", $tickerChosen);
$stmt->execute();
$result = $stmt->get_result();
while ($open = $result->fetch_all()) {
$openPrices = $open;
}
$stmt->close();
}
$conn->close();
?>
I already tried changing the $tickerChosen = $_POST["..."] with selectStock, name, option, etc, but none of those seemed to be able to "grab" the user input and pass it to the query.
Any suggestions? Thank you in advance!

Postgresql database with web access- code correctly updates database but web page takes very long time to reload

I have a postgresql database for a hypothetical zoo. I am creating web access for my database using php and some javascript. I have successfully gotten the majority of the web pages to work, but am now working on a page that allows the client to add and remove animals from current exhibits. I have a dropdown that is populated with the exhibit names from the database, the second dropdown is populated from the database with animal names and their IDs that are assigned to the current exhibit selected(exhibit_id is foreign key in animal table referencing exhibit_id in exhibit table). This is dynamically changed when the exhibit name is selected. I have a third dropdown that is populated from the database with animal names and their ID that are not assigned to an exhibit. This all works upon initial loading of the page. Upon clicking the add or remove button my database is updated correctly, but the page just keeps loading. I was expecting it to give the success message and then the client could pick another exhibit and it would show the updates, but it doesn't get there. I've been teaching myself HTML, PHP, and JS so the code is pretty sloppy. I'm using some mix of examples I found on the web to get the dynamic dropdowns and ability to select multiple options from the dropdown lists so this is probably where the issue lies since I can exit the page and go back and then it will have the dropdowns with the values they should have. I would appreciate any help on why this is happening and if there are any fixes. Thanks!
<?php
//Read database info from file and assgin to variables
$myfile = fopen("../pg_connection_info.txt", "r") or die("Unable to open \"../pg_connection_info.txt\" file!");
$my_host = fgets($myfile);
$my_dbname = fgets($myfile);
$my_user = fgets($myfile);
$my_password = fgets($myfile);
fclose($myfile);
// Make a connection to the database
$dbhost = pg_connect("host=$my_host dbname=$my_dbname user=$my_user password=$my_password");
// If the $dbhost variable is not defined, there was an error
if(!$dbhost)
{
die("Error: ".pg_last_error());
}
//Get exhibits from database
$query = "SELECT exhibit_id, name FROM exhibit";
$result = pg_query($dbhost, $query);
while($row = pg_fetch_row($result))
{
$categories[] = array("id" => $row[0], "val" => $row[1]);
}
//Get animals assigned to exhibits
$query2 = "SELECT animal_id, exhibit_id, name FROM animal";
$result2 = pg_query($dbhost, $query2);
while($row = pg_fetch_row($result2))
{
$subcats[$row[1]][] = array("id" => $row[0], "val" => $row[2]);
}
$jsonCats = json_encode($categories);
$jsonSubCats = json_encode($subcats);
?>
<html lang="en-us">
<head>
<title>Manage Animals/Exhibits</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
?>
//exhibit dropdown options
function loadCategories(){
var select = document.getElementById("exhibit");
select.onchange = updateSubCats;
var j = 0;
select.options[0] = new Option("--Select an option--");
for(var i = 0; i < categories.length; i++){
select.options[j + 1] = new Option(categories[i].val,categories[i].id);
j++;
}
}
//animals assigned to exhibits dropdown options
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("animal");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val + " - " + subcats[catid][i].id ,subcats[catid][i].id);
}
}
//Allows multiple selecting of dropdown items
window.onmousedown = function(e)
{
var el = e.target;
if(el.tagName.toLowerCase() == 'option' && el.parentNode.hasAttribute('multiple'))
{
e.preventDefault();
if(el.hasAttribute('selected')) el.removeAttribute('selected');
else el.setAttribute('selected', '');
}
}
</script>
</head>
<body onload='loadCategories()'>
<h1>Add and Remove Animals from Exhibits</h1>
<form action="Manage_Animal_Exhibit.php" method="post">
<p>Select an exhibit to add or remove animal(s) from</p>
</select>
Exhibit: <select name="exhibit" id="exhibit">
</select><br><br>
<p>Current animals in exhibit:</p>
<select name="animal[]" id='animal' multiple>
</select><br><br>
<input type="submit" name="Remove" value="Remove"/><br><br>
<p>Current animals not assigned to an exhibit:</p>
<select name="animalAvail[]" id='animalAvail' multiple>
<?php
//get animals not in exhibit
$query3 = "SELECT name, animal_id FROM animal WHERE exhibit_id is NULL";
$result3 = pg_query($dbhost, $query3);
while($row = pg_fetch_row($result3)){
$name = $row[0];
$id = $row[1];
//Display animal's name and id in dropwdown. Assign id to the option so no need for an associative array
echo "<option value='$id'>$name - $id </option>";
}
?>
</select><br><br>
<input type="submit" name="Add" value="Add"/><br><br>
</form>
<!--Exits the Manage_Animal_Exhibit page and returns to the Home Page-->
<form action="Home_Page.php" method="post">
<input type="submit" name="Exit" value="Exit"/>
</form>
<?php
//When add button is pressed assign animals to exhibit
if(isset($_POST["Add"]))
{
//If exhibit isn't selected display message
if($_POST["exhibit"] == "--Select an option--")
{
echo "<script type='text/javascript'>alert('Select an exhibit')</script>";
}
else
{
$arr = array();
//Get each animal selected from dropdown and add their ID to an array
foreach($_POST["animalAvail"] as $animalID)
{
array_push($arr, "$animalID");
}
//Get id of exhibit selected and then add animals to exhibit
$exhibitID = $_POST["exhibit"];
$query4 = "UPDATE Animal SET exhibit_id = $1 WHERE animal_id = $2";
pg_prepare($dbhost, "prepare1", $query4);
for($i = 0; i < count($arr); $i++)
{
$idToUpdate = $arr[$i];
pg_execute($dbhost, "prepare1", array($exhibitID, $idToUpdate));
}
echo "<script type='text/javascript'>alert('The animals were added to the exhibit')</script>";
}
}
if(isset($_POST["Remove"]))
{
//If exhibit isn't selected display message
if($_POST["exhibit"] == "--Select an option--")
{
echo "<script type='text/javascript'>alert('Select an exhibit')</script>";
}
else
{
$arr2 = array();
//Get each animal selected from dropdown and add their ID to an array
foreach($_POST["animal"] as $aID)
{
array_push($arr2, "$aID");
}
$query5 = "UPDATE Animal SET exhibit_id = NULL WHERE animal_id = $1";
pg_prepare($dbhost, "prepare2", $query5);
for($i = 0; i < count($arr2); $i++)
{
$idUpdate = $arr2[$i];
pg_execute($dbhost, "prepare2", array($idUpdate));
}
echo "<script type='text/javascript'>alert('The animals were removed from the exhibit')</script>";
}
}
// Free the result from memory
pg_free_result($result);
// Close the database connection
pg_close($dbhost);
?>
</body>
</html>
I condensed my code and was able to get the web page to load immediately. The issue was within the code for updating the database when the add and also the remove button was pressed. I had an enhanced for loop to get the selected values and add them to an array and then a for loop to update the records in the database. I condensed it to just one enhanced for loop that would get the values selected and also update the database. Here is an example of what I did for the add. The remove is the same format.
//When add button is pressed assign animals to exhibit
if(isset($_POST["Add"]))
{
//If exhibit isn't selected display message
if($_POST["exhibit"] == "--Select an option--")
{
echo "<script type='text/javascript'>alert('Select an exhibit')</script>";
}
else
{
//Get id of exhibit selected and then add animals to exhibit
$exhibitID = $_POST["exhibit"];
$query4 = "UPDATE Animal SET exhibit_id = $1 WHERE animal_id = $2";
pg_prepare($dbhost, "prepare1", $query4);
foreach($_POST["animalAvail"] as $animalID)
{
pg_execute($dbhost, "prepare1", array($exhibitID, $animalID));
}
echo "<script type='text/javascript'>alert('The animals were added to the exhibit'
</script>";
}
}

Using span text in where clause in php

This div act as a button. Whenever I click one, the page goes to the page name "teacherinfo.php". The "Sample" text is used as the name of the teacher. The problem is when I click the "Sample2" the Sample text appear on the "teacherinfo.php" page.
Here is the script for going to "teacherinfo.php":
<?php
while ($row = mysqli_fetch_array($query)) {
echo '<div class="announcementSlider" id="click">
<img src="pictures/blank photo.png" class="teacherpic"><br>
<span name="LastName">'.$row['LastName'].'</span><br>
<span>'.$row['Grade'].' - </span>
<span>'.$row['Section'].'</span>
</div>';
}
?>
<script type="text/javascript">
var a = document.getElementsByClassName("announcementSlider");
for (i=0; i<a.length; i++) {
a[i].onclick = function () {
location.href = "teacherinfo.php";
};
}
</script>
Code for displaying the text in "teacherinfo.php":
<div class="leftForm hide-on-med-and-down">
<img src="pictures/default-avatar-250x250.png">
<p class="name"><?php echo $name3; ?></p>
<p class="section"><?php echo $grade3; ?>-<?php echo $section; ?></p>
</div>
Code for retrieving data in database:
$sql3 = mysqli_query($db,"select * from teacherinfo");
$row3 = mysqli_fetch_array($sql3,MYSQLI_ASSOC);
$name3 = $row3['LastName'];
$grade3 = $row3['Grade'];
$section3 = $row3['Section'];
I want to use the "'.$row['LastName'].'" as a where clause in mysqli_query($db,"select * from teacherinfo"). How can I do that? or is there another solution to this issue?
First of all, I don't understand why you use javascript when you can use simple a tag with correct href:
<?php
while ($row = mysqli_fetch_array($query)) {
echo '<a class="announcementSlider" href="teacherinfo.php?id=' . $row['id'] . '">
<img src="pictures/blank photo.png" class="teacherpic"><br>
<span name="LastName">'.$row['LastName'].'</span><br>
<span>'.$row['Grade'].' - </span>
<span>'.$row['Section'].'</span>
</a>';
}
?>
Here, I suppose that every teacher in your mysql-table has some unique id field.
On teacherinfo.php you access id as $_GET['id'] and create a query like (here I skip security part, but $_GET['id'] can be forged and therefore contain some insecure data, you have to check it):
sql3 = mysqli_query($db,"select * from teacherinfo where id = " . $_GET['id']);
$row3 = mysqli_fetch_array($sql3,MYSQLI_ASSOC);
$name3 = $row3['LastName'];
$grade3 = $row3['Grade'];
$section3 = $row3['Section'];

Jscript/Ajax to return PHP without page reload

Complete novice but making progress. Please assist in getting form data to php and back without a page refresh. I know this should require JQuery / AJAX. I have tried multiple methods (serialize/dataform) but I am stumped. The goal is to fill in a listbox on form.php with headers acquired with PHPExcel from an Excel file PRIOR to being uploaded / tmp (no fopen etc) via lbox.php. All code below works. ** I am not looking to submit the data with the button YET, this should be called when a file has been chosen to be uploaded**
form.php
<html>
<head>
<title>Testing Page</title>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script = "text/javascript">
window.onload = startChecking;
function startChecking()
{
var myVar = setInterval(doFunction, 1000);
}
function doFunction()
{
var nme= document.getElementById("file");
var x=document.getElementById("right");
if(nme.value.length<1){
document.getElementById("right").style.display="none";
return false;
}
document.getElementById("right").style.display="block";
//CODE NEEDED TO LOAD THE LISBOX THAT IS NOW APPEARING
clearInterval(myVar);
}
</script>
</head>
<body>
<form action="lbox.php" method="post" enctype="multipart/form-data" name="creationform" id="frmCreate">
Project Name:
<input type="text" name="YourName" value="Testing">
<br><br>
Choose your file: <br>
<input type="file" name="file" id="file">
<input type="submit" name="Create" value="Create" />
</form>
<div id = "right" style="display:none">
Below should be the data from PHP loaded into the listbox
<BR>
<!-- //This code takes our array of headers and builds them into a listbox -->
<select size="15" name="decision1" multiple>
<?php foreach($myArray as $key => $value) { ?>
<option value="<?php echo $key ?>"><?php echo $value ?></option> -->
<?php }?>
</select>
</div>
</body>
</html>
lbox.php
<?php
include 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$objPHPExcel = PHPExcel_IOFactory::load($_FILES['file']['tmp_name']);
// This code creates our concatenation of column headers
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$val2 = null;
// $highestRow = $worksheet->getHighestDataRow(); // e.g. 10
$highestRow = 1; // e.g. 10
$highestColumn = $worksheet->getHighestDataColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$nrColumns = ord($highestColumn) - 64;
for ($row = 1; $row <= $highestRow; ++ $row) {
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val2 .= $cell->getValue().',';
$dataType = PHPExcel_Cell_DataType::dataTypeForValue($val2);
}
}
}
//The code below gets rid of the extra comma at the end
$val2 = substr($val2,0,strlen($val2)-1);
$val2 .= '';
echo '<br />';
// This code takes our concatenation and turns it into an array with the comma delimiter
$myString = $val2;
$myArray = explode(',',$myString);
print_r($myArray);
echo '<br />';
?>
Thanks, Mark.

Categories