mysqli insert into database - php

Hello all i have this script and i will not insert into the database and i get no errors :S, do you know what it is?
function createUser($username, $password) {
$mysql = connect();
if($stmt = $mysql->prepare('INSERT INTO users (username, password, alder, hood, fornavn, efternavn, city, ip, level, email) VALUES (?,?,?,?,?,?,?,?,?,?)')) {
$stmt->bind_param('ssssssssss',$username,$password, $alder, $hood, $fornavn, $efternavn, $city, $ip, $level, $email);
$stmt->execute();
$stmt->close();
} else {
echo 'error: ' . $mysql->error;
}

Maybe you get an error from the $stmt->execute(); call? Check $stmt->error (which is a string) just before you run $stmt->close();
Maybe some of your values should not be strings, such as the level and/or hood parameters? They look like typical integer parameters.

Related

Inserting data from forms to access by ODBC

I have try to use ODBC to insert data. However, it does not work
This is my code. How can I solve the problem?
<?php
if(isset($_POST['submit']))
{ $ContactPersonID=$_POST['ContactPersonID']
$FirstName=$_POST['First name'];
$LastName=$_POST['Last name'];
$PhoneNumber=$_POST['PhoneNumber'];
$RestaurantID=$_POST['RestaurantID'];
echo $ContactPersonID ." ".$FirstName." ".$LastName." ".$PhoneNumber." ".$PhoneNumber." ".$RestaurantID ;
$con=odbc_connect("Online Food Delivery Database","", "");
$sql="INSERT INTO RestaurantPeopleContact
(ContactPersonID,FirstName,LastName,PhoneNumber,RestaurantID)
VALUES ('$ContactPersonID','$FirstName','$LastName','$FirstName','$PhoneNumber','$RestaurantID')";
if(odbc_exec($con,$sql))
{
echo "Data saved.";
}
else
{
echo "Error";
}
}
?>
You are inserting twice the firstname.
By this reason, the columns declaration doesnt match with the number of variables
Consider using PHP's PDO for the MS Access connection, a better handler to pass parameters and raise needed exceptions and of course to avoid SQL injection especially from web input. You may need to initialize PDO in your .ini file.
Also, ContactPersonID and RestaurantID might be integer values but you look to be quoting them. Parameters help in defining needed data types without worrying about quote enclosures or messy string concatenation.
$ContactPersonID = $_POST['ContactPersonID']
$FirstName = $_POST['First name'];
$LastName = $_POST['Last name'];
$PhoneNumber = $_POST['PhoneNumber'];
$RestaurantID = $_POST['RestaurantID'];
$database = "C:\Path\To\Database\Online Food Delivery Database.accdb";
# PREPARED STATEMENT WITH PLACEHOLDERS
$sql = "INSERT INTO RestaurantPeopleContact
(ContactPersonID, FirstName, LastName, PhoneNumber, RestaurantID)
VALUES (?, ?, ?, ?, ?)";
try {
$dbh = new PDO("odbc:DSN=MS Access Database;DBq=$database;");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $dbh->prepare($sql);
# BIND PARAMETERS
$sth->bindParam(1, $ContactPersonID, PDO::PARAM_INT);
$sth->bindParam(2, $FirstName, PDO::PARAM_STR);
$sth->bindParam(3, $LastName, PDO::PARAM_STR);
$sth->bindParam(4, $PhoneNumber, PDO::PARAM_STR);
$sth->bindParam(5, $RestaurantID, PDO::PARAM_INT);
$sth->execute();
}
catch(PDOException $e) {
echo $e->getMessage()."\n";
}
# close the connection
$dbh = null;

Using AES_ENCRYPT in Prepared Statement with Bind Variables

Wanting to encrypt a particular data variable but keep getting "PHP Fatal error: Call to undefined function AES_ENCRYPT()..."
Research has lead me to a hint that it's using PHP instead of MySQL?
$key="xyz";
$stmt = mysqli_prepare($mysqli, "INSERT INTO details (FirstName, LastName, EncryptThis) VALUES (?,?,?)");
if ($stmt === false) {
trigger_error('Statement failed! ' . htmlspecialchars(mysqli_error($mysqli)), E_USER_ERROR);
}
$bind = mysqli_stmt_bind_param($stmt, "sss", $FirstName, $LastName, AES_ENCRYPT('$EncryptThis','$key'));
if ($bind === false) {
trigger_error('Bind param failed!', E_USER_ERROR);
}
$exec = mysqli_stmt_execute($stmt);
Am using varbinary in the DB...
Have tried various uses of
AES_ENCRYPT('$EncryptThis','$key')
EG
AES_ENCRYPT($EncryptThis,$key)
etc etc
MySQL is expecting values to be be passed as bind parameters. Not names of functions or other SQL expressions. Just values.
If you want to invoke the MySQL AES_ENCRYPT function, that needs to be appear as part of the SQL text (the string prepared as a SQL statement). The name of the function can't be passed as a part of a bind parameter.
Like this:
"INSERT ... VALUES ( ? , ? , AES_ENCRYPT( ? , ? ) )"
mysqli_stmt_bind_param($stmt, "ssss", $FirstName, $LastName, $EncryptThis, $key);

How to get select query working sqli

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);
}

INSERT with mysqli

I have a register page which inserts the registration data into a database.
It goes along the lines of this:
if ($_POST['password'] == $_POST['conf_pass']){
$user = $_POST['username'];
$pass = $_POST['password'];
$hash = md5(rand(0,1000));
$accres = mysqli_query($connection, "INSERT INTO accounts (street1, suburb, city, postcode, username) VALUES($address, $suburb, $city, $postcode, $username)");
$account_id = mysqli_insert_id($accres);
$peopleres = mysqli_query($connection, "INSERT INTO people (lastname, firstname, accounts_id, birthdate, phonenumber, username, password, email, hash) VALUES($lastname, $firstname, $account_id, $birthdate, $phonenumber, $username, $password, $email, $hash)");
$peoplerows=mysqli_fetch_assoc($peopleres);
$person_id=$peoplerows[0];
mysqli_query("INSERT INTO PeopleToRole (role_id) VALUES(1)");
$email = $_SESSION['email'];
$p->addContent("User Registered");
}
I originally programmed all of this using postgres (while hosted locally on an apache server) but had to change to mysqli because the host website was already working with mysqli.
So, this code returns the User Registered on the page, therefore the if statement is working. But for some reason the insert statement won't insert anything into the database.
Do i have some sort of formatting error? or something small that i've missed?
Any and all help would be appreciated.
Thanks
You forgot the quotes in the query, for example, you should change:
"INSERT INTO accounts (street1, suburb, city, postcode, username) VALUES($address, $suburb, $city, $postcode, $username)"
to:
"INSERT INTO accounts (street1, suburb, city, postcode, username) VALUES('$address', '$suburb', '$city', '$postcode', '$username')"
That said, working like this makes your code vulnerable to sql injection (as cfreak mentioned in the comments above).
Here's a small example from the manual that shows how you can use bind_param() to make the code more secure:
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);
$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
A common problem: you're not bothering to check your queries for errors, so when something goes wrong you don't know what's happened.
Check the return value of mysqli_query() for FALSE, and if you find it, check mysqli_error($connection) for an error message.
For example:
$accres = mysqli_query($connection, "INSERT INTO accounts (street1, suburb, city, postcode, username) VALUES($address, $suburb, $city, $postcode, $username)");
if ($accres === false) {die(mysqli_error($connection));}
Do something similar for your other queries. When you have an error message, fix it, or come back and ask again.

Database returning false, cant figure out where i went wrong?

I am sorry to bother you with such a newbie question, and thank you for taking the time to go over it and answer it.
function dbaddusr($username, $email, $password){
try{
$conn = new PDO(CONNECTDATA);
$stmt = $conn->prepare("INSERT INTO 'users' ('username', 'email', 'password') VALUES (:username, :email, :password)");
$pass = crypt($password);
$result = $stmt->execute(array("username" => $username, "email" => $email, "password" => $pass));
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
return false;
}
}
Problem is, $result is always false. (I discovered this by some simple var_dump statements inside the try block.
I am very new to this and your help on fixing it is highly appreciated.
Don't quote the column names, if you want, use the backticks `
INSERT INTO users (username, email, password) VALUES (:username, :email, :password)
Change quotes to backticks for table & column name in your query,
$stmt = $conn->prepare("INSERT INTO `users` (`username`, `email`, `password`) VALUES
(:username, :email, :password)");
You are passing $pass in your array and your function accepts $password
Check your error messages to get specific details and you will find the problem.
A non-bloated version with all useless and wrong code cleaned.
function dbaddusr($username, $email, $password){
global $conn;
$sql = "INSERT INTO users (username, email, password) VALUES (?,?,?)";
$stmt = $conn->prepare($sql);
$pass = crypt($password);
$stmt->execute(array($username, $email, $pass));
}
You have to connect ONCE per application, and then use that single connection all the way.

Categories