+ Reply to Thread
Results 1 to 7 of 7

Thread: Why doesnt this code work? ( PHP )

  1. #1
    liguehs is offline x10Hosting Member liguehs is an unknown quantity at this point
    Join Date
    Jul 2009
    Posts
    62

    Why doesnt this code work? ( PHP )

    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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <!--
    Design by Free CSS Templates
    http://www.freecsstemplates.org
    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="http://www.w3.org/1999/xhtml">
    <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="http://www.freecsstemplates.org/">Free CSS Templates</a>. Coded and Maintained by <A href="http://aravinthan.x10hosting.com">Aravinthan</a>. </p>
    </div>
    <!-- end #footer -->
    </body>
    </html>
    Thanks for your help,

  2. #2
    xweetok59 is offline x10Hosting Member xweetok59 is an unknown quantity at this point
    Join Date
    Oct 2009
    Posts
    31

    Re: Why doesnt this code work? ( PHP )

    If i was good in it, i should help you. But im not. =(. So I can't help you. =/.

  3. #3
    liketobemad is offline x10Hosting Member liketobemad is an unknown quantity at this point
    Join Date
    Sep 2009
    Posts
    26

    Re: Why doesnt this code work? ( PHP )

    I think this line , I sense something
    PHP Code:
    $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 by liketobemad; 10-12-2009 at 01:15 PM. Reason: I really can't find much problem with it... may be i can see once more.. If u can say ... what output u r getting

  4. #4
    liguehs is offline x10Hosting Member liguehs is an unknown quantity at this point
    Join Date
    Jul 2009
    Posts
    62

    Re: Why doesnt this code work? ( PHP )

    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 by liguehs; 10-12-2009 at 02:55 PM. Reason: Automerged Doublepost

  5. #5
    ah-blabla's Avatar
    ah-blabla is offline x10 Lieutenant ah-blabla is an unknown quantity at this point
    Join Date
    Sep 2009
    Posts
    375

    Re: Why doesnt this code work? ( PHP )

    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 by ah-blabla; 10-12-2009 at 03:17 PM.

  6. #6
    liguehs is offline x10Hosting Member liguehs is an unknown quantity at this point
    Join Date
    Jul 2009
    Posts
    62

    Re: Why doesnt this code work? ( PHP )

    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...

  7. #7
    misson is offline x10 Spammer misson is a jewel in the rough
    Join Date
    Mar 2008
    Location
    Libertatia
    Posts
    2,506

    Re: Why doesnt this code work? ( PHP )

    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 Code:
    <?php
      
    //db.php
    $link = new PDO("mysql:host=localhost;dbname=liguehs_league""...""...");
    $link->setAttribute(PDO::ATTR_ERRMODEPDO::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 Code:
    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));

    Be sure to read all pages linked in this post; they have further information that should prove useful. When asking for help, make sure you follow Eric Raymond's and Jon Skeet's guidelines for prompt, accurate responses. Please answer any questions I ask; they're not rhetorical (probably). Any posted code is intended as illustrative example, rather than a solution to your problem to be copied without alteration. Study it to learn how to write your own solution.
    Misson, not Mission.

+ Reply to Thread

Similar Threads

  1. Php scripts don't work
    By Slicker in forum Free Hosting
    Replies: 4
    Last Post: 11-16-2008, 08:03 AM
  2. Host php code for an adult blog
    By mycamgirl in forum Free Hosting
    Replies: 2
    Last Post: 10-13-2008, 08:27 AM
  3. PHP pages won't work
    By jjpeacha in forum Free Hosting
    Replies: 7
    Last Post: 05-01-2008, 04:05 PM
  4. PHP Mail Code Problem
    By Swiblet in forum Free Hosting
    Replies: 2
    Last Post: 11-04-2007, 08:57 PM
  5. I need help for php code
    By alizwong in forum Scripts & 3rd Party Apps
    Replies: 2
    Last Post: 10-31-2006, 01:19 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
x10hosting free hosting for the masses
dedicated servers