0

I have the following code which is part of a function to add a user to a database in PHP. It adds a user to a database.

if($user != '' && $pass != ''){
            $new_name_q = "INSERT IGNORE INTO $db_name (`User`, `Password` ,`Name`, `Medals`, `TextSize`)
                                         VALUES ('$user','$pass','$nameComplete', '000000', '18')";
            $new_name_rs = mysqli_query($connection1,$new_name_q);

            if(!$new_name_rs)
            {
                die("No name added: " . mysql_error());
            }
        }

The query works fine and I don't get any duplicates. But I would like to echo a warning to the user in case the query is ignored.

kaya3
  • 47,440
  • 4
  • 68
  • 97
  • 1
    `mysql_error()` doesn't mix with the mysqli_ api, so you never get the (real) error if and when you do get errors. – Funk Forty Niner Sep 11 '18 at 15:32
  • Possible duplicate of [Can I mix MySQL APIs in PHP?](https://stackoverflow.com/questions/17498216/can-i-mix-mysql-apis-in-php) – aynber Sep 11 '18 at 15:34
  • You can try `mysql_affected_rows()` – FedeCaceres Sep 11 '18 at 15:34
  • 1
    Is `User` the `PRIMARY KEY` (or at least `UNIQUE`)? If you've got an auto-incremented id in there as well you may have an issue. You should also use a [prepared statement with bound parameters](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). – CD001 Sep 11 '18 at 15:37

1 Answers1

0

Here's the code you need:

if($user != '' && $pass != ''){
    $new_name_q = "INSERT IGNORE INTO $db_name (`User`, `Password` ,`Name`, `Medals`, `TextSize`)
        VALUES ('$user','$pass','$nameComplete', '000000', '18')";
    $new_name_rs = mysqli_query($connection1,$new_name_q);
    $affected = mysqli_affected_rows($connection1);
    if(!$affected) {
        die("No name added");
    }
}

See http://www.php.net/manual/en/mysqli.affected-rows.php

[I'm assuming here that you've done things like ensuring the variables are properly escaped already]

Chris Lear
  • 6,592
  • 1
  • 18
  • 26