-2

but i do not understand what i am doing wrong and why it is not working ?

Seems like it connects with DB, but it wont update DB table.

My PHP code

<?php
        $host = 'localhost';
        $db_name = 'db_name';
        $db_user = 'user'; 
        $db_password = 'password';

        $con = mysqli_connect($host, $db_user, $db_password, $db_name);
            if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}
        function _VoteReward($custom)
             {
                $sql = "UPDATE `users` SET `gold` = `gold` + 50000 WHERE `id` = '".$custom."' ";

                mysqli_query($con, $sql);
            }


            $custom = $_POST["custom"];
            $key = $_POST["key"];
            $result = false;

                if (($custom > 0) && ($key == 'key'))
            { 
                $result = true;
                _VoteReward($custom);

                }
    mysqli_close($con);

 ?> 
WikStar
  • 11
  • 1
  • 6
  • 3
    You don't know what's wrong because you don't check for errors in your code. Never assume the code is always going to work flawlessly. Use [`mysqli_error()`](http://php.net/manual/en/mysqli.error.php) to get a detailed error message from the database. – John Conde May 25 '18 at 12:48
  • 1
    Your script is at risk of [SQL Injection Attack](//stackoverflow.com/questions/60174) Have a look at what happened to [Little Bobby Tables](http://bobby-tables.com/) Even [if you are escaping inputs, its not safe!](//stackoverflow.com/questions/5741187) Use [prepared parameterized statements](https://php.net/manual/en/mysqli.quickstart.prepared-statements.php). – John Conde May 25 '18 at 12:49
  • @JohnConde There is no error, if i take the syntax out of the function and load the file it works. But it wont work in function! – WikStar May 25 '18 at 12:59
  • `$con` is not in scope within `_VoteReward`. – deceze May 25 '18 at 13:00
  • Thanks @daceze that was the problem – WikStar May 25 '18 at 13:02

1 Answers1

1

The above code does actually produce a connection to the database. However, the resulting connection does need to be checked for errors. Typically by the following:

if(!$con)
{ // creation of the connection object failed
    die("connection object not created: ".mysqli_error($con));
}

if (mysqli_connect_errno()) 
{ // creation of the connection object has some other error
    die("Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
}
bginsburg
  • 123
  • 4