excel data into database using php - php

this is my sample excelsheet values
State 1972-1973 1973-1974 1974-1975 1975-1976 1976-1977 1977-1978 1978-1979 1979-1980 1980-1981 1981-1982
Alabama $733,750 $1,066,300 $1,136,244 $1,343,670 $1,476,307 $1,642,927 $1,507,315 $1,849,825 $2,402,873 $2,079,000
Alaska $1,019,000 $1,100,000 $1,180,500 $1,172,300 $1,415,300 $1,411,700 $1,666,500 $2,026,400 $3,409,800 $7,200,000
Arkansas $890,496 $1,173,304 $1,193,362 $1,735,266 $1,824,536 $1,929,071 $2,090,590 $2,173,595 $2,042,632 $2,203,864
through php coding i need to store in db.how to store it.

just try this
<title>Upload page</title>
<style type="text/css">
body {
background: #E3F4FC;
font: normal 14px/30px Helvetica, Arial, sans-serif;
color: #2b2b2b;
}
a {
color:#898989;
font-size:14px;
font-weight:bold;
text-decoration:none;
}
a:hover {
color:#CC0033;
}
h1 {
font: bold 14px Helvetica, Arial, sans-serif;
color: #CC0033;
}
h2 {
font: bold 14px Helvetica, Arial, sans-serif;
color: #898989;
}
#container {
background: #CCC;
margin: 100px auto;
width: 945px;
}
#form {padding: 20px 150px;}
#form input {margin-bottom: 20px;}
</style>
</head>
<body>
<div id="container">
<div id="form">
<?php
include "e2.php"; //Connect to Database
$deleterecords = "TRUNCATE TABLE books"; //empty the table of its current records
mysql_query($deleterecords);
//Upload File
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
echo "<h2>Displaying contents:</h2>";
readfile($_FILES['filename']['tmp_name']);
}
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import="INSERT INTO books (BookID,Title,Author,PublisherName,CopyrightYear) VALUES('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]')";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
print "Import done";
//view upload form
}else {
print "Upload new csv by browsing to file and clicking on Upload<br />\n";
print "<form enctype='multipart/form-data' action='index.php' method='post'>";
print "File name to import:<br />\n";
print "<input size='50' type='file' name='filename'><br />\n";
print "<input type='submit' name='submit' value='Upload'></form>";
}
?>
</div>
</div>
</body>
</html>
this is e2.php
$db = mysql_connect("localhost","root","") or die("Could not connect.");
if(!$db)
die("no db");
if(!mysql_select_db("books",$db))
die("No database selected.");
?>

Try this
simplex excel library and script you can create your own excel import to mysql.
if (isset($_FILES['file'])) {
require_once "simplexlsx.class.php";
$xlsx = new SimpleXLSX( $_FILES['file']['tmp_name'] );
echo '<h1>Parsing Result</h1>';
echo '<table border="1" cellpadding="3" style="border-collapse: collapse">';
list($cols,) = $xlsx->dimension();
foreach( $xlsx->rows() as $k => $r) {
// if ($k == 0) continue; // skip first row
echo '<tr>';
for( $i = 0; $i < $cols; $i++)
echo '<td>'.( (isset($r[$i])) ? $r[$i] : ' ' ).'</td>';
echo '</tr>';
}
echo '</table>';
}
?>
<h1>Upload</h1>
<form method="post" enctype="multipart/form-data">
*.XLSX <input type="file" name="file" /> <input type="submit" value="Parse" />
</form>

the following worked for me if the source is a csv file:
$filename = "/path/to/your/csvfile.csv";
$handle = fopen ($filename, "r");
$buffer = "";
while (!feof($handle)) {
$buffer .= fgets($handle, 16384);
}
$array = parse_csv_php($buffer);
// do what you want with your array...
function parse_csv_php(&$data,$delim=';',$enclosure='"'){
$enclosed=false;
$fldcount=0;
$linecount=0;
$fldval='';
for($i=0;$i<strlen($data);$i++) {
$chr=$data{$i};
switch($chr) {
case $enclosure:
if($enclosed&&$data{$i+1}==$enclosure) {
$fldval.=$chr;
++$i; //skip next char
} else { $enclosed=!$enclosed; }
break;
case $delim:
if(!$enclosed) {
$ret_array[$linecount][$fldcount++]=$fldval;
$fldval='';
} else { $fldval.=$chr; }
break;
case "\r":
if(!$enclosed&&$data{$i+1}=="\n")
continue;
case "\n":
if(!$enclosed) {
$ret_array[$linecount][$fldcount]=$fldval;
$linecount++;
$fldcount=0;
$fldval='';
} else { $fldval.=$chr; }
break;
default:
$fldval.=$chr;
}
}
if($fldval) {
$ret_array[$linecount][$fldcount]=$fldval;
}
return $ret_array;
}

Related

if isset $_POST output fail

I'm trying to create a banning system for a chat that I made and it has a separate "console" only seen by admins. Im using Mac OS 10.11.4, I am the owner and am using Mamp with php version 5.6.10
Ban.php
<?php
$ban = $_POST['ban'];
$mybfile = fopen("banned.txt", 'a');
$txtb = ($ban." , ");
//Makes sure ip banned it not an admins
if (isset($_POST['ban'])) {
//example ip addresses
if ($ban === '1.1.1.1' || 192.168.1.132) {
echo 'Can\'t ban an Admin';
} else {
echo 'IP banned';
fwrite($mybfile, $txtb);
fclose($mybfile);
}
}
?>
<style>
.ban {
background-color: black;
width:30em;
height:5em;
color: #7ACC52;
}
.buttonBAN {
border:1px solid black;
width: 85px;
height: 55px;
background-color: white;
color: black;
position: absolute;
}
</style>
<body>
<form method="POST">
BanCMD<br />
<input type="text" name="ban" class="ban">
<input type="submit" value="Enter" class="buttonBAN">
</form>
</body>
Chat.php:
<?php
require "blocked.php";
require "connect.inc.php";
require "core.inc.php";
require "commands.php";
$sent = $_POST['chat'];
$myfile = fopen("chat.txt", 'a') or die("Unable to open file!");
$txt = ($sent."\n");
$first = getuserfield('username');
$active = ($first.":".$ip_addr);
$activef = fopen("ip-user.txt", 'a');
$myFile = "domains/domain_list.txt";
if (loggedin()) {
echo 'Welcome, '.$first,'<br />';
if ($first != 'SnR' || 'Koi') {
fwrite($activef, $active."\n"."=");
}
} else if (!loggedin()) {
die('Not logged in');
}
if (isset($_POST['chat'])) {
if (!empty($sent)) {
fwrite($myfile, $first.': '.$txt.'=');
fclose($myfile);
} else if (empty($sent)) {
echo 'Cant send an empty message','<br />';
}
}
$file = "chat.txt";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
$line = fgets($handle);
$linecount++;
}
fclose($handle);
if ($linecount > 49) {
unlink($file);
} else {
echo 'Line count: '.$linecount,'<br />';
}
echo 'Chat will reset at 50 lines','<br />';
echo 'Your IP:';
echo $ip_addr,'<br />';
?>
<html>
<head>
</head>
<body>
<!-- <a href='active.txt'>Online users</a><br /> -->
<iframe id='reload' src='refresh.php'>
<fieldset class="field">
<div id="list"><p><?php
$filename = 'chat.txt';
$handle = fopen($filename, 'r');
$detain = fread($handle, filesize($filename));
$chat_array = explode('=', $detain);
foreach($chat_array as $chat) {
echo $chat.'<br />';
}
?></p></div>
</fieldset>
</iframe>
<form action="chat.php" method="POST">
<input type="text" name="chat" class="textbox">
<input type="submit" value="Send" class="button">
</form>
</body>
</html>
<?php
if ($first == 'SnR' && 'Koi') {
include 'AdminCMD.php';
include 'ban.php';
?>
<iframe id='reload' src='refresh2.php' class="field2">
<fieldset class="field">
</fieldset>
</iframe>
<?php
}
?>
The problem is that everything is fine until you give an input, no matter what you put into the box the output is always "Can't ban an Admin" meaning that it doesn't write to the given file
Thank you for any help.
Your code contains an error, preventing the file from being written. The first line of PHP code,$ban = $_POST['ban'];, could fail if no post data was sent. You need to first check if the $_POST['ban'] was set. A fixed version of your code can be found below.
<?php
//Makes sure ip banned it not an admins
if (isset($_POST['ban'])) {
$ban = $_POST['ban'];
$mybfile = fopen("banned.txt", 'a');
$txtb = ($ban." , ");
if ($ban === '1.1.1.1') {
echo 'Can\'t ban an Admin';
} else {
echo 'IP banned';
fwrite($mybfile, $txtb);
fclose($mybfile);
}
}
?>
<style>
.ban {
background-color: black;
width:30em;
height:5em;
color: #7ACC52;
}
.buttonBAN {
border:1px solid black;
width: 85px;
height: 55px;
background-color: white;
color: black;
position: absolute;
}
</style>
<body>
<form method="POST">
BanCMD<br />
<input type="text" name="ban" class="ban">
<input type="submit" value="Enter" class="buttonBAN">
</form>
</body>
When i ran your code it returns undefined index ban, you can try this and make sure what is not working for you.
<?php
$ban = isset($_POST['ban']) ? $_POST['ban'] : null;
$mybfile = fopen("banned.txt", 'a');
$txtb = ($ban." , ");
//Makes sure ip banned it not an admins
if(isset($ban)){
if ($ban === '1.1.1.1') {
echo 'Can\'t ban an Admin';
} else {
echo 'IP banned';
fwrite($mybfile, $txtb);
fclose($mybfile);
}
}
?>
<style>
.ban {
background-color: black;
width:30em;
height:5em;
color: #7ACC52;
}
.buttonBAN {
border:1px solid black;
width: 85px;
height: 55px;
background-color: white;
color: black;
position: absolute;
}
</style>
<body>
<form method="POST">
BanCMD<br />
<input type="text" name="ban" class="ban">
<input type="submit" value="Enter" class="buttonBAN">
</form>
</body>

How to add delete in php script in my photo gallery

I made a Photo gallery by php.
I am able to make upload image and show the image list. But i want to add a delete button where users can delete there unwanted image. But i was failed to add this button work.
Someone please help to fix it?
Here is my code on GitHub: https://github.com/sagar290/photo_gallerey/blob/6cad3743e735ea109723de7e14d5477bff1e964b/gallery.php
<?php
if (isset($_FILES["file"]["name"])) {
$name = $_FILES['file']['name'];
//$size = $_FILES['file']['size'];
//$extention = $type;
$type = strtolower($_FILES['file']['type']);
$tmp_name = $_FILES['file']['tmp_name'];
if (isset($name)) {
if (!empty($name)) {
if (($type=='image/jpg')||($type=='image/jpeg')||($type=='image/gif')) {
$location = 'photos/';
if(move_uploaded_file($tmp_name, 'photos/'.$name)) {
echo $name.' is uploaded';
}
}else {
echo 'file must be jpg or jpeg ';
}
}else {
echo 'please choose a file';
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Photo gallery</title>
<style type="text/css">
ul {
list-style-type: none;
}
li {
float: left;
padding: 10px;
margin: 10px;
font: bold 10px Verdana, sans-serif;
}
img {
display: block;
border: 1px solid #333300;
margin-bottom: 5px;
}
</style>
</head>
<body>
<h2>Photo gallery</h2>
<form action="gallery.php" method="POST" enctype="multipart/form-data">
UPLOAD:
<input type="file" name="file"><br><br>
<input type="submit" value="submit">
</form>
<ul>
<form action="gallery.php" method="POST">
<?php
//define location of photo image
$photosDir = './photos';
//define which file extention are images
$photosExt = array('gif','jpg','jpeg','tif','tiff','bmp','png');
//initialize array to hold filenames of images found
$photoList = array();
//read directory contents
//build photo list
if (file_exists($photosDir)) {
$dp = opendir($photosDir) or die('Error: cannot open file');
while ($file = readdir($dp)) {
if ($file != '.' && $file != '..') {
$fileData = pathinfo($file);
if (in_array($fileData['extension'], $photosExt)) {
$photoList[] = "$photosDir/$file"; // file includes as an array
}
}
}
closedir($dp);
}else {
die('ERROR: directory dosent exists');
}
//itarate over photo list
//display each image and file name
if (count($photoList)>0) {
for ($x=0; $x <count($photoList) ; $x++) {
?>
<li>
<input type="submit" name="delete" value="Delete">
<img src="<?php echo $photoList[$x]; ?>" height="150" width="200"/>
<?php echo basename($photoList[$x]); ?><br>
<?php echo round(filesize($photoList[$x])/1024) . 'KB'; ?>
</li>
<?php
}
} else {
die('ERROR: No image found');
}
?>
</form>
</ul>
</body>
</html>
hello just change your submit input to:
<input type="submit" name="delete" value="<?php echo $photoList[$x] ?>">
and then check for that value:
<?php if(isset($_POST['delete']) && !empty($_POST['delete'])){
//find the file
$file = 'photos/'.$_POST['delete'];
if(is_file($file)){
unlink($file);
}else{
echo $_POST['delete']." has not been found!";
}
}?>

using PHP to get information in xml file. How to make it shorter and expandable in the future?

These are the working codes that i have done. the program is about accessing information in an xml file such as student's name,id and marks based on group and team number submitted from a form. there are 2 submit buttons if one button is clicked, it will display with an additional element (pic) and the other one without it. so far so good.
but looking at the php codes, i know that i will be facing problems if there are numerous groups and team numbers. there would be a lot of if-else statements and the codes would be very long. i have tried using foreach but i'm not getting the result that i want. are there anyways to simplify this? i have been searching on the web but it seems that i just don't know how to implement them. quite new to this.
<html><style>
.datagrid table { border-collapse: collapse; text-align: center; width: 100%; }
.datagrid {font: normal 12px/150% Arial, Helvetica, sans-serif;
background: #fff;
overflow: hidden;
border: 4px solid #006699;
-webkit-border-radius: 20px;
-moz-border-radius: 20px;
border-radius: 20px; }
.datagrid table td, .datagrid table th { padding: 7px 20px; }
.datagrid table thead th {background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #006699), color-stop(1, #00557F) );
background:-moz-linear-gradient( center top, #006699 5%, #00557F 100% ); filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#006699', endColorstr='#00557F');
background-color:#006699; color:#FFFFFF; font-size:15px; font-weight:bold;
border-left: 1px solid #0070A8; }
.datagrid table thead th:first-child { border: none; }
.datagrid table tbody td { color: #00496B; border-left: 1px solid #E1EEF4;font-size: 13px;font-weight: normal; }
.datagrid table tbody .alt td { background: #E1EEF4; color: #00496B; }
.datagrid table tbody td:first-child { border-left: none; }
.datagrid table tbody tr:last-child td { border-bottom: none; }
</style>
<center>
<form action="" method="post" >
<select name="group">
<option value="csa">CSA</option>
<option value="csb">CSB</option>
</select>
Enter team number:<input type="text" name="teamnum" value="">
<input type="submit" name="submit1" value="With Photo">
<input type="submit" name="submit2" value="Without Photo">
</form>
<form action="index.php">
<input type="submit" value="main">
</form>
</center>
</html>
<?php
if (isset($_POST['submit1']) != '') {
$file = "student.xml";
$xml = simplexml_load_file($file) or die("Unable to load XML file!");
if (isset($_POST['group']) && isset($_POST['teamnum']) != '') {
$teamnum = $_POST['teamnum'];
$group = $_POST['group'];
if ($group == 'csa' && $teamnum == '1') {
$name = $xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/name');
$id = $xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/id');
$total = $xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/total');
//$photo =$xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/pic');
echo "<div class='datagrid'><table border='1' cellpadding='1'>";
echo "<thead><tr><th>Photo</th><th>Name</th><th>ID</th><th>carry marks</th></tr></thead>";
while ((list(, $node) = each($name)) && (list(, $node1) = each($id)) && (list(, $node2) = each($total))) {
echo "<tbody><tr class='alt'>";
echo "<td>1</td>";
echo "<td>$node</td>";
echo "<td>$node1</td>";
echo "<td>$node2</td>";
echo "</tr>";
}
echo "</tbody></table></div>";
}
else if ($group == 'csa' && $teamnum == '2') {
$name = $xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/name');
$id = $xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/id');
$total = $xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/total');
//$photo =$xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/pic');
echo "<div class='datagrid'><table border='1' cellpadding='1'>";
echo "<thead><tr><th>Photo</th><th>Name</th><th>ID</th><th>carry marks</th></tr></thead>";
while ((list(, $node) = each($name)) && (list(, $node1) = each($id)) && (list(, $node2) = each($total))) {
echo "<tbody><tr class='alt'>";
echo "<td>1</td>";
echo "<td>$node</td>";
echo "<td>$node1</td>";
echo "<td>$node2</td>";
echo "</tr>";
}
echo "</tbody></table></div>";
}
else if (isset($_POST['submit2']) != '') {
$file = "student.xml";
$xml = simplexml_load_file($file) or die("Unable to load XML file!");
if (isset($_POST['group']) && isset($_POST['teamnum']) != '') {
$teamnum = $_POST['teamnum'];
$group = $_POST['group'];
if ($group == 'csa' && $teamnum == '1') {
$name = $xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/name');
$id = $xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/id');
$total = $xml->xpath('//student[teamNum[contains(text(),"1")] and group[contains(text(),"CSA")]]/total');
echo "<div class='datagrid'><table border='1' cellpadding='1'>";
echo "<thead><tr><th>Name</th><th>ID</th><th>carry marks</th></tr></thead>";
while ((list(, $node) = each($name)) && (list(, $node1) = each($id)) && (list(, $node2) = each($total))) {
echo "<tbody><tr class='alt'>";
echo "<td>$node</td>";
echo "<td>$node1</td>";
echo "<td>$node2</td>";
echo "</tr>";
}
echo "</tbody></table></div>";
}
else if ($group == 'csa' && $teamnum == '2') {
$name = $xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/name');
$id = $xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/id');
$total = $xml->xpath('//student[teamNum[contains(text(),"2")] and group[contains(text(),"CSA")]]/total');
echo "<div class='datagrid'><table border='1' cellpadding='1'>";
echo "<thead><tr><th>Name</th><th>ID</th><th>carry marks</th></tr></thead>";
while ((list(, $node) = each($name)) && (list(, $node1) = each($id)) && (list(, $node2)= each($total))) {
echo "<tbody><tr class='alt'>";
echo "<td>$node</td>";
echo "<td>$node1</td>";
echo "<td>$node2</td>";
echo "</tr>";
}
echo "</tbody></table></div>";
}
?>
i have found the way to solve this by using foreach
<?php
if (isset($_POST['submit1']) != '') {
$file = "student.xml";
$xml = simplexml_load_file($file) or die("Unable to load XML file!");
if (isset($_POST['group']) && isset($_POST['teamnum']) != '') {
$teamnum = $_POST['teamnum'];
$group = $_POST['group'];
echo "<div class='datagrid'><table border='1' cellpadding='1'>";
echo "<thead><tr><th>Photo</th><th>Name</th><th>ID</th><th>carry marks</th></tr></thead>";
echo "<tbody>";
foreach ($xml->xpath("//student[contains(teamNum, $teamnum) and contains(group, $group)]") as $student) {
echo "<tr class='alt'>";
echo "<td>".$student->picture."</td>";
echo "<td>".$student->name."</td>";
echo "<td>".$student->id."</td>";
echo "<td>".$student->total."</td>";
echo "</tr>";
}
echo "</tbody></table></div>";
}else echo 'no data';
} else {
echo "enter a team's number";
}
?>
the trick is in the xpath. it selects all students that contains submitted values. after that it will be as $student and i will be able to output the element values from there.

PHP search engine in a txt file

I need to create a basic search engine with PHP to search for an ID within a .txt file but still don't know how to do it, I'm new programming :(
Any help would be much appreciated.
Here's the code I have so far.
<style type="text/css">
td {
font-family:verdana,arial;
font-size:8pt;
border-color:#ccc; }
.header{
background-color:66b50b;
border-style:solid;
border-color:#32661e;
border-width:1px;
font-weight:bold;
font-size:10pt;
color:ffffff; }
.estiloceldaw{
background-color:ffffff;
border-style:solid;
border-color:666666;
border-width:1px; }
.estiloceldag{
background-color:ddeeff;
color:333333;
font-weight:bold;
font-size:10pt; }
</style>
<?php
$criterioid=$_POST["id"];
echo $criterioid;
$critrionombre=$_POST["nombre"];
$catalogo= array();
$datospelicula = array("clave","titulo","sinopsis","genero","anio","precio","status");
function TraeCatalogo()
{
$numregistros=0;
$ar=fopen("catalogo.txt","r") or
die("No se pudo abrir el archivo");
while (!feof($ar)) {
$linea=fgets($ar);
$catalogo[] = $datospelicula =explode("|",$linea);
$numregistros=$numregistros+1;
}
fclose($ar);
echo "numero de registros".$numregistros;
return $catalogo;
}
function Muestralistado($catalogo,$criterioid,$criterionombre)
{
$tabla= "<table><tr colspan=6><td>Clave</td><td>Nombre</td><td>Sinopsis</td><td>Genero</td><td>Año</td><td>precio</td><td>Status</td></tr>";
if (!isset($criterioid) || trim($criterioid) == "")
{
foreach ($catalogo as $k => $pelicula)
{
$clave=$catalogo[$k][0];
$titulo=$catalogo[$k][1];
$sinopsis=$catalogo[$k][2];
$genero=$catalogo[$k][3];
$anio=$catalogo[$k][4];
$precio=$catalogo[$k][5];
$status=$catalogo[$k][6];
$tabla.="<tr><td>".$clave."</td><td>".$titulo."</td><td>".$sinopsis."</td><td>".$genero."</td><td>".$anio."</td><td>".$precio."</td><td>".$status."</td></tr>";}
}else
{
$tabla.="<tr><td colspan=6>hay un criterio de busqueda!</td></tr>";
} $tabla.="<table>";
echo $tabla;
}
$catalogo2=TraeCatalogo("wa");
Muestralistado($catalogo2);
//var_dump($catalogo2);
?>
<html>
<body> Buscar Pelicula: <form action="index.php" method="post">
Nombre: <input type="text" name="nombre"> id: <input type="text" name="id"> <input type="submit">
</form>
</body>
</html>
$foundText = array(); // Create an array to store your found words
Then, once you've opened the file:
while (!feof($ar))
{
$dataBuffer = fgets($ar); // Load some text into buffer
$explodedText = explode($dataBuffer, "|");
foreach($explodedText as $item){
if(strpos($item, $clave) != false)
$foundText[] = $dataBuffer ;
}
}
}
And then you can iterate through each found item:
foreach($foundText as $textItem){
echo 'Word found: ' . $textItem . ' <br>';
}

SQL/PHP query works in PHPmyAdmin but not the site

SQL/PHP query works in PHPmyAdmin but not the site.
I notice that many have had this problem but admittedly I am not as advanced as some of the coders on this site...yet. =) I humbly request any experience you may have laying around :P Thank you.
<?php
// session_start();
// ob_start();
ini_set("display_errors", true);
error_reporting(-1);
// Connection to database.
mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db('') or die(mysql_error());
?>
<?php
// Maintenance page.
$maintenance = 1; // 1 = Site Online || 0 = Site Offline
if ($maintenance == 0) {
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<head>
<style type="text/css">
body {
color:#ffffff;
background-color: #000000;
font-family: Arial, Helvetica, sans-serif;
}
</style>
</head>
<title></title>
</head>
<body>
<center><img src="images/p4flogo.png" /></center><br />
<?php
echo "<br/><br /><center>This site is currently under maintenance.</center>";
} else {
// Start of main website.
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<head>
<style type="text/css">
body {
color:#ffffff;
background-color: #000000;
font-family: Arial, Helvetica, sans-serif;
}
a:link {color: orange; text-decoration: underline; }
a:active {color: red; text-decoration: underline; }
a:visited {color: orange; text-decoration: underline; }
a:hover {color: red; text-decoration: none; }
table {
border-color: #333333;
}
th {
background-color:#ffffff;
color:#000000;
font-family: Arial, Helvetica, sans-serif;
height:30px;
}
td { font-family: Arial, Helvetica, sans-serif;
color:#ffffff;
height:35px;
}
</style>
</head>
<title></title>
</head>
<body>
<table border="0" cellspacing="1" align="center">
<tr><td>
<center><img src="images/p4flogo.png" /></center><br /><br />
<form action="" method="post">
Search for a soldier: <input type="text" name="value" size="35" /><input type="submit" value="search" /><br />
<?php
if (isset($_POST['value']) && !empty($_POST['value'])) {
$value = mysql_real_escape_string($_POST['value']);
// query to database for soldier stats
// query works in phpmyadmin but not on site.
$sql = "
SELECT
`Name`,
MAX(`Level`),
`Class`,
SUM(`Kills`),
SUM(`Deaths`),
SUM(`Points`),
SUM(`TotalTime`),
SUM(`TotalVisits`),
`CharacterID`
FROM
`Characters`
WHERE
`Name` LIKE '$value%' OR `CharacterID` LIKE '$value'
GROUP BY
`Name`,
`Class`,
`CharacterID`
ORDER BY
`Name` ASC;";
$query = mysql_query($sql);
$numrow = mysql_num_rows($query);
if ($numrow >= 1) {
echo "<br /><b>View TOP 100 Players!</b><br />";
echo "<table border=\"1\" cellspacing=\"0\" cellpadding=\"5\"> ";
echo "<th>Soldier Name</th><th>Level</th><th>Class</th><th>KDR</th><th>Kills</th><th>Deaths</th><th>Points</th><th>Hours Played</th><th>Total Visits</th><th>CharacterID</th>";
echo "<br />";
WHILE ($row = mysql_fetch_assoc($query)) {
$SoldierName = $row['Name'];
$Level = $row['Level'];
$Class = $row['Class'];
if ($Class == NULL | empty($Class)) {
$Class = '<center>n / a</center>';
}
if ($Class == 1) {
$Class = 'Assault';
}
if ($Class == 2) {
$Class = 'Recon';
}
if ($Class == 3) {
$Class = 'Medic';
}
if ($Class == 4) {
$Class = 'Engineer';
}
echo $Kills = $row['Kills'];
if ($Kills == 0) {
$Kills = 1;
}
$Deaths = $row['Deaths'];
if ($Deaths == 0) {
$Deaths = 1;
}
$Kdr = round($Kills / $Deaths, 2);
$Points = $row['Points'];
$TimePlayed = $row['TotalTime'];
if ($TimePlayed == 0) {
$TimePlayed = 1;
} else {
$TimePlayed = round(($TimePlayed / 3600), 0);
}
$TotalVisits = $row['TotalVisits'];
$CharacterID = $row['CharacterID'];
echo "<tr>";
echo "<td><b>$SoldierName</b></td>";
echo "<td>$Level</td>";
echo "<td>$Class</td>";
if ($Kdr > 3.9) {
echo "<td><font color=\"red\"><b>$Kdr</b></font></td>";
} else if ($Kdr > 2.5 && $Kdr < 4) {
echo "<td><font color=\"orange\"><b>$Kdr</b></font></td>";
} else {
echo "<td><font color=\"limegreen\">$Kdr</font></td>";
}
echo "<td>$Kills</td>";
echo "<td>$Deaths</td>";
echo "<td>$Points</td>";
echo "<td>$TimePlayed</td>";
echo "<td>$TotalVisits</td>";
echo "<td>$CharacterID</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "No player found with that name. Please try again.";
}
} else {
if (empty($_POST['value'])) {
echo "<font color=\"red\">You must enter a search value.</font>";
}
// query to p4f database for top 100 players.
$sql = "SELECT * FROM `Characters` WHERE `Points` > 1 GROUP BY `Name` ORDER BY `Points` DESC LIMIT 100;";
$query = mysql_query($sql);
echo "<h3>TOP 100 PLAYERS</h3>";
echo "<table border=\"1\" cellspacing=\"0\" cellpadding=\"5\"> ";
echo "<th></th><th>Soldier Name</th><th>Level</th><th>Class</th><th>KDR</th><th>Kills</th><th>Deaths</th><th>Points</th><th>Hours Played</th><th>Total Visits</th><th>CharacterID</th>";
// echo "Made it to loop!";
$Rank = 1;
WHILE ($row = mysql_fetch_assoc($query)) {
$SoldierName = $row['Name'];
$Level = $row['Level'];
$Class = $row['Class'];
if ($Class == NULL | empty($Class)) {
$Class = '<center>n / a</center>';
}
if ($Class == 1) {
$Class = 'Assault';
}
if ($Class == 2) {
$Class = 'Recon';
}
if ($Class == 3) {
$Class = 'Medic';
}
if ($Class == 4) {
$Class = 'Engineer';
}
$Kills = $row['Kills'];
if ($Kills == 0) {
$Kills = 1;
}
$Deaths = $row['Deaths'];
if ($Deaths == 0) {
$Deaths = 1;
}
$Kdr = round($Kills / $Deaths, 2);
$Points = $row['Points'];
$TimePlayed = $row['TotalTime'];
if ($TimePlayed == 0) {
$TimePlayed = 1;
} else {
$TimePlayed = round(($TimePlayed / 3600), 0);
}
$TotalVisits = $row['TotalVisits'];
$CharacterID = $row['CharacterID'];
echo "<tr>";
echo "<td>$Rank</td>";
echo "<td><b>$SoldierName</b></td>";
echo "<td>$Level</td>";
echo "<td>$Class</td>";
if ($Kdr > 3.9) {
echo "<td><font color=\"red\"><b>$Kdr</b></font></td>";
} else if ($Kdr > 2.5 && $Kdr < 4) {
echo "<td><font color=\"orange\"><b>$Kdr</b></font></td>";
} else {
echo "<td><font color=\"limegreen\">$Kdr</font></td>";
}
echo "<td>$Kills</td>";
echo "<td>$Deaths</td>";
echo "<td>$Points</td>";
echo "<td>$TimePlayed</td>";
echo "<td>$TotalVisits</td>";
echo "<td>$CharacterID</td>";
echo "</tr>";
$Rank++;
}
echo "</table>";
}
}
?>
</td></tr>
</table>
</body>
</html>
I'm not sure about MySQL, but I know that in SQL when you do an aggregate function, like SUM(Kills), then you can't reference the row via $row['kills']. I don't know if this is your problem, but you could try doing SUM(Kills) as 'kills' in your SELECT statement. Doing this for your aggregate SELECTs will allow you to reference them all this way.

Categories