1

Hi I had searched a lot on this site for help, but more I search more I'm confused.

I have one table competition where there is field ID(primary key) Player *TeamName*(3 players in a team) and Score(players)

      competition                     TeamCompetition

Player : TeamName : Score       :  TeamName  :  TeamScore
------ : -------- : -----       :  ----------------------
 Tom   :   team1  :   50        :   team1    :  50+66+35=151
Brian  :   team1  :   66        :   team2    :  54+85+...etc
 Tim   :   team1  :   35        :   
Calvin :   team2  :   54        :
Jerry  :   team2  :   85        :

etc.

I have managed to make SUM in SQL Like so:

$result1 = mysql_query("SELECT SUM(Score) AS team1 FROM competition WHERE TeamName='team1' ");

I tried to save that variable $team1 to new table called TeamCompetition and where sum of one team is saved like one number with name of a team

$row1= mysql_fetch_array($result1);

$team1= $row1['team1'];

$sql1=("INSERT INTO TeamCompetition (TeamScore)
        VALUES '$_POST[team1]' 
        WHERE TeamName='team1' ");

But that wont work, can anybody suggest me how to deal with this code, OR is there another more eleganth way to solve it? If I echo it without $sql1 it shows result why can't I save it...?

pero furid
  • 17
  • 5
  • 2
    your code is open for sql injection you need to escape all request from user .. and you are using obsolete api (Mysql_*) so either use pd or mysqli or IMO only use pdo check [Why shouldn't I use mysql_* functions in PHP?](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php/14110189#14110189) – NullPoiиteя Feb 22 '13 at 11:13
  • 1
    Do you need to calculate the team score for a specific team, or can they all be done in one go? If the latter then @sjdaws answer is good, otherwise ppeterka has a solution for the individual insert/update. – Raad Feb 22 '13 at 11:31
  • I had tried to do one team by one, and now its everything in blur for me, I'm testing now all this codes I'll inform you ow it went – pero furid Feb 22 '13 at 11:40
  • 1
    It doesn't need to go one by one if there is better solution – pero furid Feb 22 '13 at 11:43

2 Answers2

3

The basic solution to your SQL syntax issue is:

$sql1=("INSERT INTO TeamCompetition (TeamScore, TeamName)
    VALUES ('".$_POST[team1]."','team1'");

As there is no row currently in the DB woth the teamname, you should create it. Also, notice that the $_POST is an array, not handled well in evaluated scripts.

However, I assume you'd like to updtae this as you get scores:

$sql1=("UPDATE TeamCompetition set TeamScore = '".$_POST[team1]."'
    WHERE TeamName = 'team1'");

But there is one neat trick in MySQL, the INSERT.... ON DUPLICATE KEY UPDATE feature:

$sql1=("INSERT INTO TeamCompetition (TeamScore, TeamName)
    VALUES ('$_POST[team1]','team1'
    ON DUPLICATE KEY UPDATE TeamScore = '".$_POST[team1]."'" );

There is however one thing I can't go by: this code reeks of SQL injection

  • either use PDO (generally best solution)
  • and/or don't use any data coming from untrusted, or easy to manipulate sources wihtout verifying, and properly handling them (worse solution, but way better than nothing)

The least effort protection for this code (as long as these functions are still supported, noted by the awesome NullPointer) can be using mysql_real_escape_string, but still, this whole thing is going to be deprecated, so it should not be used for new developments:

$sql1=("INSERT INTO TeamCompetition (TeamScore, TeamName)
    VALUES ('".mysql_real_escape_string($_POST[team1])."','team1'
    ON DUPLICATE KEY UPDATE TeamScore = '".$_POST[team1]."'" );

So if you have to patch up an old code, that is going to stay that way, you can decide to use this, but only after evaluating the possibilities of using PDO! If there is only a slight possibility of using PDO, then that is the way to go (with courtesy of the PHP PDO documentation):

<?php
try {
    //open connection, this is different than in the old functions
    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);

    //***running query
    //**step1: create statement
    $stmt = $dbh->prepare("INSERT INTO TeamCompetition (TeamScore, TeamName)
    VALUES (:teamScore,:teamName)
    ON DUPLICATE KEY UPDATE TeamScore = :teamScore "); //notice parameters prefixed with ':'

    //**step2: bind values
    $stmt->bindValue(':teamScore', $_POST[team1]);
    $stmt->bindValue(':teamName', 'team1');

    //**step3: exexcute statement
    $stmt->execute();

    $dbh = null;
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}
?> 
ppeterka
  • 20,583
  • 6
  • 63
  • 78
  • FYI mysql_* function are deprecated and no longer maintained by community .... also new version of pho >=5.5 wont support them and show E_DEPRECATED error – NullPoiиteя Feb 22 '13 at 11:18
  • @NullPointer I think with the last two snippets, not anymore... Sorry, if it wasn't clear, my point was - as OP seemed not to be very seasoned regarding these - to provide a detailed, (small) step by (small) step explanation about these issues. I could have done a "here is teh codez" approach, but I don't usually find that constructive... And I'm a sllllow typer, so everything takes a while to write down – ppeterka Feb 22 '13 at 11:44
  • Thank you for answers but I'm lost in code, thank you for your time and effort. – pero furid Feb 22 '13 at 11:59
3

You could just do it all in one fowl swoop. No need to pass information via PHP at all.

INSERT INTO TeamCompetition (TeamName, TeamScore) VALUES (SELECT TeamName, SUM(Score) FROM competition GROUP BY TeamName)

you need to validation input and your code is vunerable to sql injection check How to prevent SQL injection in PHP?

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. Learn about prepared statements instead, and use PDO or MySQLi

Community
  • 1
  • 1
sjdaws
  • 3,466
  • 16
  • 20
  • INSERT INTO TeamCompetition (TeamName, TeamScore) SELECT TeamName, SUM(Score) FROM competition GROUP BY TeamName; But without VALUES, quick an easy deserve+1 – navjot singh Aug 22 '19 at 10:58