the user exists in the database into the Get_Id - php

This is how I'm going to make a small sign system, it is such that it must find out if username is in the Get_id that you have visited,
GET_Id it is the page ID as it is for example 1 or 10
tilmeldt_navn the user's name on the page.
tilmeldt_email the person's own email.
I think like here in this still:
if ($stmt = $mysqli->prepare('SELECT tilmeldt_navn, tilmeldt_email FROM `tilmeldtOpgave` WHERE `get_id` = ?')) {
$stmt->bind_param('i', $id);
$id = $_GET['id'];
$stmt->execute();
$stmt->bind_result($tilmeldt_navn, $tilmeldt_email);
while ($stmt->fetch()) {
if($tilmeldt_navn == "")
{
echo "finds in the database";
}
else
{
echo "The finds in the database so can not sign me again!";
}
}
$stmt->close();
}
the problem is: it does not appear in the with some of them at all.
The need to find out whether the user has signed up for the get_id and if it has it must take the last of if and when it does not have to be the roof the first in the if

Honestly, it's really hard to understand what you really want to happen. But, since you try to
echo "finds in the database" it seems that you want to check if the record exist from your database.
Just try this:
if(isset($_GET['id'])){
$stmt = $mysqli->prepare("SELECT tilmeldt_navn, tilmeldt_email FROM `tilmeldtOpgave` WHERE `get_id` = ?");
$id= $_GET['id'];
$stmt->bind_param('s', $id);
$stmt->execute();
$stmt->bind_result($id);
$stmt->store_result();
if($stmt->num_rows == 1) //Check if value is returned
{
while($stmt->fetch()) //To fetch the contents of the row
{
echo 'Result Found';
}
}
else {
echo 'No result found';
}
$stmt->close();
$stmt->free_result();
}
$mysqli->close();
?>
Hope this helps.

Related

Why am I receiving null as a response for an sql column with data in it? (PHP)

I am building a log in system and every other part works perfectly fine except for the portion that cross references the entered password with the password in the database. So when I checked to see if the passwords match I realized that the password from the database is coming back as null. May I ask what is happening?? (There is no issue with the "uidExists" method, it seems to just be in the "loginUser" method).
This is based of of this video https://www.youtube.com/watch?v=gCo6JqGMi30
I believe its around the hour and 40 minute mark he gets to the loginUser function.
function loginUser($conn,$username,$pwd){
$uidExists = uidExists($conn,$username,$username);
if($uidExists === false){
header("location: ../login.php?error=wrongslogin");
exit();
}
else{
echo $pwd;
if(is_null($uidExists["userPwd"])){
echo "Empty bruv";
}
else{
echo $uidExists["userPwd"];
}
}
function uidExists($conn,$username,$email){
$sql = "SELECT * FROM users WHERE userUid = ? OR userEmail = ?;";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt,$sql)){
header("location: ../signup.php?error=stmtfailed");
exit();
}
mysqli_stmt_bind_param($stmt,"ss",$username,$email);
mysqli_stmt_execute($stmt);
$resultData = mysqli_stmt_get_result($stmt);
if(mysqli_fetch_assoc($resultData)){
return $row;
}
else{
$result = false;
return $result;
}
mysqli_stmt_close($stmt);
}
This doesn't look right:
$uidExists = uidExists($conn,$username,$username);
Should this be:
$uidExists = uidExists($conn,$username,$userPwd);

Checking if value is stored in the database with isset()

I want to display a page, if user doesn't pay for content (via Stripe) and therefore have to check in DB if he paid or not. If he paid, I store string "ok" into status and if he doesn't it's just blank.
Now I'm not sure why the following code doesn't work:
<?php
if(!isset($_SESSION["username"])) {
?>
Login to watch Satellite data.
<?php
$query = 'SELECT status
FROM users
WHERE username="'.$_SESSION["username"].'"';
$stmt = $conn->prepare($query);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$status = $row["status"];
if ($status !== "ok") {
$status_notpaid = true;
}
}
} elseif(isset($_SESSION["username"]) && isset($status_notpaid)) {
include("notpaid.php");
} else {
?>
<?php
$query = 'SELECT id
FROM users
WHERE username="'.$_SESSION["username"].'"';
$stmt = $conn->prepare($query);
$stmt->execute();
$result = $stmt->get_result();
?>
Hello <strong><?php echo $_SESSION["username"];?></strong> |
<?php
while ($row = $result->fetch_assoc()) {
echo $row["id"]; }
?>
I'm not sure why elseif(isset($_SESSION["username"]) && isset($status_notpaid)) { include("notpaid.php"); } doesn't work.
I am assuming the login script sets $_SESSION["username"] if login is successful.
It would make more sense to put the id of the users table, as I assume that is the primary key. You can keep username in session as well if you like and that would save you running some of this code at all.
<?php
if(!isset($_SESSION["userid"])) {
# user not logged in direct to login, and nothing else
echo 'Login to watch Satellite data.';
}
if (isset($_SESSION["userid"])) {
# then we are logged in
# So now we check if they paid
$query = 'SELECT status
FROM users
WHERE id=?';
$stmt = $conn->prepare($query);
$stmt->bind_param('i', $_SESSION["userid"])
$stmt->execute();
$result = $stmt->get_result();
# we had better only be getting one row as a resut of that query
# so a loop is totally unnecessary
$row = $result->fetch_assoc();
$status = $row["status"];
if ($status !== "ok") {
include("notpaid.php");
}
}
?>
Hello <strong><?php echo $_SESSION["username"];?></strong> | $_SESSION['userid']

How to delete the image path from a server using unlink in PHP?

I've almost finished my project but I'm stuck on a small problem I'm hoping to get help with. This is my first PHP/mysqli project and I'm still very "green". Any help is much appreciated.
I have been able to successfully upload and delete images from my database, however I can't seem to get the unlink command to delete the images from my server.
Please find below the code I am using in the background (hotel-imgdelete.php):
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
// 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 image from server
$path = "../hotels/";
$image = "name";
unlink($path.$image);
// delete record from database
if ($stmt = $mysqli->prepare("DELETE FROM hotels 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: ../home.php");
}
else
// if the 'id' variable isn't set, redirect the user
{
header("Location: ../delete-hotel-images.php");
}
?>
This is the code I am using to view and select the images to delete
(delete-hotel-images.php)
<?php
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM hotels ORDER BY id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
while ($row = $result->fetch_object())
{
$row->id;
echo "<div id='partner'><img src='hotels/" . $row->name . "'></a><br><br>";
echo "<center><a href='#' onclick='delete_user(". $row->id . ")'>Delete</a></center></div>";
}
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
?>
I'm not entirely sure what your filesystem looks like, or what the file is supposed to be, but it looks like you're trying to delete "../hotels/name", since $image is set to the string "name".
I'm assuming this wasn't intentional so that could be the problem there. If, however, you are trying to delete a directory (since it appears to have no file extension) you will need to use "rmdir" and not "unlink".
How are the images laid out on your filesystem?
sorted
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
// get the 'id' variable from the URL
$id = $_GET['id'];
if ($stmt = $mysqli->prepare("SELECT id, name FROM hotels WHERE id=?"));
{
$stmt->bind_param("i", $id);
$stmt->execute();
}
$stmt->bind_result($id, $name);
$stmt->fetch();
$path = "../images/hotels/";
$image = $name;
unlink($path.$image);
$stmt->close();
include_once 'db_connect.php';
include_once 'functions.php';
// delete record from database
if ($stmt = $mysqli->prepare("DELETE FROM hotels 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: ../home.php");
}
else
// if the 'id' variable isn't set, redirect the user
{
header("Location: ../delete-hotel-images.php");
}

PHP script to check If user already exists in MySQL database

I'm creating simple game for Facebook. All users who used app are written to database. I need always check If user already exists Is in database, how to do that correctly?
So I have variable $name = $user_profile['name']; It successfully returns user's name
And this is my part of code to check If user already exists in database.
$user_profile = $facebook->api('/me');
$name = $user_profile['name'];
$mysqli = new mysqli("host","asd","pw","asdf");
echo "1";
$sql = "SELECT COUNT(*) AS num FROM myTable WHERE userName = ?";
echo "2";
if ($stmt = $mysqli->prepare($sql)) {
echo "3";
$stmt->bind_param('s', $name);
echo "4";
$stmt->execute();
echo "5";
$results = $stmt->get_result();
echo "6";
$data = mysqli_fetch_assoc($results);
echo "7";
}
if($data['num'] != 0)
{
echo "bad";
print "user already exists\n";
} else {
echo "good";
$apiResponse = $facebook->api('/me/feed', 'POST', $post_data);
print "No user in database\n";
}
}
This code not working, It should post data on user's wall If user not exists in database. I spent many time to find reason why, but unsuccessfully. After debugging It don't show any errors. To find which line is incorrect after every line I used echo "number" so now I know which line is incorrect. It prints 1 2 3 4 5 and stucks. (everything what are below the code not loading.) So that means this line $results = $stmt->get_result(); is incorrect. But I misunderstood what's wrong with this line?
If I comment this line all code loading (then print 1 2 3 4 5 6 7 No user in database! and It post data on user's wall.) but in this case program always do the same, not checking database.
Also I've tried to change COUNT(*) to COUNT(userName), but the same.
So could you help me, please?
I've read this: Best way to check for existing user in mySQL database? but It not helped me.
P.s. In this case i need to use FB username.
Can you try this, $stmt->fetch() instead of mysqli_fetch_assoc($results)
$mysqli = new mysqli("host","asd","pw","asdf");
echo "1";
/* Create the prepared statement */
$stmt = $mysqli->prepare("SELECT COUNT(*) AS num FROM myTable WHERE userName = ?") or die("Prepared Statement Error: %s\n". $mysqli->error);
/* Execute the prepared Statement */
$stmt->execute();
/* Bind results to variables */
$stmt->bind_result($name);
$data = $stmt->fetch();
if($data['num'] > 0)
{
echo "bad";
print "user already exists\n";
} else {
echo "good";
$apiResponse = $facebook->api('/me/feed', 'POST', $post_data);
print "No user in database\n";
}
/* Close the statement */
$stmt->close();
Ref: http://forum.codecall.net/topic/44392-php-5-mysqli-prepared-statements/

PHP/MySQL - Prepared Statements - Is the usage in this example correct?

I am creating an part of a website that deals with confirmation of a user subscribing to a newsletter.
I am having trouble with the usage on prepared statements when selecting data.
This is basically a check against information that was sent to the user in an email and retrieved by getting the info from the entered url.
So there is a string or 'key' in the database that is sent to the user in an email as a link to a page on my site with the users details appended to the url. The script checks to see if these keys match
The problem is that when I run the script it will trigger an error. This says "wrong key".
The key in the database ($dbkey) is the same as the key provided in the email link. which is the same key that is made into $key. The problem though, is that in the while loop an error is being triggered and $dbkeyis not being passed the data from the database :
Notice: Trying to get property of non-object in C:\wamp\www\site\script.php on line 35
The sql statement when run in phpmyadmin does return the correct result set.
Here is the code:
$confirm= sanitize($_GET['confirm']);
$stmt = $link->prepare("SELECT id, dbkey FROM specials WHERE id = ?");
if (!$stmt)
{
$error = "{$link->errno} : {$link->error}";
include "$docRoot/html/main/error.html.php";
exit();
}
if (!$stmt->bind_param("i", $confirm))
{
$error = "{$stmt->errno} : {$stmt->error}";
include "$docRoot/html/main/error.html.php";
exit();
}
if (!$stmt->execute())
{
$error = "{$stmt->errno} : {$stmt->error}";
include "$docRoot/html/main/error.html.php";
exit();
}
$stmt->store_result();
if ($stmt->num_rows)
{
while ($row = $stmt->fetch())
{
$dbKey = $row->dbkey;
}
$key= sanitize($_GET['key']);
if ($dbKey !== $key)
{
echo 'wrong key';
}
}
else
{
echo 'not in database';
}
I would like to say that all other scripts connecting to the database in this manner do work, but this was the first time I have used prepared statements to select data. I wonder if this problem is caused by an error in my coding, hence the reason why I have posted this question.
If anyone could spot where I have gone wrong here, or possibly possibly provide some advice on how I would debug the code to see what exactly the error is that would be greatly appreciated!
Thanks!!
EDIT: The problem simply is the $key returns a string but $dbkey returns empty
EDIT2:
if ($stmt = $link->prepare("SELECT id, verified, dbkey FROM specials WHERE id=?")) {
$stmt->bind_param("i", $confirm);
$stmt->execute();
$stmt->bind_result($dbId, $dbVerified, $dbKey);
$stmt->fetch();
$stmt->close();
if ($dbKey !== $key)
{
echo 'wrong key';
}
else if ($dbVerified == 1)
{
echo 'already activated';
}
else if ($dbKey == $key && dbVerified == 0)
{
echo 'success';
}
}
else
}
echo 'user not in db';
}
$stmt->fetch() just returns a boolean indicating whether it was successful, not an object whose properties are the current row's fields. You need to call $stmt->bind_result() to specify into which variables you want the fields to be placed.
The approach taken in your second edit looks good, except that the test for whether the user is in the database should be onfetch(), not prepare() (or else use num_rows as you had previously). Thus:
if ($stmt = $link->prepare("SELECT id, verified, dbkey FROM specials WHERE id=?"))
{
$stmt->bind_param("i", $confirm);
$stmt->execute();
$stmt->bind_result($dbId, $dbVerified, $dbKey);
if ($stmt->fetch())
{
if ($dbVerified == 1)
{
echo 'already activated';
}
else if ($dbKey !== $key)
{
echo 'wrong key';
}
else if ($dbKey == $key && dbVerified == 0)
{
echo 'success';
}
}
else
}
echo 'user not in db';
}
$stmt->close();
}

Categories