How can I place the SELECTED elements from database into a variable - php

How can I place these elements into a variable?
$user_information = $connect->prepare("SELECT email, gender, firstname, middlename, FROM members");
like
$firstname = 'firstname';
$gender = 'gender';
$email = 'email';
how can I do this
Thanks in advance

If you are using PDO
$user_information ->execute();
$result = $user_information->fetch(PDO::FETCH_ASSOC);
$firstname = $result['firstname'];
$gender = $result['gender'];
$email = $result['email'];
if you are using mysqli
$user_information->execute();
$user_information->bind_result($firstname, $gender, $email);
$user_information->fetch();
printf("%s, %s, %s\n", $firstname, $gender, $email);
$user_information ->close();

If you are using PHP and PDO, you can use the in the fetch method to get an object using PDO::FETCH_OBJ. http://de3.php.net/manual/en/pdostatement.fetch.php
$result = $sth->fetch(PDO::FETCH_OBJ);
print $result->NAME;

list($email, $gender, $firstname, $middlename) = $user_information;
For more info check LIST function # PHP docs.

if it returns an object you can get it like;
$firstname = $user_information->firstname;
$gender = $user_information->gender;
$email = $user_information->email;
or if it returns an array;
$firstname = $user_information["firstname"];
$gender = $user_information["gender"];
$email = $user_information["email"];

Related

how to forbid to send data to sql

I'm using strlen to check my inputs values. I want to forbid to the users to send data to my database if the strlen is too long. I didn't find any way to forbid it, so anyone can send as long values as he wants right now. Here's my code:
if (isset($_POST['sub'])) {
$name = $_POST['name'];
$phone = $_POST['phone'];
$phone2 = $_POST['phone2'];
$email = $_POST['email'];
$zipcode = $_POST['zipcode'];
$address = $_POST['address'];
$job = $_POST['job'];
$description = $_POST['description'];
$userid = $_SESSION['id'];
$stmt = $mysqli -> prepare('UPDATE cards SET name=?, phone=?, phone2=?, email=?, zipcode=?, address=?, job=?, description=?, visibility=?, confirmed=? WHERE id = ?');
if (
$stmt &&
$stmt->bind_param('ssssisssiii', $name, $phone, $phone2, $email, $zipcode, $address, $job, $description, $visibility, $confirmed, $id) &&
$stmt -> execute()
) {
echo "Sikeres módosítás!";
} else {
echo $mysqli -> error;
}
}
$getstmt = $mysqli->prepare("SELECT * FROM cards WHERE id= ?");
if ($getstmt and
$getstmt->bind_param('i', $id) and
$getstmt->execute() and
$result = $getstmt->get_result() and
$row = $result->fetch_assoc()
) {
if($row['userid'] == $_SESSION['id']){
$name = $row['name'];
$phone = $row['phone'];
$phone2 = $row['phone2'];
$email = $row['email'];
$zipcode = $row['zipcode'];
$address = $row['address'];
$job = $row['job'];
$description = $row['description'];
}else{
header("Location: index.php");
}
I check the length of inputs here:
if(strlen($name) > 30)
{
echo "test";
exit();
}
if(strlen($job) > 50)
{
echo "test";
exit();
}
if(strlen($email) > 50)
{
echo "test";
exit();
}
//more of these strlen checks
//and html code under that
How can I modify the echo parts to forbid to send the datas?
Well, if you really have to do it your way, you can throw an exception.
However, more common way is to bind your data to model, validate the model checking any business constraints (using the validator) and then acting accordingly. There is plenty of web frameworks providing such an abstraction in any programming language, for PHP see Laravel for inspiration.

Query failed: SQLSTATE[42000]: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]The multi-part identifier "msd#gmail.com" could not be bound

Whenever I tried to update my table am getting this error.
My SQL file where I have update function has this code:
function updateUser($userid, $firstname, $lastname, $phone, $email, $address, $zip, $city, $state, $password)
{
$firstname = str_replace('\'', '\'\'', trim($firstname));
$lastname = str_replace('\'', '\'\'', trim($lastname));
$phone = str_replace('\'', '\'\'',trim($phone));
$email = str_replace('\'', '\'\'',trim($email));
$address = str_replace('\'', '\'\'',trim($address));
$zip = str_replace('\'', '\'\'',trim($zip));
$city = str_replace('\'', '\'\'',trim($city));
$state = str_replace('\'', '\'\'',trim($state));
$password = str_replace('\'', '\'\'',trim($password));
$query = <<<STR
Update tbl_users
Set firstname = '$firstname', lastname = '$lastname', phone = $phone, email = $email,
address = '$address', zip = '$zip', city = '$city', state = '$state', password = '$password'
Where userid = $userid
STR;
executeQuery($query);
}
My profile page where am trying to update has the following code:
if (isset($_SESSION['user_id']))
{
// get the details for the movie to be edited
$userdetails = getUserDetailsByID($_SESSION['user_id']);
$_SESSION['userdetails'] = $userdetails;
}
$lastname = $_SESSION['userdetails'][0]['lastname'];
$firstname = $_SESSION['userdetails'][0]['firstname'];
$phone = $_SESSION['userdetails'][0]['phone'];
$email = $_SESSION['userdetails'][0]['email'];
$address = $_SESSION['userdetails'][0]['address'];
$zip = $_SESSION['userdetails'][0]['zip'];
$city = $_SESSION['userdetails'][0]['city'];
$state = $_SESSION['userdetails'][0]['state'];
$password = $_SESSION['userdetails'][0]['password'];
if (isset($_POST['register']) && count($userdetails)){
updateUser((int)$_POST['userid'], $_POST['firstname'], $_POST['lastname'], $_POST['phone'],
$_POST['email'], $_POST['address'], $_POST['zip'],$_POST['city'], $_POST['state'], $_POST['password']);
header("Location: profile.php");
echo '<h2>Thank you for Registering. You will now be redirected to the login page.<h2>';
die();
}
?>

PHP - getting last statements PK ID to use in second function Insert statement [duplicate]

This question already has answers here:
Getting the return value from a function
(2 answers)
Closed 6 years ago.
Duplicate Edit: This question is different because I'm trying to return a specific value, the primary key ID to be used in another functions INSERT statement as a foreign key, within the same action. The "duplicate" question does not answer this, rather it only shows how to get a return value from a function. Not how to get it and insert it correctly in another functions prepare statement. Which I wasn't sure I was doing correctly.
I have two tables, orders and customers that are to have data inserted from one form within the same action. The orders table has a primary key = orderID which also needs to be added into the customers table.
DB Relationship Diagram
I can upload the data to the orders table without a problem, but the second query function to the customers table does nothing. I'm pretty sure it's due to the foreign key constraint I've set. I've done some research and realize I need to get the foreign key id, possibly using $mysqli->insert_id or PDO::lastInsertId, but I'm lost as to how to use it with my current functions.
index.php
$product = $_POST['product'];
$fName = $_POST['fName'];
$lName = $_POST['lName'];
$address = $_POST['address'];
$address2 = $_POST['address2'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$country = $_POST['country'];
$phoneNumber = $_POST['phoneNumber'];
$email = $_POST['email'];
/* Functions */
order_Data ($db, $product, $fName, $lName, $email);
// Need to have orderID from ^ table used in order_custData sql statement
order_custData($db, $orderID, $fName, $lName, $address, $address2, $city, $state, $zip, $country, $phoneNumber, $email);
functions.php
<?php
/** Order Data Function
*/
function order_Data($db, $product, $fName, $lName, $email) {
try {
$sql = "INSERT INTO orders SET product = :product, fName = :fName, lName = :lName, email = :email";
$ps = $db->prepare($sql);
$ps->bindValue(':product', $product);
$ps->bindValue(':fName', $fName);
$ps->bindValue(':lName', $lName);
$ps->bindValue(':email', $email);
$ps->execute();
return $orderID = $db->lastInsertId();
} catch (PDOException $e) {
die("Sorry, There was a problem order table.");
}
}
/** Customer Purchase Information Function
* #param $orderID -- I need to insert the orderID from orders table?
*/
function order_custData($db, $orderID, $fName, $lName, $address, $address2, $city, $state, $zip, $country, $phoneNumber, $email) {
try {
$sql = "INSERT INTO customers SET orderID = :orderID, fName = :fName, lName = :lName, address = :address, address2 = :address2,city = :city, state = :state, zip = :zip, country = :country, phoneNumber = :phoneNumber, email = :email";
$ps = $db->prepare($sql);
$ps->bindValue(':orderID', $orderID); // Foreign key from orders table
$ps->bindValue(':fName', $fName);
$ps->bindValue(':lName', $lName);
$ps->bindValue(':address', $address);
$ps->bindValue(':address2', $address2);
$ps->bindValue(':city', $city);
$ps->bindValue(':state', $state);
$ps->bindValue(':zip', $zip);
$ps->bindValue(':country', $country);
$ps->bindValue(':phoneNumber', $phoneNumber);
$ps->bindValue(':email', $email);
return $ps->execute();
} catch (PDOException $e) {
die("Sorry, There was a problem with the customer table!");
}
}
?>
Now the $orderID and :orderID IN THE order_custData function are just there for me as a visual representation to figure out the problem. I wasn't try to execute the sql statement with it originally. However, anything I've tried seems to throw errors underfined variable or fatal calls to the prepare function of the first function.
Thank you for your time.
The utility function order_Data() already returns the ID:
…
return $orderID = $db->lastInsertId();
(Rewrite to return $db->lastInsertId();, though.)
Simply carry the return value by assigning to a variable:
$orderID = order_Data ($db, $product, $fName, $lName, $email);
order_custData($db, $orderID, $fN …);
Try this. Simply carry the return value by assigning to a variable
<?php
require_once ("models/dbConn.php");
require_once ("models/functions.php");
$action = $_REQUEST['action'];
if ($action == NULL || empty($action)):
$action = '';
endif;
include_once ("views/header.php");
switch ($action) :
case '':
include ("views/main.php");
break;
case 'checkoutCart':
// Once form button is clicked action = completePurchase
include ("views/checkout.php");
break;
case 'completePurchase':
$product = $_POST['product'];
$fName = $_POST['fName'];
$lName = $_POST['lName'];
$address = $_POST['address'];
$address2 = $_POST['address2'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$country = $_POST['country'];
$phoneNumber = $_POST['phoneNumber'];
$email = $_POST['email'];
/* Functions */
$orderID = order_Data ($db, $product, $fName, $lName, $email);
// Need to have orderID from ^ table used in order_custData sql statement
order_custData($db, $orderID, $fName, $lName, $address, $address2, $city, $state, $zip, $country, $phoneNumber, $email);
include ("views/complete.php");
break;
endswitch;
include_once ("views/footer.php");
?>
Your order_Data() function is returning the Order Id, but you are not assigning the the return value in index.php to $objectID.
I.e. Change this...
order_Data ($db, $product, $fName, $lName, $email);
... to this ...
$orderID = order_Data ($db, $product, $fName, $lName, $email);
I recommending checking your error reporting level for PHP on your development environment to include notices, as PHP will have triggered a notice for use of an undefined variable.

Is this code vulnerable to sql injection?

Is this code prone to SQL Injection? Can you suggest something to improve the security? Is it right to use mysqli_real_escape_string? And do you think it's alright to use this for project?
<?php
require 'db.php';
if(isset($_POST['pawnshopName'])&&isset($_POST['street'])&&isset($_POST['barangay'])&&isset($_POST['city'])&&isset($_POST['dtiPermitNo'])&&isset($_POST['mayorPermitNo'])&&isset($_POST['firstName'])&&isset($_POST['lastName'])&&isset($_POST['middleName'])&&isset($_POST['contactNumber'])&&isset($_POST['email'])&&isset($_POST['password'])&&isset($_POST['confirmPassword']))
{
$options = ['cost' => 11, 'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),];
$pawnshopName = mysqli_real_escape_string($connection, $_POST['pawnshopName']);
$street = mysqli_real_escape_string($connection, $_POST['street']);
$barangay = mysqli_real_escape_string($connection, $_POST['barangay']);
$city = mysqli_real_escape_string($connection, $_POST['city']);
$dtiPermitNo = mysqli_real_escape_string($connection, $_POST['dtiPermitNo']);
$mayorPermitNo = mysqli_real_escape_string($connection, $_POST['mayorPermitNo']);
$firstName = mysqli_real_escape_string($connection, $_POST['firstName']);
$lastName = mysqli_real_escape_string($connection, $_POST['lastName']);
$middleName = mysqli_real_escape_string($connection, $_POST['middleName']);
$contactNumber = mysqli_real_escape_string($connection, $_POST['contactNumber']);
$email = mysqli_real_escape_string($connection, $_POST['email']);
$password = mysqli_real_escape_string($connection, password_hash($_POST['password'], PASSWORD_BCRYPT, $options));
$confirmPassword = mysqli_real_escape_string($connection, $_POST['confirmPassword']);
if(password_verify($confirmPassword,$password))
{
echo 'Password Match';
}else
{
echo 'Password mismatch';
}
$sql = "INSERT INTO pawnshop ".
"(Pawnshop_ID, Pawnshop_Name, Street, Barangay, City, DTI_Permit_No, Mayor_Permit_No, Firstname, Middlename, Lastname, Contact_Number, Email_Address, Password) ".
"VALUES ".
"('','".$pawnshopName."', '".$street."', '".$barangay."', '".$city."', '".$dtiPermitNo."', '".$mayorPermitNo."', '".$firstName."', '".$lastName."', '".$middleName."', '".$contactNumber."', '".$email."', '".$password."' )";
mysqli_query($connection, $sql);
mysqli_close($connection);
}
?>
No, you must use prepare method. Then on every place where you want to add a value place a ?. Than you must use the bind_param method. Finally, you can execute it and get the results whit get_results. An example:
$stmt = $connection->prepare("INSERT INTO Customers (CustomerName, Address, CityID) VALUES (?, ?, ?)");
$stmt->bindParam('ssi', $name, $address, $cityId);
$stmt->execute();
$results = $stmt->get_results();
The 'ssi' are corresponding variable the types of the attributes.
i are integers
d are doubles
s are strings
b is a blob and will be sent in packets
My resources are: w3schools and php.net

"No data supplied for parameters in prepared statement"

So I am reworking a script to include prepared statements. It was working fine before, but now I am getting "No data supplied for parameters in prepared statement" when the script runs. What is the issue here?
<?php
require_once("models/config.php");
$firstname = htmlspecialchars(trim($_POST['firstname']));
$firstname = mysqli_real_escape_string($mysqli, $firstname);
$surname = htmlspecialchars(trim($_POST['surname']));
$surname = mysqli_real_escape_string($mysqli, $surname);
$address = htmlspecialchars(trim($_POST['address']));
$address = mysqli_real_escape_string($mysqli, $address);
$gender = htmlspecialchars(trim($_POST['gender']));
$gender = mysqli_real_escape_string($mysqli, $gender);
$city = htmlspecialchars(trim($_POST['city']));
$city = mysqli_real_escape_string($mysqli, $city);
$province = htmlspecialchars(trim($_POST['province']));
$province = mysqli_real_escape_string($mysqli, $province);
$phone = htmlspecialchars(trim($_POST['phone']));
$phone = mysqli_real_escape_string($mysqli, $phone);
$secondphone = htmlspecialchars(trim($_POST['secondphone']));
$secondphone = mysqli_real_escape_string($mysqli, $secondphone);
$postalcode = htmlspecialchars(trim($_POST['postalcode']));
$postalcode = mysqli_real_escape_string($mysqli, $postalcode);
$email = htmlspecialchars(trim($_POST['email']));
$email = mysqli_real_escape_string($mysqli, $email);
$organization = htmlspecialchars(trim($_POST['organization']));
$organization = mysqli_real_escape_string($mysqli, $organization);
$inriding = htmlspecialchars(trim($_POST['inriding']));
$inriding = mysqli_real_escape_string($mysqli, $inriding);
$ethnicity = htmlspecialchars(trim($_POST['ethnicity']));
$ethnicity = mysqli_real_escape_string($mysqli, $ethnicity);
$senior = htmlspecialchars(trim($_POST['senior']));
$senior = mysqli_real_escape_string($mysqli, $senior);
$student = htmlspecialchars(trim($_POST['student']));
$student = mysqli_real_escape_string($mysqli, $student);
$order= "INSERT INTO persons (firstname, surname, address, gender, city, province, postalcode, phone, secondphone, email, organization, inriding, ethnicity, senior, student_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = mysqli_prepare($mysqli, $order);
mysqli_stmt_bind_param($stmt, "sssd", $firstname, $surname, $address, $gender, $city, $province, $postalcode, $phone, $secondphone, $email, $organization, $inriding, $ethnicity, $senior, $student);
mysqli_stmt_execute($stmt);
echo $stmt->error;
$result = mysqli_query($mysqli,$stmt);
if ($result === false) {
echo "Error entering data! <BR>";
echo mysqli_error($mysqli);
} else {
echo "User $firstname added <BR>";
}
?>
Thanks in advance.
You have only bound four arguments, by the control string "sssd", but you have many parameters. When binding variables with mysqli, you need one character for each parameter, for example:
mysqli_stmt_bind_param($stmt, "sssdsssssssssdd", $firstname, $surname, $address,
$gender, $city, $province, $postalcode, $phone, $secondphone, $email,
$organization, $inriding, $ethnicity, $senior, $student);
(I'm assuming senior and student are integers, and need the "d" code.)
You don't need to treat any of your variables with mysqli_real_escape_string() -- that's the point of using parameters. If you do escaping as well, you'll get literal backslash characters in your data in the database.
And you never need to use htmlspecialchars() in any case - you would use that when outputting to HTML, not when inserting to the database. You're going to get literal sequences like & in your data in the database.
Re your next error:
"Catchable fatal error: Object of class mysqli_stmt could not be converted to string in..."
This is caused by the following:
$result = mysqli_query($mysqli,$stmt);
That function expects the second argument to be a string, a new SQL query. But you've already prepared that query, so you need the following:
$result = mysqli_stmt_execute($stmt);

Categories