INSERT INTO

Hi:

New to PHP, had several forms which used to work with MYSQL last week, but reinstalled Xampp and nothing inserts. Went online, searched Stackoverflow, MySQL sites, PHP sites, Youtube videos, copied and copied, pasted and testeed all of the latest statements, nothing inserts. Works directly in the PHPMyAdmin interface, but not from HTML forms. These connect.inc.php files were untouched and working, and now not. This is localhost (127.0.0.1), not online.

No error messages, nothing saying I am not connecting, no syntax errors on any lines to fix, just a blank screen after hitting submit and, when I check, the db has no rows added. I went down to one simple field in the HTML, one $_POST[field].

If I got an error, I would research that. Tried the following:

1.) $sql=“INSERT INTO testing (username) VALUES (’$_POST[username]’)”;

2.) $stmt = $db->prepare(“INSERT INTO testing(username) VALUES(:’$_POST[username]’)”);

The first one used to work last week. The second one is copied and pasted from PHP.net.
This is the entire php page:

<?php $con=mysqli_connect("localhost","username","password","test_db"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } if (isset($_POST['username']) && !empty ($_POST['username'])){ $username = $_POST['username']; $sql="INSERT INTO `testing` (username) VALUES ('$_POST[username]')"; $stmt = $db->prepare("INSERT INTO testing(username) VALUES(:'$_POST[username]')"); if (!mysqli_query($con,$stmt)) <<<<<<<<<

Good to see you’re trying to use parameterized queries!

You need to decide if you’re using procedural or object oriented code.
mysqli_connect, mysqli_connect_errno, mysqli_query are part of the procedural way of doing it.
While $db->prepare is object oriented.

I would recommend writing object oriented.

Prepared example from php.net
[php]<?php
$mysqli = new mysqli(“example.com”, “user”, “password”, “database”);
if ($mysqli->connect_errno) {
echo “Failed to connect to MySQL: (” . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

/* Prepared statement, stage 1: prepare */
if (!($stmt = $mysqli->prepare(“INSERT INTO test(id) VALUES (?)”))) {
echo “Prepare failed: (” . $mysqli->errno . ") " . $mysqli->error;
}

/* Prepared statement, stage 2: bind and execute */
$id = 1;
if (!$stmt->bind_param(“i”, $id)) {
echo “Binding parameters failed: (” . $stmt->errno . ") " . $stmt->error;
}

if (!$stmt->execute()) {
echo “Execute failed: (” . $stmt->errno . ") " . $stmt->error;
}[/php]http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php

Sponsor our Newsletter | Privacy Policy | Terms of Service