4

I am currently learning PHP and am using the query below to insert values into my MySQL table.
I would like to check whether or not the values were inserted correctly. I have tried writing an IF statement and have searched through numerous examples, none of which seem to be working.

I would appreciate any help in steering me in the right direction.

$dd_tracking_insert = $dd_tracking_conn->query("INSERT INTO $dd_tracking_table_name (invoice_id, user_id, gc_bill_id, gc_bill_amount, gc_bill_fees, gc_bill_status, gc_bill_created) VALUES ('$invoice_id', '$user_id', '$gc_transaction_id', '$invoice_amount', '$gc_fees', '$gc_status', now())");

IF inserted correctly - echo "inserted".
If Error: was not inserted -echo "error: values where not inserted correctly."

Link to full code here

5
  • Pdo rowcount is an easy way. Increment your insert loop and check the number of rows in your table at the end. Commented Mar 1, 2016 at 23:49
  • try mysql_affected_rows() php.net/manual/tr/function.mysql-affected-rows.php Commented Mar 1, 2016 at 23:58
  • @mdemir OP is using mysqli_ not mysql_. Plus, if you're going to reference PHP.net, please use English-based. You meant php.net/manual/en/mysqli.affected-rows.php Commented Mar 2, 2016 at 0:02
  • @Fred-ii- sorry for lang. I wasn't aware. Commented Mar 2, 2016 at 0:24
  • @mdemir No worries. Just thought I would let you know that ;-) Cheers Commented Mar 2, 2016 at 0:33

2 Answers 2

4

To check if your INSERT was successful, you can use mysqli_affected_rows().

Returns the number of rows affected by the last INSERT, UPDATE, REPLACE or DELETE query.

Object oriented style

int $mysqli->affected_rows;

Procedural style

int mysqli_affected_rows ( mysqli $link )

And check for errors against your query and for PHP.

References:


Your present code is open to SQL injection if user interaction is involved.

Use mysqli with prepared statements, or PDO with prepared statements.

Sign up to request clarification or add additional context in comments.

Comments

0
if (!$dd_tracking_conn->query("INSERT...")){
    //echo "error: values where not inserted correctly.";
    printf("Error: %s\n", $dd_tracking_conn->error);
}else {
    echo "inserted";
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.