Problem with adding record to table MySQL, PHP

I have a problem with MySQL query. The main thing is that my MySQL query which is inserted to PHP code partly works.

$q = "INSERT INTO `users` (`nickname`, `name`, `surname`, `password`, `department`, `position`, `accountcreated`, `avatarurl`) VALUES ('$nickname','$name','$surname', '$passworda', '$department', '$position', '$nowdate', '$createavatar') ";

mysqli_query($conn, $q);

Partly? I'll explain it to you. Of course this code is inserted in "if", which is created to inform me about succcess or fail of code execution.

Everytime shows me "success", but the records doesn't show up in MySQL table. It's not adding. So i thought that somehow maybe is a problem with query. I copyed query, changed varriables with normal words and there it is! Query works fine, but the wierd thing is that ID from AutoIncrement is not for example: 3, what it should be, because i have two records in table already, but it's 6. The ID rised everytime when i pushed "Do" button, but only ID without the records.

I checked of course all varriables. I can echo them one by one and works fine.

Of course the other queries which i execute works perfect. It's just for information.

1 answer

  • answered 2018-10-11 19:21 spencer7593

    Check the return from mysqli_query. It will return FALSE when there is an error.

    For example:

    if (!mysqli_query($conn, $q)) {
        printf("Error: %s\n", mysqli_error($conn));
        printf("SQL: %s\n", $q);
    }
    

    From the code shown in the question, we're guessing that no check is being performed. The code is putting its figurative pinky finger to the corner of its figurative mouth Dr. Evil style "I just assume it will all go to plan. What?"


    Also, the pattern in the code appears to be vulnerable to SQL. (Not enough code shown to make that determination, it could be that the variables are returned from mysqli_real_escape_string. Consider using prepared statements with bind placeholders.

    Also, if you're not overly invested into the procedural style, consider switching to the object oriented style.