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;
Related
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 am using a Microsoft Access Database and am connected to it by ODBC in my PHP code. I have looked online and the PHP manual says that odbc_exec prepares and executes the statement.
My code has parameters to avoid an sql injection but I cannot use odbc_prepare and odbc_execute as they are not supported by MS Access. I am having trouble finding out how to bind my variables to the parameters in my sql statement.
PHP
<?php
$con=odbc_connect("InventoryDB", "", "");
if (isset($_POST['partNumber'])) {
$partNum = $_POST['partNumber'];
}
if (isset($_POST['manufacturer'])) {
$manufacturer = $_POST['manufacturer'];
}
if (isset($_POST['supplier'])) {
$supplier = $_POST['supplier'];
}
if (isset($_POST['catalogNumber'])) {
$catalogNumber = $_POST['catalogNumber'];
}
if (isset($_POST['deviceFamily'])) {
$deviceFamily = $_POST['deviceFamily'];
}
if (isset($_POST['listPrice'])) {
$listPrice = $_POST['listPrice'];
}
if (isset($_POST['quantity'])) {
$quantity = $_POST['quantity'];
}
if (isset($_POST['packets'])) {
$packets = $_POST['packets'];
}
$stmt = odbc_prepare($con, 'INSERT INTO Parts (PartNumber, Manufacturer, Supplier, CatalogNumber, DeviceFamily, ListPrice, Quantity, Packets) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'); // Insert all of the values from the form into the table
$rs = odbc_execute($stmt, array($partNum, $manufacturer, $supplier, $catalogNumber, $deviceFamily, $listPrice, $quantity, $packets));
?>
I would like to know how to do what I am currently doing with prepare and execute using just odbc_exec.
The values all come from a form to add to the database which shows the inventory of a company.
EDIT
The error that using prepare and execute returns is odbc_prepare():
SQL error: [Microsoft][ODBC Driver Manager] Driver does not support this
function, SQL state IM001 in SQLDescribeParameter
Consider PHP's generalized DB-API, PDO, that among other RBDMS's can connect to MS Access via ODBC for parameterized queries. You may need to enable php_pdo_odbc in .ini file:
$database = "C:\\path\\to\\mydatabase.accdb";
// WITH DSN
$dbh = new PDO("odbc:DSN=MS Access Database;DBq=$database;");
// WITH DRIVER
// $dbh = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBq=$database;");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO Parts (PartNumber, Manufacturer, Supplier, CatalogNumber,
DeviceFamily, ListPrice, Quantity, Packets)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
try {
$sth = $dbh->prepare($sql);
$sth->execute(array($partNum, $manufacturer, $supplier, $catalogNumber,
$deviceFamily, $listPrice, $quantity, $packets));
}
catch(PDOException $e) {
echo $e->getMessage()."\n";
}
// CLOSE CONNECTION
$dbh = null;
If you can't use odbc_prepare you have to generate your SQL statement as a string and do the best you can to defend against SQL injection. By far the biggest problem is the ' character. I use these two functions:
function Qs($Text) { return(str_replace("'","''",$Text)); }
function Qsz($Text) { return(empty($Text)?'NULL':("'".Qs($Text)."'")); }
The first just avoids issues with '. I use the second if I want to insert NULL instead of an empty string (usually the case).
Use double quotes on generating your SQL statement, so they don't conflict with the single quotes inside the statement. Example (assuming both fields are text):
$sql = "INSERT INTO Parts (PartNumber, Manufacturer) VALUES (".Qsz($_POST['partNumber']).",".Qsz($_POST['partNumber']).")";
Help! please, I'm trying to add Mysql injection to my code:
if($stmt = mysqli_prepare($dbconn,$sqlinsert="INSERT INTO `T`(`ID`,`FName`, `LName`, `Gender`, `Agreement`,`Photo`,`Photo_name`) VALUES ('$id','$fname','$lname','$Gender','$radios','$image','$image_name')"))
{
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "i", $id);
}
I'm getting this warning
Warning: mysqli_stmt_bind_param(): Number of variables doesn't match number of parameters in prepared statement in C:\wamp\www\Ex\insert-data.php on line 30
Call Stack
# Time Memory Function Location
1 0.0005 142320 {main}( ) ..\insert-data.php:0
2 0.1655 294232 mysqli_stmt_bind_param ( ) ..\insert-data.php:30
line 30 is :
mysqli_stmt_bind_param($stmt, "i", $id);
Is there any way to fix that?
I tried this type $mysqli->prepare, but it didn't work.
Any idea?, Thanks for any help.
Assuming you are willing to use PDO instead of mysqli.
Your database connection should look like this:
DB.php
<?php
$host = 'localhost';
$dbname = 'Example';
$username = "root";
$password = "";
$conn = new PDO('mysql:host=localhost;dbname=Example', $username,
$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
Prepared Statements:
file.php
<?php
//Example prepared statement with INSERT
$reply = $conn->prepare("INSERT INTO reply (user_name,
receipient, comment, comment_id, user_image) VALUES
(:username,:receipient,:commentt,:commentid,:userimage)");
$reply->bindParam(":username", $user3_name, PDO::PARAM_STR);
$reply->bindParam(":receipient", $user2_name, PDO::PARAM_STR);
$reply->bindParam(":commentt", $comment2, PDO::PARAM_STR);
$reply->bindParam(":commentid", $c_id, PDO::PARAM_INT);
$reply->bindParam(":userimage", $u_image, PDO::PARAM_STR);
$reply->execute();
?>
FOR MYSQLI
db.php
<?php
$db = new mysqli("localhost","root","","dbname");
?>
file.php
<?php
$stmt = $db->prepare("INSERT INTO reply (user_name,
receipient, comment, user_image) VALUES
(?,?,?,?)");
$stmt->bind_param('ssss', $username, $receipient,$commentt,$userimage);
$stmt->execute();
?>
<?php
$fname = $_POST['first'];//should be the name attribute used in your form
$lname = $_POST['last'];
$gender = $_POST['gen'];
$agreement = $_POST['agree'];
$photo = $_POST['pic'];
$p_name = $_POST['pic_name'];
$stmt = $dbconn->prepare("INSERT INTO T(FName, LName, Gender,
Agreement,Photo,Photo_name) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param('ssssss',$fname,$lname,$gender,$agreement,$photo,$p_name);
$stmt->execute();
?>
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);
}
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.