0

i'm currently trying to work through a problem where an entry gets added into a database if it doesn't exist. However if it does and the username matches one of the database, it gets updated to whatever the other inputs are. However I am currently getting the error:

sqlsrv_num_rows() expects parameter 1 to be resource

My code is shown below:

 $describeQuery = ("INSERT INTO User 
                  (userID, first_name, last_name)
                   VALUES ('".$Username."', '".$FirstName."', '".$LastName."');");
 $results = sqlsrv_query($conn, $describeQuery);
 if(sqlsrv_num_rows($describeQuery) == 0)
        {
            echo 'New entry added';
        }
        else
        {                   
            $describeQuery2= ("UPDATE User 
                             SET first_name = '".$FirstName."',
                             last_name = '".$LastName."' 
                             WHERE userID = '".$Username."'");
            $results = sqlsrv_query($conn, $describeQuery2);

            $describeQuery3= ("UPDATE Current_Location 
                             SET first_name = '".$FirstName."',
                             last_name = '".$LastName."' 
                             WHERE userID = '".$Username."'");
            $results = sqlsrv_query($conn, $describeQuery3);            

            echo '<br>';
            echo '<br>';
            echo 'Entry updated';

Any help would be appreciated.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
Charliejb
  • 15
  • 6
  • INSERT does not return any rows. Instead try using "INSERT ... ON DUPLICATE KEY UPDATE". Then you won't need to do the subsequent queries. – aynber May 05 '17 at 14:53
  • You can run a SELECT query and see how many rows are already present. Or as @aynber suggested, use ON DUPLICATE KEY UPDATE and let the DB do the work. – LSerni May 05 '17 at 14:53
  • My friend your query is not working try to write a good query statment first of all it contain double quetos inside single which is not true. – Osama May 05 '17 at 14:57
  • @aynber thanks for the suggestion, i'll look into it. – Charliejb May 05 '17 at 15:03
  • 1
    If I'm not horribly mistaken, you're also trying to run the `sqlsrv_num_rows` on the query-string, instead of the actual run query - it should be `sqlsrv_num_rows($results)`, shouldn't it? – junkfoodjunkie May 05 '17 at 15:04
  • I could be mistaken, but I don't think SQL Server has ON DUPLICATE KEY UPDATE. I think that's just a MySQL thing. But there are some alternatives, see [here](http://stackoverflow.com/questions/1197733/does-sql-server-offer-anything-like-mysqls-on-duplicate-key-update) and [here](http://stackoverflow.com/questions/27076348/equivalent-of-mysql-on-duplicate-key-update-in-sql-server). – Don't Panic May 05 '17 at 15:05

0 Answers0