0

I'm a newbie with WAMP on Windows7 ; using HTML5 on Chrome browser plus jQuery and a PHP script. WAMP is up and running. I'm not using 'root' and have setup an account named 'my_user' with password 'my_password'. Through phpMyAdmin I believe I have set the privs correctly for my_user to have access to the taskmanager database. I am able to update things via the mysql console window.

enter image description here

This is a screenshot of my users page.

The connection in PHP code is successful and I'm able to replace the UPDATE code with SELECT code to verify that things are working. It's just that nothing actually gets updated.

$host = "localhost";  // 127.0.0.1 port =  55394 asof 3/9/17
$username = "my_user";
$password = "my_password";
$database = "taskmanager";

try {
    $db = new mysqli( $host, $username, $password, $database);
    if ( ! $db ) {
        echo "Error: call to mysqli with $host, $username, $password, $database failed";
        exit;
    }
}
catch (Exception $e) {
    echo "Exception Message: " . $e->getMessage();
    exit;
}

if ($db->connect_error > 0) {
    die('Unable to connect to database [' . $db->connect_error . ']');
}

I call this PHP script via an ajax POST call from my JavaScript code.

   // console.log( JSON.stringify(dataStore));
    $.ajax({
        url : "taskmanagerSaveTasks.php" ,
        type : 'POST',
        cache: false,
        data : {'whichUser' : forThisUser, 'whichDay': onThisDay, 'jsonData' : JSON.stringify(dataStore)  },
        success : function(res) {
                // Successfully sent data
              console.log(res);
        },
        error: function(err) {
            // Unable to send data
              console.log(err);
        }
    });

I log my UPDATE command string to a text file, for debug purposes and this is what I see.

UPDATE elapsed, users, tasks
      SET elapsed=28000
      WHERE elapsed.day='2017-03-10' AND elapsed.taskid=1 AND tasks.taskid=elapsed.taskid
          AND users.name='jimladeroute' AND users.userid=tasks.userid ;

 success affected=0

You see? The affected list is always zero.

enter image description here

The variable $strSQL is what I'm using to try and do the update. I searched stackoverflow for an existing solution but I don't see one where things pass ok (no query error) and yet nothing gets affected in the database via PHP.

Again, I can update the data using the UPDATE from the SQL COMMAND LINE and from the phpAdmin window. Just can't do it via my own php script.

I changed the setup of strSQL variable to not use the heredoc method, and I didn't see any differences in the result (still no updates to the database).

enter image description here

And here is how I process the inputs.

<?php

    $whichDay = date('Y-m-d'); // this gets you today's date - but on the server which could be in a different timezone!
    $whichUser = 'anybody';    // there is no anybody user unless one is created in the database ; maybe allow this for testing?
    $data = [];

    if(isset($_POST['whichUser'])) {
        $whichUser = $_POST['whichUser'];
    }

    if(isset($_POST['whichDay'])) {
        $whichDay = $_POST['whichDay'];
    }

    if(isset($_POST['jsonData'])) {
        $contents = $_POST['jsonData'];
        $data = json_decode( $contents );
    }

Here is the full text of the PHP script.

<?php

    $whichDay = date('Y-m-d'); // this gets you today's date - but on the server which could be in a different timezone!
    $whichUser = 'anybody';    // there is no anybody user unless one is created in the database ; maybe allow this for testing?
    $data = [];

    if(isset($_POST['whichUser'])) {
        $whichUser = $_POST['whichUser'];
    }

    if(isset($_POST['whichDay'])) {
        $whichDay = $_POST['whichDay'];
    }

    if(isset($_POST['jsonData'])) {
        $contents = $_POST['jsonData'];
        $data = json_decode( $contents );
    }

    //  $contents equals  [{"idnum":"1","category":"HOUSEHOLD","title":"DISHES","elapsed":"10000"},{"idnum":"2","category":"HOUSEHOLD","title":"CLEAN FLOORS","elapsed":"10000"}]

    $filename = "taskdata.json.save.txt";
    $nbytes = file_put_contents( $filename,  "data=".$contents );

    $host = "localhost";  // 127.0.0.1 port =  55394 asof 3/9/17
    $username = "my_user";
    $password = "my_password";
    $database = "taskmanager";

    try {
        $db = new mysqli( $host, $username, $password, $database);
        if ( ! $db ) {
            echo "Error: call to mysqli with $host, $username, $password, $database failed";
            exit;
        }
    }
    catch (Exception $e) {
        echo "Exception Message: " . $e->getMessage();
        exit;
    }

    if ($db->connect_error > 0) {
        die('Unable to connect to database [' . $db->connect_error . ']');
    }

    $safeUser = mysqli_real_escape_string( $db, $whichUser) ;
    $safeDay  =  mysqli_real_escape_string( $db, $whichDay) ;

    $mystring = '';
    foreach ( $data as $jsonObj ) {
        $taskid  =    $jsonObj->{'idnum'} ;
        $elapsedMS =  $jsonObj->{'elapsed'}; // in milliseconds
        $mystring = $mystring . "=================\r\n" ;

        $selStrSQL = <<<SQL1
        SELECT * FROM elapsed AS e, tasks AS t, users AS u 
        WHERE e.day='$safeDay' AND e.taskid=$taskid AND t.taskid=e.taskid
              AND u.name='$safeUser' AND u.userid=t.userid ;
SQL1;

/*        
        $strSQL = <<<SQL
        UPDATE elapsed, users, tasks
           SET elapsed=$elapsedMS
           WHERE elapsed.day='$safeDay' AND elapsed.taskid=$taskid AND tasks.taskid=elapsed.taskid
                 AND users.name='$safeUser' AND users.userid=tasks.userid ;
SQL;
*/

        $strSQL = "UPDATE elapsed, users, tasks SET elapsed=" . $elapsedMS . " WHERE elapsed.day='" . $safeDay ."' AND elapsed.taskid=" . $taskid . " AND tasks.taskid=elapsed.taskid AND users.name='" . $safeUser . "' AND users.userid=tasks.userid ;" ;

  //      $mystring = $mystring . $strSQL . "\r\n" ;

        $result = $db->query( $strSQL );
        if ( $result === false ) {
            echo "Error updating record: " . $db->error ;
            $mystring = $mystring . " error " . $db->error . "\r\n" ;  
        } else {
            echo "Record update successfully affected=" . $db->affected_rows . "\r\n";
            $mystring = $mystring . " success affected=" . $db->affected_rows . "\r\n" ;
        }
    }

$nbytes = file_put_contents( "taskdata.sql.txt" , $mystring );

$db->close();

?>

Here is the modified PHP code - now using prepared statements. Doing this did not resolve the problem. Things are still not getting updated in the database.

    $safeUser = mysqli_real_escape_string( $db, $whichUser) ;
    $safeDay  =  mysqli_real_escape_string( $db, $whichDay) ;
    $mystring = '';

    $strSQL = "UPDATE elapsed, users, tasks SET elapsed=? WHERE elapsed.day=? AND elapsed.taskid=? AND tasks.taskid=elapsed.taskid AND users.name=? AND users.userid=tasks.userid" ;
    if ( !($stmt = $db->prepare( $strSQL ))) {
        echo "Prepare failed: (" . $db->errno . ") " . $db->error ;
        $mystring = $mystring . " Prepare failed "  . $db->errno . ") " . $db->error . "\r\n";
    }

    foreach ( $data as $jsonObj ) {
        $taskid  =    $jsonObj->{'idnum'} ;
        $elapsedMS =  $jsonObj->{'elapsed'}; // in milliseconds
        $catname =    $jsonObj->{'category'}; 
        $title =   $jsonObj->{'title'};

        $mystring = $mystring . "=================\r\n" ;
        $mystring = $mystring . "UPDATE using $taskid, $catname, $title, elapsed=$elapsedMS \r\n" ;

        if ( !$stmt->bind_param( "isis", $elapsedMS,  $safeDay, $taskid, $safeUser ) ) {
            echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error ;
            $mystring = $mystring . " Binding parameters failed " . $stmt->errno . ") " . $stmt->error . "\r\n" ;
        }

        if ( !$stmt->execute()) {
            echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error ;
            $mystring = $mystring . "execute failed " . $stmt->errno . ") " . $stmt->error . "\r\n";
        }

       $mystring = $mystring . "  affected_rows=" . $db->affected_rows . "\r\n" ;
    }

$nbytes = file_put_contents( "taskdata.sql.txt" , $mystring );

$db->close();
Francisco
  • 10,918
  • 6
  • 34
  • 45
J. Laderoute
  • 313
  • 2
  • 13
  • 1
    can you try removing << – Satya Mar 10 '17 at 01:56
  • 2
    really? images of code? here's an [image of a rough solution](https://icanhazcode.com/img/rough.jpg) – Jaromanda X Mar 10 '17 at 01:57
  • 1
    Isolate the issue. Is the AJAX an issue? – chris85 Mar 10 '17 at 01:59
  • 1
    I would recommend re-crafting your SQL strings to follow the lines of `$strSQL = "UPDATE ... WHERE elapsed.day = " . $safeDay . " AND ..."`, or better yet, use parameterised queries. – Obsidian Age Mar 10 '17 at 01:59
  • Tried using = "" instead of << – J. Laderoute Mar 10 '17 at 02:06
  • I will look into how to use parameterised queries ; is that the recommended approach for PHP MySql queries ? Thank you Obsidian Age. – J. Laderoute Mar 10 '17 at 02:07
  • Heredocs quote style should work too, but it just looks bad due to the fact you can't indent the closing quote tag. – StackSlave Mar 10 '17 at 02:08
  • I don't see how it can be an AJAX issue. I can see that the ajax call works, and that the php script does get invoked. It's just that the database does not get updated. If I take the same SQL STRING and copy&paste into the phpMyAdmin QUERY window it works. Just does not work via the PHP script. From what I can tell. – J. Laderoute Mar 10 '17 at 02:09
  • Your script is at risk of [SQL Injection Attack](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Have a look at what happened to [Little Bobby Tables](http://bobby-tables.com/) Even [if you are escaping inputs, its not safe!](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) Use [prepared parameterized statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) – RiggsFolly Mar 10 '17 at 02:11
  • @JaromandaX :) I think that solved it – RiggsFolly Mar 10 '17 at 02:12
  • Can you show how you process the data `'whichUser', 'whichDay'` etc (after passing from AJAX) on the PHP script? – Anne Mar 10 '17 at 02:15
  • Anne, I've updated my question to include that information for you. – J. Laderoute Mar 10 '17 at 02:18
  • @Jaromanda X ; sorry. I used images partly to show the line numbers, partly because I was trying to make things easier on myself. I stick with text for code from now on. – J. Laderoute Mar 10 '17 at 02:23
  • @RiggsFolly - I redid my code using parameters statements. All the calls pass, but the database still is not getting updated. – J. Laderoute Mar 10 '17 at 03:59

1 Answers1

0

Well, after all the code changes that I made; I decided to click on the WAMP icon in the taskbar and choose 'Restart All Services' ; after doing that, the updates started working. Go figure !!!

J. Laderoute
  • 313
  • 2
  • 13