0

I am a beginner in php. I am trying to make an web application where users score is updated for every correct answer he answers. The script is as below

<?php
$username="surendra";
$useranswer=$_REQUEST['option'];
$qno=$_REQUEST['a'];

  $con=mysqli_connect("localhost","root","","gk");

// Check connection

  include('connection.php');
    $sql1="SELECT * FROM questions  WHERE  qid=$qno";
    $result=mysql_query($sql1);
while ($row = mysql_fetch_array($result))
{
    $correctanswer=$row['answer'];

}

   include('connection.php');
     $sql1="SELECT * FROM contest  WHERE  username LIKE '".$username."'";
     $result=mysql_query($sql1);
while ($row = mysql_fetch_array($result))
{
    $points=$row['points'];

}   

    if ($username=$correctanswer)
      {
         $con=mysqli_connect("localhost","root","","gk");
          // Check connection
       if (mysqli_connect_errno())
         {
          echo "Failed to connect to MySQL: " . mysqli_connect_error();
          }

        mysqli_query($con,"UPDATE contest SET points=$points+5
         WHERE username =$username");

          mysqli_close($con);
         }

  ?>

The update function is not working pls help me in this?

3
  • mysql_*() functions are deprecrated and you have huge security flaws in your script (sql injections) that could get you in trouble.
    – mimipc
    Mar 4, 2013 at 15:13
  • 1
    that code is horrible and very racy, as well as highly likely to be vulnerable to SQL injection attacks. Also has a pretty distinct cargo-cult programming smell about it. Looks like you're selecting based on primary key fields, yet use while loops to retrieve what will most likely only ever be a single row of data.
    – Marc B
    Mar 4, 2013 at 15:14
  • Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article
    – TNK
    Mar 4, 2013 at 16:00

3 Answers 3

1

try to enclose $username in single quotation marks:

mysqli_query($con,"UPDATE contest SET points=$points+5 WHERE username = '$username'");

And if ($username==$correctanswer) like the others posted.

Then I recommend you to learn how to bind params and work with prepared statements. Read here

0

you have include('connection.php'); twice in your code.

if ($username=$correctanswer) should be ==.

Consider using mysqli_ functions or PDO and protect your code against SQL injection.

0

You're missing an = sign

if ($username=$correctanswer)
           --^

Try:

if ($username == $correctanswer)

Also, $username needs to be quoted:

mysqli_query($con,"UPDATE contest SET points = $points + 5 WHERE username ='".$username."'");

Not the answer you're looking for? Browse other questions tagged or ask your own question.