As the title says Im trying to do a simple insert, but nothing actually is inserted into the table. I try to print out errors, but nothing is reported.
My users table has many more fields than these 4, but they should all default.
$query = 'INSERT INTO users (username, password, level, name) VALUES (?, ?, ?, ?)';
if($stmt = $db -> prepare($query))
{
$stmt -> bind_param('ssis', $username, $password, $newlevel, $realname);
$stmt -> execute();
$stmt -> close();
echo 'Any Errors: '.$db->error.PHP_EOL;
}
There are no errors given, but when I go to look at the table in phpmyadmin there is not a new row added. I know for sure that the types are correct (strings and integers). Is there something really wrong here or does it have something to do with the fact that I'm ignoring other columns. I have about 8 columns in the user table.
If you have turned auto commit off, you will have to explicitly call the commit method after you execute the query.
$stmt->execute();
$db->commit();
$stmt->close();
You have to check for errors at each stage of the process: When you connect, when you prepare the statement, when you bind, when you execute, and when you close. In your code, assuming the $db handle was properly created, the error check happens after the ->close() call, which should succeed, so there won't be any error at that point.
Something along these lines will show where things blew up:
$query = 'INSERT INTO users (username, password, level, name) VALUES (?, ?, ?, ?)';
$stmt = $db->prepare($query);
echo 'prepare error: ', $db->error, PHP_EOL;
$stmt->execute();
echo 'execute error: ', $db->error
etc....
Check if the string "Any Errors" is being printed. If not, then the statement:
if ($stmt = $db->prepare($query))
is returning false. You should move echo 'Any Errors: '.$db->error.PHP_EOL; outside of the conditional block.
Do u initialize the values of $username, $password, $newlevel, $realname before the
$stmt -> execute(); statement. Otherwise you have to initialize and try
$query = 'INSERT INTO users (username, password, level, name) VALUES (?, ?, ?, ?)';
if($stmt = $db -> prepare($query)){
$stmt -> bind_param('ssis', $username, $password, $newlevel, $realname);
$username='testname';$password='testpwd';$level=5;$realname='testrealname';
$stmt -> execute(); echo "inserted SuccessFully"; $stmt -> close(); }
else { printf("Prepared Statement Error: %s\n", $mysqli->error);}
try this code. If the query is executed successfully it show the "Inserted Successfully" otherwise it shows the error.
Related
I need help with this query. If I use this query in MySQL that works fine but is not being executed when used in PHP.
$sql = "INSERT INTO dtable (name, mobile, email) VALUES ('".$MP_Name."', '".$MP_Mobil."','".$MP_Email."');";
$conn->query($sql);
Use prepared statements to avoid sql injection.
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare("INSERT INTO dtable (name, mobile, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $MP_Name, $MP_Mobil, $MP_Email);
$stmt->execute();
$stmt->close();
Try to echo the query string before executing it and copy/paste that echoed query in phpmyadmin and check for errors in the query
$result= $sql->query(sprintf("INSERT INTO dtable(name,mobile,email) VALUES ('%s','%s','%s')", ($_POST['MP_Name']), ($_POST['MP_Mobil']), ($_POST['MP_Email'])));
echo $sql;
With more study, I came to know that I was actually getting an error; commands out of sync; you can't run this command now.
I added $conn->next_result() before running the query which solved the issue.
I am creating a user registration system, and I am at the point where I start modifying the database i get the error
"Warning: mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables in /opt/lampp/htdocs/Projectss/01_sarah/index.php on line 41
"
I have tried using every single method in php documentation concerning adding data to the database
here is some code
$hash_password = password_hash($password, PASSWORD_DEFAULT);
$query = "INSERT INTO users (first_name,last_name,email,password) VALUES('$first_name','$last_name','$email','$hash_password')";
$stmt = $conn->prepare($query);
if (!$stmt) {
echo mysqli_error($conn);
}
$stmt->bind_param('ssss', $query);
$stmt->execute(); // execute prepared statement
$conn->close(); // close connection
}
The expected result should is to not receive any warning after saving the information to the database
You're passing complete query in the bindParam and also passing the values in the query instead of this you need to pass the parameters in the bindParam like this..
$hash_password = password_hash($password, PASSWORD_DEFAULT);
$query = "INSERT INTO users (first_name,last_name,email,password) VALUES(?, ?, ?, ?)";
$stmt = $conn->prepare($query);
$stmt->bind_param('ssss', $first_name, $last_name, $email, $hash_password);
$stmt->execute(); // execute prepared statement
$conn->close(); // close connection
I want to perform a select query on my users table with sqli in php.
For security reasons (sql injection) i want to do it using parameter(s).
Also i want to store the result in a php variable.
This is my code:
the $conn variable is filled in correctly.
$login = $_POST['username'];
//Check if username is available
/*Line44*/ $stmt = $conn->prepare("SELECT login FROM users WHERE login = ?");
/*Line45*/ $stmt->bind_param('s', $login);
$result = $stmt->execute();
if ($result->num_rows > 0)
{
echo "This username is in use.";
}
else
{
//Add account to database
$stmt = $conn->prepare("INSERT INTO users (login, password, email, gender) VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $login, $md5pass, $email, $gender);
$stmt->execute();
$stmt->close();
echo "<font color=\"#254117;\">Your account is succesfully geregistered! <br />U can now login!</font>";
}
I get this error:
Warning: mysqli::prepare() [mysqli.prepare]: Couldn't fetch mysqli in
C:\xampp\htdocs\cammerta\registreer.php on line 44
Fatal error: Call to a member function bind_param() on a non-object in
C:\xampp\htdocs\cammerta\registreer.php on line 45
I hope someone can provide an solution and explain to me what i did wrong.
Thanks in advance!
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);
$stmt->execute();
Plus
1.Please run query in phpmyadmin or any program
2.Maybe you not set variables. $login, $md5pass, $email, $gender
$stmt = $conn->prepare statement may be return false.Please use given code for getting error in query.
if ($stmt = $conn->prepare('your query')) {
$stmt->bind_param(...);
}
else {
printf("Error=: %s\n", $conn->error);
}
I think this one should be pretty easy but I am having trouble getting it right. I have searched a bit but being new to prepared statements I can't quite figure out the syntax from looking at other examples I have found here and elsewhere. Anyhow here is my code.
if($stmt = $mysqli -> prepare("INSERT INTO user_info (city, state, website, public_contact, user, zipcode, pic, emailme) VALUES (?, ?, ?, ?, ?, ?, ?,?)
ON DUPLICATE KEY UPDATE (city, state, website, public_contact, user, zipcode, pic, emailme) VALUES (?, ?, ?, ?, ?, ?, ?,?)")) {
$stmt -> bind_param("sssssssi",$city, $state, $website, $public_contact, $user, $zipcode, $pic, $emailme);
$stmt -> execute();
$stmt -> bind_result($result);
$stmt -> close();
}
user is the unique. This IMO is just a syntax problem so could somebody help me out with the correct syntax? Much appreciated.
ETA: just to help trouble shooting this does work as intended when I remove the ON DUPLICATE KEY UPDATE part but obviously, it only allows the one record per user and will not update
UPDATE: was never able to find a working syntax to use the ON DUPLICATE KEY UPDATE so what I did instead (admittedly probably not the most efficient way) was check the table before hand for the user. If the user exist I run and UPDATE, if not I run a INSERT. Below is my working code. Hope this helps somebody who gets stuck in my situation.
$sql = "SELECT * FROM user_info WHERE user='$user'";
if ($result=mysqli_query($mysqli,$sql))
{
/* Return the number of rows in result set */
$rows=mysqli_num_rows($result);
/* Free result set */
mysqli_free_result($result);
}
if($rows == 0) {
if($stmt = $mysqli -> prepare("INSERT INTO user_info (city, state, website, public_contact, user, zipcode, pic, emailme) VALUES (?, ?, ?, ?, ?, ?, ?,?) ")) {
$stmt -> bind_param("sssssssi",$city, $state, $website, $public_contact, $user, $zipcode, $pic, $emailme);
$stmt -> execute();
$stmt -> bind_result($result);
$stmt -> close();
}
} else {
if($stmt = $mysqli -> prepare("UPDATE user_info SET city=?, state=?, website=?, public_contact=?, zipcode=?, pic=?, emailme=? WHERE user='$user'")) {
$stmt -> bind_param("ssssssi",$city, $state, $website, $public_contact, $zipcode, $pic, $emailme);
$stmt -> execute();
$stmt -> bind_result($result);
$stmt -> close();
}
}
The easiest way to use INSERT...ON DUPLICATE KEY UPDATE is to use the VALUES clause in the following way, so you don't need to repeat the parameters in the UPDATE clause. They just use the same values for each column that you passed in the VALUES clause:
if($stmt = $mysqli -> prepare("
INSERT INTO user_info (city, state, website, public_contact,
user, zipcode, pic, emailme)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
city = VALUES(city),
state = VALUES(state),
website = VALUES(website),
public_contact = VALUES(public_contact),
user = VALUES(user),
zipcode = VALUES(zipcode),
pic = VALUES(pic),
emailme = VALUES(emailme)") {
$stmt -> bind_param("sssssssi",$city, $state, $website, $public_contact,
$user, $zipcode, $pic, $emailme);
$stmt -> execute();
$stmt -> close();
}
The IODKU syntax requires that you set each column individually. You can't list them all in one clause like you were trying to do.
You should always report any errors from any call to prepare() or execute(). Or you can make mysqli throw exceptions:
$mysqli -> report_mode = MYSQLI_REPORT_STRICT;
Also, you don't need to bind_result(), since there is no result set from INSERT:
// NO: $stmt -> bind_result($result);
I'd strongly suggest having a look at something like Doctrine DBAL (not ORM) - it allows you to heave key => value pairs and makes these types of operations easier to wield when there's so many values.
You can then do something like:
try {
$conn->insert(
'db.`table`',
[
'city' => $city,
'state' => $state
]);
} catch (Exception $e) {
if( $e->getCode() !== '23000' ) {
throw $e;
}
$conn->update(
'db.`table`',
[
'city' => $city,
'state' => $state
],
[
'user' => $user
]);
}
I am trying to insert into a table with Procedural Mysqli. It is not posting any errors nor is it posting the information to the database. Here is my code:
$query = "INSERT INTO Accounts (FirstName, LastName, Username, Password, Access) VALUES ({$_POST['FirstNameTbx']}, {$_POST['LastNameTbx']}, {$_POST['UsernameTbx']}, {$_POST['PasswordTbx']}, {$_POST['AccessDDL']})";
mysqli_query($link, $query);
mysqli_close($link);
$Error .= "$query";
Update:
I changed to prepared statement, now I am getting:
Warning: mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of elements in type definition string doesn't match number of bind variables in /home/bryantrx/public_html/ec/add_user.php on line 19
There are only 5 variables that need to be bound, and the UserID auto increments, so it doesn't need to be bound or referenced in the statement..
if ($stmt = $link->prepare("INSERT INTO Accounts (FirstName, LastName, Username, Password, Access) VALUES (?, ?, ?, ?, ?)")){
$stmt->bind_param($_POST['FirstNameTbx'], $_POST['LastNameTbx'], $_POST['UsernameTbx'], $_POST['PasswordTbx'], $_POST['AccessDDL']);
$stmt->execute();
$Error .= "success";
$stmt->close();
} else {
echo $link->error;
}
To get an error message you need to call mysqli_error:
$error = mysqli_error($link);
You would also make life easier (and more secure) for yourself if you built your queries using prepare and parameters:
$query = "INSERT INTO Accounts (FirstName, LastName, Username, Password, Access)
VALUES ( ?, ?, ?, ?, ?)";
if ($stmt = mysqli_stmt_prepare($link, $query)) {
mysqli_stmt_bind_param($stmt, "sssss",
$_POST['FirstNameTbx'],
$_POST['LastNameTbx'],
$_POST['UsernameTbx'],
$_POST['PasswordTbx'],
$_POST['AccessDDL']);
if (!mysqli_stmt_execute($stmt)) {
$error = mysqli_stmt_error($stmt);
}
mysqli_stmt_close($stmt);
} else {
$error = mysqli_error($link);
}
mysqli_close($link);
UPDATE - ok, you've swapped to OO which is fine. When using bind_param the first parameter describes the data you are binding. In this case if it is five strings, you would put 5 "s" like so:
$stmt->bind_param("sssss",
$_POST['FirstNameTbx'],
$_POST['LastNameTbx'],
$_POST['UsernameTbx'],
$_POST['PasswordTbx'],
$_POST['AccessDDL']);