Eduardo
Eduardo

Reputation: 5

Data not inserting into database to a table

I am trying to insert data into a database after the user clicks on a link from file one.php. So file two.php contains the following code:

$retrieve = "SELECT * FROM catalog WHERE id = '$_GET[id]'";
$results = mysqli_query($cnx, $retrieve);
$row = mysqli_fetch_assoc($results);
$count = mysqli_num_rows($results);

So the query above will get the information from the database using $_GET[id] as a reference. After this is performed, I want to insert the information retrieved in a different table using this code:

$id = $row['id'];
$title = $row['title'];
$price = $row['price'];
$session = session_id();

if($count > 0) {
    $insert = "INSERT INTO table2 (id, title, price, session_id)
            VALUES('$id', '$title', '$price', '$session');";
    }

The first query $retrieve is working but the second $insert is not. Do you have an idea why this is happening? PS: I know I will need to sanitize and use PDO and prepared statements, but I want to test this first and it's not working and I have no idea why. Thanks for your help

Upvotes: 0

Views: 426

Answers (2)

lingo
lingo

Reputation: 1908

Here's an example of your query in PDO if you'req planning to use PDO in future.

$sql = $pdo->prepare("INSERT INTO table2 (id, title, price, session_id) VALUES(?, ?, ?, ?");
$sql->bindParam(1, $id);
$sql->bindParam(2, $title);
$sql->bindParam(3, $price);
$sql->bindParam(4, $session_id);
$sql->execute();

That's how we are more safe.

Upvotes: 0

Funk Forty Niner
Funk Forty Niner

Reputation: 74216

You're not executing the query:

$insert = "INSERT INTO table2 (id, title, price, session_id)
        VALUES('$id', '$title', '$price', '$session');";
}

it needs to use mysqli_query() with the db connection just as you did for the SELECT and make sure you started the session using session_start(); seeing you're using sessions.

$insert = "INSERT INTO table2 (id, title, price, session_id)
        VALUES('$id', '$title', '$price', '$session');";
}


$results_insert = mysqli_query($cnx, $insert);

basically.

Plus...

Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.

If that still doesn't work, then MySQL may be complaining about something, so you will need to escape your data and check for errors.

Sidenote:

Use mysqli_affected_rows() to check if the INSERT was truly successful.

Upvotes: 1

Related Questions