2

I got little problem with my code... because I try to SELECT sth from database and then INSERT some value to another table, but in normal code from w3school and I got error

Tryingo to get property of non-object

Here is my code:

<?php 
    session_start();

    function connectionDB(){
        $host = "localhost";
        $username = "root";
        $password = "";
        $db_name = "project";

        $conn = new mysqli($host, $username, $password, $db_name);
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        } 
        return $conn;
    }
    function getID(){
        $id = $_GET['id'];

        return $id;
    }
    $login =$_SESSION['login'];
    $conn =connectionDB();
    $idCar = getID();
    echo $idCar;
    $sqluser = "SELECT ID_USER FROM login_table WHERE LOGIN = $login";

    if($result->num_rows > 0)
    $result = $conn->query($sqluser);
    {
        while($row = $result->fetch_assoc())
        {
            $sql = "INSERT INTO cart (id_user) VALUES ('".$row['ID_USER']."')";
        }
    }else echo"error";
?>

THIS IS THE CODE OF SIDE WITH PRODUCT

11
  • Please tell me on which line you are facing error? Commented Jan 21, 2016 at 12:37
  • The error is in line 28 $result = $conn->query($sqluser); Notice: Trying to get property of non-object in C:\xampp\htdocs\car-repair\insert.php on line 28 Commented Jan 21, 2016 at 12:39
  • @MaciekWiśniewski your statement sequence is wrong. Use $result = $conn->query($sqluser); before if loop Commented Jan 21, 2016 at 12:42
  • @MaciekWiśniewski: so what result you are getting? Commented Jan 21, 2016 at 12:45
  • @Abp Yeah i changed it but is still the same error, in line with if line if($result->num_rows >= 0) Commented Jan 21, 2016 at 12:46

1 Answer 1

2

Please see change near your IF loop

    $sqluser = "SELECT ID_USER FROM login_table WHERE LOGIN = $login";
    $result = $conn->query($sqluser);  //check result first

    if($result->num_rows > 0)  //get number of rows
    {
        while($row = $result->fetch_assoc())
        {
            $sql = "INSERT INTO cart (id_user) VALUES ('".$row['ID_USER']."')";
        }
    }else echo"error";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.