dropdown populated with prepared statement - php

Hello and thank you for your time in advance.
I am looking to populate a dropdown menu from a mysql database using a prepared statement in PHP. I am just looking for any entries that have a matching "client_id". I have seen this addressed many ways (some of them out dated, some of them crazy complicated) but have not been able to find an example that is using php in a way similar enough to what I have been using (see below) so that I can cobble together something that works.
Here is the code I would like to work with.
<?php
include ('connect.php');
if ($_POST) {
if (!empty($_POST['client_id'])) {
$client_id = htmlspecialchars($_POST['client_id']);
$stmt = $link->prepare("SELECT project_id, nickname FROM project WHERE client_id=?");
$stmt->bind_param('s', $client_id);
$stmt->execute();
$row = $stmt->fetch();
while ($stmt->fetch()) {
echo ("<option value='$row['project_id']'>$row['nickname']</option>");
}
$stmt->close();
}
}
include ('disconnect.php');
?>
I know that the echo part is not correct, but I wanted to be able to show what I was thinking at the very least. In general I am not 100% I am using the row variable correctly either. I appreciate any assistance here.
EDIT:
the above file is called "fetchProjects.php"
Here is the code where this PHP file included.
<div class="twelve columns">
<p>select an existing project below</p>
<select size="10" name="selectedProject">
<?php include('fetchProjects.php')?>
</select>
</div>

You can use bind_result, on each iteration of the while loop $project_id and $nickname get updated with the current database row values
$stmt = $link->prepare("SELECT project_id, nickname FROM project WHERE client_id=?");
$stmt->bind_param('s', $client_id);
$stmt->bind_result($project_id, $nickname);
$stmt->execute();
$stmt->store_result();
while ($stmt->fetch()) {
echo '<option value="'.$project_id.'">'.$nickname.'</option>';
}
$stmt->close();
Not tested but it should work

You forgot to assign your fetch here:
while ($stmt->fetch()) {...
It should be:
while ($row = $stmt->fetch()) {...
Now the array elements you try to access with $row will work. You should delete your first fetch, because that will consume the first row of data. One more thing: you do not need parentheses areound your echo.

Please review:
http://php.net/manual/en/mysqli-result.fetch-assoc.php
http://php.net/manual/en/mysqli-stmt.fetch.php
Would advise:
<?php
include ('connect.php');
if (isset($_POST['client_id'])) {
if (!empty($_POST['client_id'])) {
$client_id = htmlspecialchars($_POST['client_id']);
$stmt = $link->prepare("SELECT project_id, nickname FROM project WHERE client_id=?");
$stmt->bind_param('s', $client_id);
$stmt->execute();
$stmt->bind_result($pid, $nick);
while ($stmt->fetch()) {
echo ("<option value='$pid'>$nick</option>");
}
$stmt->close();
}
}
include ('disconnect.php');
?>

Related

Else does not work in selection of $row

I want to check if user has set his gender. If not, it will display the 1st echo. If yes, it'll display the echo of his gender.
Problem is that the page shows only the 1st echo even though there IS set gender in database... I really don't know why it is not working...
My code:
<?php
$username = $_SESSION['username'];
$sql = "
SELECT gender FROM members WHERE username = ?";
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($username);
while ($stmt->fetch()){
if($row['gender'] == ""){
echo "You have not selected your gender yet."; // This is the 1st echo and this is the only one that is displayed
} else {
echo "You selected that you are {$row['gender']}."; // This is not displayed no matter what...
}
}
?>
What I have wrong?
I'm not a php expert, but I think this code would work better for you as I don't think that $row contains anything (I don't see where it's being set anywhere, and according to the docs, bind_result doesn't work that way anyway):
$username = $_SESSION['username'];
$stmt = $mysqli->prepare("SELECT gender FROM members WHERE username = ?");
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($gender);
while ($stmt->fetch()){
if(empty($gender)){
echo "You have not selected your gender yet.";
} else {
echo "You selected that you are " . $gender;
}
}
EDIT
Used empty() instead of = "" in case nulls are returned for $gender.
EDIT 2
I noticed that you don't ever use $sql. I updated the code for the proper syntax, assuming that your database connection is called $mysqli.
Might want to check the docs here: https://php.net/manual/en/mysqli-stmt.bind-result.php

Get the rows and display them in echo mysqli prepared

im trying to get the rows from database with mysqli prepare statments and display them in echo like <?php echo $username; ?> but don't know how to get them , wasted 4 hours no success , help would be greate
php
<?php
include("secure/functions.php");
session_start();
$stmt = $mysqli->prepare("SELECT * FROM members WHERE username = ?");
$stmt->bind_param('s', $_SESSION['username']); // Bind "$username" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
if($stmt->num_rows == 1) {
$stmt->bind_result($id,$username); // get variables from result.
$stmt->fetch();
}
?>
You initially used $session_start(); where it should be session_start(); no dollar sign.
Try to check existence of session_start(); at begin of your script.
And, you can check which value sets to prepared statement - before binding of parameter $_SESSION['username'], try to display this value with echo or print.

Debug mySQLi prepared statement -> email not found

i try to implement a register form and try to check via php and jQuery if a user already registered with a certain email.
here is my piece of code:
if(endsWith($email, 'domain.tld'))
{
$result = $database->prepare("SELECT id FROM users WHERE email LIKE ?");
$result->bind_param('s', $email);
//echo $email;
$result->execute();
//echo $result->execute();
//echo $result->num_rows;
//exit();
if($result->num_rows == 0)
{
echo'ok';
}
else {
echo 'duplicate';
}
$result->close();
}
else {
echo 'validation failed';
}
I used the commented echos and exit() to debug my code. The problem is that the database holds the user user#domain.tld and the script shows me in the echo "user#domain.tld10". So the statement ist executed successful but no rows are returned. If i execute the statement
SELECT id FROM users WHERE email LIKE "user#domain.tld"
i get the id (in this case 11) returned.
My question is, how can i debug this php script better and the biggest question is, why is my scipt not working properly?
Thank you so much in advance!
Use before num_rows
$result->store_result();
The use of mysqli_stmt_num_rows() depends on whether or not you used
mysqli_stmt_store_result() to buffer the entire result set in the
statement handle.
Docs

Having problems going from mysqli_query to mysqli_prepare

I'm new to PHP and made a simple php site that allows me to submit a form and delete data stored in a database. I was told it was better to use prepared statements to avoid SQL Injection.
I updated my delete and it still works, not sure if it's totally right:
<?php
include("dbconnect.php");
$getid = $_GET["id"];
$delete = mysqli_prepare($database,"DELETE FROM contacts WHERE id IN ($getid)");
mysqli_stmt_execute($delete);
header("Location:http://localhost/address-book");
exit;
?>
But I can't seem to get the add to database feature to work. I tried a variety of different ways to write it, but I'm sure that I'm missing something simple. Here's the unsafe code that I originally wrote:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
include("inc/dbconnect.php");
// assigns form data to table columns
$assign = "INSERT INTO contacts(firstName,lastName,email,phone,birthday) VALUES ('$_POST[firstName]','$_POST[lastName]','$_POST[email]','$_POST[phone]','$_POST[birthday]')";
//execute query
if (mysqli_query($database,$assign)) {
header("Location:http://localhost/address-book/");
exit;
} else {
exit;
}
?>
If someone could guide me in the right direction I'd be thankful. I'm new to all of this.
UPDATED: I've updated my original code and came up with this instead for delete:
<?php
include("dbconnect.php");
$getid = $_GET["id"];
$delete = mysqli_prepare($database,"DELETE FROM contacts WHERE id IN (?)");
mysqli_stmt_bind_param($delete, 's', $getid);
mysqli_stmt_execute($delete);
header("Location:http://localhost/address-book");
exit;
?>
and the add feature:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
include("inc/dbconnect.php");
$firstName = "$_POST[firstName]";
$lastName = "$_POST[lastName]";
$email = "$_POST[email]";
$phone = "$_POST[phone]";
// assigns form data to table columns
$assign = mysqli_prepare($database,"INSERT INTO contacts(firstName,lastName,email,phone) VALUES (?,?,?,?)");
mysqli_stmt_bind_param($assign, 'ssss', $firstName, $lastName, $email, $phone);
mysqli_stmt_execute($assign);
exit;
}
?>
A simple Prepare statement is something along the lines of
$query = $this->db->prepare("Query here WHERE something = ?") - note this example is taken from my site so you'll likely have something else instead of $this->->prepare.
The key thing is that the "= something " is denoted as a question mark.
You then bind the value of that question mark to the query
$query->bindValue(1, passed in parameter)
As a fully working example:
//function to add 1 to downloads each time a file is downloaded
public function addToDownload($filename){
$query = $this->db->prepare('UPDATE trainingMaterial SET downloads = downloads + 1 WHERE filename = ?');
$query->bindValue(1, $filename);
try{
$query->execute();
}catch(PDOException $e){
die($e->getMessage());
}
}
Your query `$assign = "INSERT INTO contacts(firstName,lastName,email,phone,birthday) VALUES ('$_POST[firstName]','$_POST[lastName]','$_POST[email]','$_POST[phone]','$_POST[birthday]')";
would be
$assign = "INSERT INTO contacts(firstName,lastName,email,phone,birthday) VALUES ?,?,?,?,?)";
$assign->bindValue(1, '$_POST[firstName]')
$assign->bindValue(2, '$_POST[lastName]')
etc etc

PHP Checking if something exists in database

I'm making an iOS app that sends a username string to this PHP file and then the PHP file checks to see if their username exists in a database, in a table called "members". I got this code online and modified it a little to fit my needs. This is the code:
// Main method to redeem a code
function redeem() {
// Check for required parameters
if (isset($_POST["username"])) {
// Put parameters into local variables
$code = $_POST["username"];
echo $code;
// Look up code in database
$user_id = 0;
echo "userid";
$stmt = $this->db->prepare('SELECT username FROM members WHERE username=', $code);
echo "dbprepare";
$stmt->bind_param("is", $code);
echo "bindparam";
$stmt->execute();
echo "execute";
$stmt->bind_result($id, $code);
echo "bindresult";
while ($stmt->fetch()) {
break;
}
$stmt->close();
The code is tripping up on bind_param, it only gets to echo "dbprepare". Am I doing something incorrectly? How do I check for the username?
try this code
$stmt = $this->db->prepare('SELECT username FROM members WHERE username=?');
echo "dbprepare";
$stmt->bind_param("s", $code);
I would guess you do miss an actual placeholder here:
$stmt = $this->db->prepare('SELECT username FROM members WHERE username=?', $code);
See the added ?. The prepare call does not just append the value.
You do need to tell it where it belongs. (If your class implements prepare/bind as in mysqli or PDO, and as commonly understood.)
You forgot to add a ? in your SQL.
$stmt = $this->db->prepare('SELECT username FROM members WHERE username=?', $code);
echo "dbprepare";
$stmt->bind_param("is", $code);

Categories