Why doesnt this code work? ( PHP )

liguehs

New Member
Messages
62
Reaction score
0
Points
0
Hi,

I made a php page that retreives data from a MYSQL table. And it checks if the data contains a number if it does, it puts all in one row. If it doesnt it splits into plenty of rows. But for some reason, it doesnt seem to work.

Here is the code:
Code:
<?php
$id = $_GET['id'];
$link = mysql_connect ("localhost", "", "");
mysql_select_db ("liguehs_league", $link);
     $get_trade = mysql_query("SELECT * FROM `trade`  WHERE `id` = '$id'",$link);
     $run_trade = mysql_fetch_array($get_trade) or die(mysql_error());
     $team1 = "" .$run_trade['team1']. "";
     $team2 = "" .$run_trade['team2']. "";
     $players1 = "" .$run_trade['players1']. "";
     $players2 = "" .$run_trade['players2']. "";
$table1 = "
<table>
 <thead>
  <tr>
   <th colspan='7'>$team1</th>
  </tr>
  <tr>
   <th>Nom</th>
   <th>Contrat</th>
   <th>Salaire</th>
   <th>Age</th>
   <th>Off</th>
   <th>Def</th>
   <th>Oa</th>
  </tr>
 </thead>
 <tfoot>
  <tr>
   <th colspan='7'>&nbsp;</th>
  </tr>
 </tfoot>
";
$table2 = "
<table>
 <thead>
  <tr>
   <th colspan='7'>$team2</th>
  </tr>
  <tr>
   <th>Nom</th>
   <th>Contrat</th>
   <th>Salaire</th>
   <th>Age</th>
   <th>Off</th>
   <th>Def</th>
   <th>Oa</th>
  </tr>
 </thead>
 <tfoot>
  <tr>
   <th colspan='7'>&nbsp;</th>
  </tr>
 </tfoot>";
$count1 = substr_count($players1,",");
$count2 = substr_count($players2,",");
$players1 = rawurldecode($players1);
$players1 = explode(",",$players1);
$players2 = explode(",",$players2);
$x1 = 0;
$x2 = 0;
while($count1 > $x1)
{
echo "<br/>$x1<br/>";
$numberOfNumbersFound1 = preg_match("/[0-9]+/", $players1[$x1]);
echo "$players1[$x1] $numberOfNumbersFound1";
if ($numberOfNumbersFound1 == "0" )
{
$get_stats = mysql_query("SELECT * FROM `players`  WHERE `name` = '$players1[$x1]'",$link);
     $run_stats = mysql_fetch_array($get_stats) or die(mysql_error());
     $off = "" .$run_stats['off']. "";
     $def = "" .$run_stats['def']. "";
     $oa = "" .$run_stats['oa']. "";
     $age = "" .$run_stats['age']. "";
     $salary = "" .$run_stats['salary']. "";
     $contract = "" .$run_stats['contract_lenght']. "";
$body1 = "$body1
<tr><td>$players1[$x1]</td><td>$contrat</td><td>$salary</td><td>$age</td><td>$off</td><td>$def</td><td>$oa</td></tr>";
}
else {
$body1 = "$body1
<tr><td colspan='7'>$players1[$x1]</td></tr>";
}
$x1 ++;
}
while($count2 > $x2)
{
$numberOfNumbersFound2 = preg_match("/[0-9]+/", $players2[$x2]);
if ($numberOfNumbersFound2 == "0" )
{
     $get_stats = mysql_query("SELECT * FROM `players`  WHERE `name` = '$players2[$x2]'",$link);
     $run_stats = mysql_fetch_array($get_stats) or die(mysql_error());
     $off = "" .$run_stats['off']. "";
     $def = "" .$run_stats['def']. "";
     $oa = "" .$run_stats['oa']. "";
     $age = "" .$run_stats['age']. "";
     $salary = "" .$run_stats['salary']. "";
     $contract = "" .$run_stats['contract_lenght']. "";
$body2 = "
<tr><td>$player</td><td>$contract</td><td>$salary</td><td>$age</td><td>$off</td><td>$def</td><td>$oa</td></tr>";
}
else
{
$body2 = "
<tr><td colspan='7'>$players2[$x2]</td></tr>";
}
$x2 ++;
}
$close = "</table>";
$response = "$table1 $body1 $close<br/>$table2 $body2 $close";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "[URL]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd[/URL]">
<!--
Design by Free CSS Templates
[URL]http://www.freecsstemplates.org[/URL]
Released for free under a Creative Commons Attribution 2.5 License
Name       : Professional
Description: A two-column, fixed-width design with dark color scheme background.
Version    : 1.0
Released   : 20081230
-->
<html xmlns="[URL]http://www.w3.org/1999/xhtml[/URL]">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>D&eacute;tails des &eacute;changes</title>
<link rel="stylesheet" type="text/css" media="screen" href="../style.css">
<style>
table{
width: 400px;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="header">
 <div id="logo">
  <h1><a href="#">LHS</a></h1>
  <p>Ligue d'Hockey Simule</p>
 </div>
 <!-- end #logo -->
 <?php include("topmenu.php"); ?>
 <!-- end #menu -->
</div>
<!-- end #header -->
<div id="page">
 <div id="header-pic"></div>
 <div id="content">
  <div class="post">
   <h1 class="title">Reponse</h1>
   <div class="entry">
  <Center>
  <?php echo"$response"; ?>
  </center>
   </div>
  </div>
 </div>
 <!-- end #content -->
 <div id="sidebar">
  <div id="sidebar-bgtop"></div>
  <div id="sidebar-content">
   <div id="sidebar-bgbtm">
   <ul>
   <?php include("search.php"); ?>
   <?php include("sidet_menu.php"); ?>
   <?php include("sideb_menu.php"); ?>
   </ul>
  </div>
  </div>
 </div>
 <!-- end #sidebar -->
 <div style="clear:both; margin:0;"></div>
</div>
<!-- end #page -->
</div>
<div id="footer">
 <p>&copy; 2008. All Rights Reserved. Design by <a href="[URL]http://www.freecsstemplates.org/">Free[/URL] CSS Templates</a>. Coded and Maintained by <A href="[URL]http://aravinthan.x10hosting.com">Aravinthan</a[/URL]>. </p>
</div>
<!-- end #footer -->
</body>
</html>

Thanks for your help,
 

xweetok59

New Member
Messages
31
Reaction score
0
Points
0
If i was good in it, i should help you. But im not. =(. So I can't help you. =/.
 

liketobemad

New Member
Messages
26
Reaction score
0
Points
0
I think this line , I sense something
PHP:
$body1 = "$body1
<tr><td>$players1[$x1]</td><td>$contrat</td><td>$salary</td><td>$age</td><td>$off</td><td>$def</td><td>$oa</td></tr>";

It also seems fine..
You haven't said wheter it is working.. some error or not working as required
 
Last edited:

liguehs

New Member
Messages
62
Reaction score
0
Points
0
Oh sorry,
Ok so for the first bloc:
It shows the name correctly but these details:
Code:
$get_stats = mysql_query("SELECT * FROM `players`  WHERE `name` = '$players1[$x1]'",$link);
     $run_stats = mysql_fetch_array($get_stats) or die(mysql_error());
     $off = "" .$run_stats['off']. "";
     $def = "" .$run_stats['def']. "";
     $oa = "" .$run_stats['oa']. "";
     $age = "" .$run_stats['age']. "";
     $salary = "" .$run_stats['salary']. "";
     $contract = "" .$run_stats['contract_lenght']. "";

Doesnt get showed... Its like if it doesnt even go in that if bloc...
Edit:
Ok si I added this:
Code:
echo "$players1[$x1] $numberOfNumbersFound1<br/>";
if ($numberOfNumbersFound1 = "1" )
{
echo "$players1[$x1] $numberOfNumbersFound1 test";
}
Before the other if.

And this is the output:
Dustin Penner 0
Dustin Penner 1 test Andrew Cogliano 0
Andrew Cogliano 1 test 3 Edmonton Oilers 2010 1
3 Edmonton Oilers 2010 1 test
Before the if it shows as 0, but then inside the if it shows as 1.... Something is changing it to 1... What could it be....

I tought maybe because the last one has numbers, but while loop should execute once at a time no? As I put the $x1++ only at the end of the while.....table{width: 400px;}
 
Last edited:

ah-blabla

New Member
Messages
375
Reaction score
7
Points
0
Classic beginners mistake:
= is assignment operator,
== is comparison operator.
In the if statement you are setting $numberOfNumbersFound1 to "1", whereas you want to check whether it is 1, for which you need to write:
Code:
if ($numberOfNumbersFound1 == 1) {do something}
I did the same when I started xD...

Also, you shouldn't have quotes around the 1 if you want to treat it as a number, using quotes treats it as a string. The function preg_match() returns an int, see here. So therefore the variable $numberOfNumbersFound1 is set to a number (of type int). If you were to leave the quotes in, the code would still work, but the string "1" would be converted to a number first, which isn't particularly efficient.
 
Last edited:

liguehs

New Member
Messages
62
Reaction score
0
Points
0
Yeah I saw it and fixed it thou.

Thats why i got these results xD

Or else I get a white page.

But the error is still there...
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
You don't give a clear description of the erroneous behavior. Is the entire page blank? Is just the response section empty? Is there a table with no rows? Do you get rows containing only player names and IDs? What's the URL for a live page, so that we may see for ourselves?

Your script is vulnerable to SQL injection via the 'id' parameter. Also, you should refactor the repeated code (the two table row generating loops and the start of table strings) into functions. A for loop is clearer than a while loop in this instance. Instead of the regexp, you can use is_numeric. Try the
PHP:
 tags when you're posting PHP code; the result is much easier to read and can help you catch some simple syntactical mistakes.

Here's the first few iterations of refactoring (untested):
[php]<?php
  //db.php
$link = new PDO("mysql:host=localhost;dbname=liguehs_league", "...", "...");
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// trade.php
/* $statFields holds the fields from the players table that we're interested in. 
Keys are the column names, values are labels.
 */
$statFields = array(
	'name' => 'Nom', 
	'contract_length' => 'Contrat', 
	'salary' => 'Salaire', 
	'age' => 'Age', 
	'off' => 'Off', 'def' => 'Def', 'oa' => 'Oa'
);

$getTrades = $link->prepare('SELECT team1,players1,team2,players2  
    FROM `trade`  WHERE `id`=?');
$getStats = $link->prepare('SELECT `' . implode('`,`', array_keys($statFields)) . '` 
    FROM `players`  WHERE `name`=?');

// getStatRows() and playerTable() should probably be defined in a separate file
function getStatRows($playersString) {
	global $getStats,$statFields;
	static $fieldCnt = count($statFields);

	$players = explode(",",rawurldecode($playersString));
	$count=count($players);
	$rows=array();
	for($i=0;$i < $count ;++$i) {
		if (is_numeric($players[$i]) ) {
			$rows[] = "<tr><td colspan='$fieldCnt'>$players[$i]</td></tr>\n";
		} else {
			$stats = $getStats->execute(array($players[$i]))->fetch();
			$rows[] = "<tr><td>" . implode('</td><td>', $stats). "</td></tr>\n";
		}
	}
	return implode('', $rows);
}

function playerTable($team, $players) {
	global $statFields;
	static $hdr = '<th>' . implode('</th><th>', $statFields) . '</th>';
	static $fieldCnt = count($statFields);
	$start = "<table>
 <thead>
  <tr><th colspan='$fieldCnt'>$team</th></tr>
  <tr>$hdr</tr>
 </thead>
 <tfoot>
  <tr><th colspan='$fieldCnt'>&nbsp;</th></tr>
 </tfoot>
";
	return $start . getStatRows($players) . '</table>';
}

// now that everything's set up, do the work
try {
	$trade = $getTrades->execute(array($_GET['id']))->fetch();
	$response = playerTable($trade['team1'], $trade['players1']) . '<br/>' 
		. playerTable($trade['team2'], $trade['players2']);
} catch (PDOException $exc) {
	$response = "Internal error. It's been logged and we'll look into it.";
	error_log((string)$exc);
}
?>

You could further refactor to produce a grid view class that you can then use to display any query result in a table, and a data access layer that handles all of the SQL queries for you.

Note that the above implementation of getStatRows runs a separate query for each named player, which is inefficient. Here's an alternate implementation that runs a single query for each team, but sacrifices the clarity and security of prepared queries and doesn't preserve the order of players.
PHP:
function formatRow($row) {
	return "<tr><td>" . implode('</td><td>', $row) . "</td></tr>\n";
}

function getStatRows($playersString) {
	global $link,$statFields;
	static $fieldCnt = count($statFields);
	static $getStats = 'SELECT `' . implode('`,`', array_keys($statFields)) . "` FROM `players`  WHERE `name` IN ('";
	$nums = array();
	$names = array();
	$rows = array();
	$players = explode(",",rawurldecode($playersString));
	foreach ($players as $player) {
		if (is_numeric($player)) {
			$rows[] = "<tr><td colspan='$fieldCnt'>$players[$i]</td></tr>\n";
		} else {
			$names[] = $player;
		}
	}
	$stats = $link->query($getStats . implode("','", $names) . "')")->fetchAll(PDO::FETCH_NUM);
	
	return implode('', array_merge(array_map('formatRow', $stats), $rows));
}
 
Top