Monday 3 September 2018

PHP basic mysqli :: query () does not work

    $query = "SELECT webpage_id FROM s_w WHERE s_w_id=? LIMIT 1";
    $stmt = $connect->prepare($query);
    $stmt->bind_param("i", $s_w_id);
    $stmt->execute();
    $stmt->bind_result($webpage_id);

while($stmt->fetch()){
        echo $webpage_id;  //it echos ot $webpage_id correctly which means my prepared statement works

        $query2 = "INSERT INTO webpage_point (webpage_id, point_ip) VALUES ($webpage_id, '$ip')";
        $connect->query($query2); // however this code does not work. It does not insert anything into webpage_point. Whats wrong with this basic line?
}

Note that: i am getting $ip(varchar(50)) correctly. I am sure about that too. Just two basic line and it drives me mad.
VERY IMPORTANT EDIT: I changed my prepared statement with a normal query and it worked.
    $query = "SELECT webpage_id FROM s_w WHERE s_w_id=$s_w_id LIMIT 1";
    $result = $connect->query($query);

while($row = $result->fetch_array()){
        $webpage_id = $row['webpage_id'];

        $query = "INSERT INTO webpage_point (webpage_id, point_ip) VALUES ($webpage_id, '$ip')";
        $connect->query($query);
}

So there is something wrong about mysqli prepared statements.

You are only fetching and inserting 1 row, so you don't really need 2 sql statements and a loop.
What you could do, is something like:
INSERT INTO webpage_point (webpage_id, point_ip)
SELECT webpage_id, '$ip' FROM s_w WHERE s_w_id=? LIMIT 1"

Note that you should bind the second variable - $ip - as well, this is just to show the complete sql in an easy way.

0 comments:

Post a Comment