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.
Related
Hi I am working on simple crud project with php and mysqli statement.
First everything was working good, but for instance mysqli_num_rows($result) returns more than one row which cause all errors.
this is my PHP code
<?php
if(isset($_GET["email"]) && !empty(trim($_GET["email"]))){
// Include config file
require_once 'db.php';
// Prepare a select statement
$sql = "SELECT * FROM interns WHERE email = ?";
if($stmt = mysqli_prepare($con, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "i", $param_id);
// Set parameters
$param_id = trim($_GET["email"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
$result = mysqli_stmt_get_result($stmt);
if(mysqli_num_rows($result) == 1){
/* Fetch result row as an associative array. Since the result set
contains only one row, we don't need to use while loop */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
// Retrieve individual field value
$firstname = $row["firstname"];
$lastname = $row["lastname"];
$cin = $row["cin"];
$phone_number = $row["phone_number"];
$address = $row["address"];
$school = $row["school"];
$intern_duration = $row["intern_duration"];
$departement = $row["departement"];
$cv = $row["cv"];
$internship_report = $row["internship_report"];
} else{
// URL doesn't contain valid id parameter. Redirect to error page
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
} else{
// URL doesn't contain id parameter. Redirect to error page
header("location: error.php");
exit();
}
?>
I know it's might be a very simple error but it driving me crazy xD
mysqli_stmt_bind_param($stmt, "i", $param_id) that should be an s for a string, being for the email address. The i stands for "integer".
Your query probably returns more than one row because there are (probably) more than one row containing an integer.
You could also add a LIMIT 1 to the query which may help.
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');
?>
I want to delete some rows from my table. But when I click delete, this just show me a blank page. I'm sure about id value and my db connection.
This is my code:
// connect to the database
include('connect-db.php');
// confirm that the 'id' variable has been set
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
// get the 'id' variable from the URL
$id = $_GET['id'];
// delete record from database
if ($stmt = $mysqli->prepare("DELETE FROM my_table WHERE id = ? LIMIT 1")) {
$stmt->bind_param("i",$id);
$stmt->execute();
$stmt->close();
} else {
echo "ERROR: could not prepare SQL statement.";
}
$mysqli->close();
// redirect user after delete is successful
header("Location: Dashboard.php");
} else {
// if the 'id' variable isn't set, redirect the user
header("Location: Dashboard.php");
}
There is a similar question MySQLi Prepared Statement not executing
. Basically, you can try running the SQL directly in the database to see if you get any errors. Also confirm that the database user has delete permissions and that the id is stored as an integer in your database.
First I'd suggest you use the $_POST method, you can read more about it GET vs. POST.
Try using bindValue() instead of bindParam(), I believe something else needs to be declared for bindParam() I forget (I'm new at PHP too).
I'm trying to recall data from database to post later on
When someone logs in using this code:
function login($email, $password, $mysqli)
{
// Using prepared statements means that SQL injection is not possible.
if ($stmt = $mysqli->prepare("SELECT id, username, password, salt, phnumber, realname, age, sex FROM members WHERE email = ? LIMIT 1")) {
$stmt->bind_param('s', $email); // Bind "$email" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
// get variables from result.
$stmt->bind_result($user_id, $username, $db_password, $salt, $phnumber, $realname, $age, $sex);
$stmt->fetch();
}
}
Then I set variables for email and name using this code:
$realname = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $realname);
$_SESSION['realname'] = $realname;
$email = preg_replace("/\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b/", "", $email);
$_SESSION['email'] = $email;
Then when I recall all the variables using print_r($_SESSION); The email is posted without # or . for example: johnsmithyahoocom and also the name is posted without space like JohnSmith Which is undesirable. How can I make it post the right email form and space between names?
Why are you using preg_replace?
And I would recommend, if you are already using a database, to store only the users ID in the SESSION and fetch the other data from the database, when you need the users Information.
Sorry for wasting your time on this
Everything was going fine I just had to relogin to apply changes I made
/\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b/ is working fine and recalls the right email form from database I just had to restart the SESSION to see changed I made.
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);