Do I need to retain mysqli_query() and mysqli_close()? - php

Do I still need to use mysqli_query($connection, $results); and mysqli_close($connection); ?
$sql = $connection->prepare("INSERT INTO pawnshop ".
"(Pawnshop_Name, Street, Barangay, City, DTI_Permit_No, Mayor_Permit_No, Firstname, Middlename, Lastname, Contact_Number, Email_Address, Password) ".
"VALUES ".
"(?,?,?,?,?,?,?,?,?,?,?,?)");
$sql->bind_param("ssssiissssss", $pawnshopName, $street, $barangay, $city, $dtiPermitNo, $mayorPermitNo, $firstName, $lastName, $middleName, $contactNumber, $email, $password);
$sql->execute();
$results = $sql->get_results();
mysqli_query($connection, $results);// Do I still need this?
mysqli_close($connection); //Do I still need this

this much part of the code is enough for you to finish querying database.
$sql = $connection->prepare("INSERT INTO pawnshop ".
"(Pawnshop_Name, Street, Barangay, City, DTI_Permit_No, Mayor_Permit_No, Firstname, Middlename, Lastname, Contact_Number, Email_Address, Password) ".
"VALUES ".
"(?,?,?,?,?,?,?,?,?,?,?,?)");
$sql->bind_param("ssssiissssss", $pawnshopName, $street, $barangay, $city, $dtiPermitNo, $mayorPermitNo, $firstName, $lastName, $middleName, $contactNumber, $email, $password);
$sql->execute();
$results = $sql->get_results();
I see that you are mixing both OOP and Procedural Programming methods together by using mysqli_close($connection), it is not a good practice even though you can do it. Instead use method in $connection object like $connection->close();

i think there is no use of mysqli_query . u need to close prepared statement
by $stmt->close();
and also close the connection.
by $conn->close();

Related

PDO prepare statement for inserting array into db issue

I am creating a user registration system using PDO, and am attempting to insert the users form data into a database table. Very simple, however the wrong value is entered into the database. The values entered into the database are :username, :password, :email_address, :city, etc, rather than the value passed to the function from my form. Any idea as to what I am doing wrong? I tried using bindParam and bindValue but had similar results, and based on other posts I concluded that using an array is the best way to do it. help!
function add_user($username, $password, $email, $fName, $lName, $address, $city, $state, $zip, $phone ) {
global $db;
$sql = "INSERT INTO alumni_user_info
(username, password, email_address, first, last, address, city, state, zip_code, phone)
VALUES
(':username', ':password', ':email_address', ':first', ':last', ':address', ':city', ':state', ':zip_code', ':phone')";
$sth = $db->prepare($sql);
$result = $sth -> execute(array(':username' => $username, ':password' => $password, ':email_address' => $email, ':first' => $fName, ':last' => $lName, ':address' => $address, ':city' => $city, ':state' => $state, ':zip_code' => $zip, ':phone' => $phone));
if ($sth->execute()) {
$success = "Registration successful";
return $success;
} else {
var_dump($result->errorInfo());
$success = "Registration failed";
return $success;
}
Do not use quotes for parameters. It will be escaped because you're binding parameters already.
$sql = "INSERT INTO alumni_user_info
(username, password, email_address, first, last, address, city, state, zip_code, phone)
VALUES
(:username, :password, :email_address, :first, :last, :address, :city, :state, :zip_code, :phone)";
If you do something like this ':username' PDO will treat it as string.

Can't insert data to MySQL using PHP

I have been trying to get my form data to database through PHP code but it is not working and I have looked at the code a thousandth times for a possible error but couldn't find one as a beginner. The form will actually submit but nothing gets to the database.
Any fast help would be deeply appreciated. Here is the code:
$conn = #mysqli_connect('localhost', 'root', 'aboki');
if (mysqli_connect_error()) {
die('Connect Error: ' . mysqli_connect_error());
}
$qry = "INSERT INTO users (email, firstName, surname, userName, password, birthday) values ($email, $firstName, $surname, $userName, $password, $userDOB)";
$result = mysqli_query($conn, $qry);
try this
$qry = "INSERT INTO users (email, firstName, surname, userName, password, birthday)
values ('$email', '$firstName', '$surname', '$userName', '$password', '$userDOB')";
Firstly, you are not quoting the values which is why it is not inserting...
This will fix it (But I strongly recommend you do not use this method!):
$qry = "INSERT INTO users (email, firstName, surname, userName, password, birthday) values ('$email', '$firstName', '$surname', '$userName', '$password', '$userDOB')";
The Correct Method
You would be better off making the most of the predefined functions that mysqli offers and binding these parameters in a prepared statement like so:
mysqli_prepare($conn,"INSERT INTO users (email, firstName, surname, userName, password, birthday) values (?, ?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($conn, 'TYPES_HERE',$email, $firstName, $surname, $userName, $password, $birthday)
I have solution for data Insert , You can try it out.
$conn= mysqli_connect("localhost", "root", "my_password", "world");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "INSERT INTO users
(email, firstName, surname, userName, password, birthday) VALUES
($email, $firstName, $surname, $userName, $password, $userDOB)";
mysqli_query($conn, $query);
printf ("New Record has id %d.\n", mysqli_insert_id($link));
mysqli_close($link);
As you having mysqli in Query the syntax quite different,
Feel free to ask further Question.
Thanks
example:
$stmt = mysqli_prepare($conn, "SELECT District FROM City WHERE Name=?")) {
$stmt->bind_param("s", $city);
$stmt->execute();

PHP connected to db can't use insert function

I've been sitting on the same small problem now for over 10 hours, so it's time to ask stackoverflow! I'm connected to the database but when calling mysqli_stmt_bind_param I get "invalid object or resource".
I've tried the insert statement in the console and it works fine..
<?php
$con=mysqli_connect("127.0.0.1:3306", "myUsername", "password");
mysqli_select_db($con, "webshop");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query= mysqli_stmt_init($con);
mysqli_stmt_prepare($query, "INSERT INTO user (name, email, hash, address, tel) VALUES (?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($query, "ssssi", $name, $email, $hash, $address, $tel);
if(mysqli_stmt_execute($query))
{
mysqli_close($con);
}
?>
Thankful for any help at all!
You have to use the statement object returned by mysqli_stmt_prepare()
$stmt = mysqli_stmt_prepare($con, "INSERT INTO user (name, email, hash, address, tel) VALUES (?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, "ssssi", $name, $email, $hash, $address, $tel);
if(mysqli_stmt_execute($stmt))
Also, the mysqli_stmt_init($con) call is not needed (I think).
mysqli_stmt_init is needed as you are accessing mysqli using the procedural style.
This returns an object of type mysqli_stmt, which then acts as a container for the query you are building. As such, you should pass this as the first parameter to mysqli_stmt_prepare, mysqli_stmt_bind_param and mysqli_stmt_execute.
So your code would look like:
<?php
$con=mysqli_connect("127.0.0.1:3306", "myUsername", "password");
mysqli_select_db($con, "webshop");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$stmt = mysqli_stmt_init($con);
$query = "INSERT INTO user (name, email, hash, address, tel) VALUES (?, ?, ?, ?, ?)";
mysqli_stmt_prepare($stmt, $query);
mysqli_stmt_bind_param($stmt, "ssssi", $name, $email, $hash, $address, $tel);
if(mysqli_stmt_execute($stmt))
{
mysqli_close($stmt);
}
?>
One, unrelated point - you appear to be requiring that your tel field (which I presume to be a telephone number) is an integer. This might be a bad idea if you have to handle telephone numbers starting with 0 (common in the UK for example) at any point.

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.

PHP:PDO: Why wont my data insert?

I dont no what the problem is with my code. It doesn't insert the data into the database. Here it is.
$adduser = $con->prepare("INSERT INTO 'basicuserinfo'(email, password, firstname, lastname) VALUES(:email, :password, :firstname, :lastname)");
$adduser->bindValue(':email', $email);
$adduser->bindValue(':password', $password);
$adduser->bindValue(':firstname', $firstname);
$adduser->bindValue(':lastname', $lastname);
$adduser->execute();
INSERT INTO 'basicuserinfo'(email, password, firstname, lastname) VALUES(:email, :password, :firstname, :lastname)
That isn't a valid SQL statement. Get rid of the 's.
Are you sure it is succeeding? You aren't checking the execute as in:
if(!$adduser->execute()) echo "Execute failed";
You will likely find that it is throwing an error on the ' around the table name.
Try this..
$adduser = $con->prepare("INSERT INTO `basicuserinfo`(email, password, firstname, lastname)
VALUES(?, ? , ? , ? )");
$adduser->bindParam('ssss', $email,$password , $firstname,$lastname);
$adduser->execute();
In this way of prepare statement you can reduce your executing time..
then dont put apostapy before the tablename

Categories