I've been trying to store the session userUid and put it in the database under id. I want it to merge the two ids from different databases.
I tried setting the userUid as a variable and putting it into the database. userUid is the id from the signup/login page and profiles is the database i'm trying to insert it into.
if(!isset($_SESSION['userUid'])){
header("location: index.php"); // Redirecting To Home Page
$switch = $_SESSION['userUid'];
$Asql = "INSERT INTO profile (id) VALUES ('$switch');" ;
mysqli_query($conn2, $Asql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['id'] . "<br>";
}
}
}
I expect it to out put the newly inserted $_SESSION['userUid'] as "id" from the database profiles.
A few things to note,
Your current logic will never really work, because you only execute the query when the session-value is not set
You should always exit; after a header("Location:..."); call
You should be using prepared statements and bind your values through placeholders
An insert query has no num_rows (the equivalent is affected_rows for insert/update/delete queries) or fetch_*() methods associated with them.
if (!isset($_SESSION['userUid'])) {
header("location: index.php"); // Redirecting To Home Page
exit;
}
$sql = "INSERT INTO profile (id) VALUES (?);";
$stmt = $conn2->prepare($sql);
$stmt->bind_param("s", $_SESSION['userUid']);
$stmt->execute();
echo $stmt->affected_rows." rows inserted";
$stmt->close();
In order to properly check for errors, you should enable MySQLi exception mode by adding the following line before you create your MySQLi connection. That means that you have to use a try/catch for your query statements, but in turn means that you don't have to do individual error-checking for each function-call.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
You are trying to use mysqli_fetch_assoc on an insert query.
You could either just use $_SESSION['userUid'] or you can make a seperate select query to get the new row from the database.
First check the "if" condition in your code.
if(!isset($_SESSION['userUid'])):
...
else:
...
endif;
The final solution to you,
if(!isset($_SESSION['userUid'])):
header("location: index.php"); // Redirecting To Home Page
else:
$switch = $_SESSION['userUid'];
$Asql = "INSERT INTO profile (id) VALUES ('$switch');" ;
mysqli_query($conn2, $Asql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0):
while ($row = mysqli_fetch_assoc($result))
{
echo $row['id'] . "<br>";
}
endif;
endif;
Related
I am trying to build an override feature so users can manually remove a MySQL table row if they have the correct rights to do so. The user is prompted to input the same credentials used for program login as well as the uniqueID for the row that needs to be removed. Upon hitting the 'Submit' function, I run a series of if statements/ MySQL SELECT statements to check credentials, user rights and finally row Deletion with the result output as an alert.
However, my alert shows up blank and the row is not removed so I know there is a problem with my if statements. Upon testing, I believe the problem is when I try to use the previous query's results to run the next if statement logic.
How do I properly determine if the MySQL query returned a row using prepared statements?
All help is appreciated! Thank you!
My CODE:
if ((isset($_POST['overrideUsername'])) and (isset($_POST['overridePassword'])) and (isset($_POST['overrideUniqueID']))) {
$overridePasswordInput = $_POST['overridePassword'];
$overrideUsername = $_POST['overrideUsername'];
$overridePassword = ENCODE(($overridePasswordInput).(ENCRYPTION_SEED));
$roleID = '154';
$overrideUniqueID = $_POST['overrideUniqueID'];
//connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if(mysqli_connect_errno() ) {
printf('Could not connect: ' . mysqli_connect_error());
exit();
}
$conn->select_db($dbname);
if(! $conn->select_db($dbname) ) {
echo 'Could not select database. '.'<BR>';
}
$sql1 = "SELECT users.id FROM users WHERE (users.login = ?) AND (users.password = ?)";
$stmt1 = $conn->prepare($sql1);
$stmt1->bind_param('ss', $overrideUsername, $overridePassword);
$stmt1->execute();
$stmt1->bind_result($userID);
//$result1 = $stmt1->get_result();
if ($stmt1->fetch()) {
$sql2 = "SELECT * FROM rolestousers WHERE (rolestousers.userid = ?) AND (rolestousers.roleid = ?)";
$stmt2 = $conn->prepare($sql2);
$stmt2->bind_param('ss', $userID, $roleID);
$stmt2->execute();
$stmt2->store_result();
if ($stmt2->fetch()) {
$sql3 = "DELETE * FROM locator_time_track_out WHERE locator_time_track_out.uniqueid = ?";
$stmt3 = $conn->prepare($sql2);
$stmt3->bind_param('s', $overrideUniqueID);
$stmt3->execute();
$stmt3->store_result();
if ($stmt3->fetch()) {
echo 'Override Successful! Please scan the unit again to close it out.';
} else {
echo 'Could Not Delete Record from the table.';
}//End $sql3 if.
} else {
echo 'User does not have override permission. Please contact the IT Department.';
}//End $sql2 if.
} else {
echo 'Your login information is incorrect. Please try again. If the issue persists, contact the IT Department.';
}//End $sql1 if.
//Free the result variable.
$stmt1->free();
$stmt2->free();
$stmt3->free();
$stmt1->close();
//Close the Database connection.
$conn->close();
}//End If statement
NOTE: I am definitely sure my DB connection information is correct. The issue resides after I connect into the database. I have also tested the code using only the first if statement and get the blank alert so I'm not making it past the first if statement.
EDIT:: My php Script was definitely failing, but even earlier than expected, at the following code:
$overridePassword = ENCODE(($overridePasswordInput).(ENCRYPTION_SEED));
So my issue is that I need to properly compare the password and encryption seed information. However, the previous programmer used the following line to do the same process (which is obviously unsafe):
$querystatement = "SELECT id, firstname, lastname, email, phone, department, employeenumber, admin, usertype FROM users WHERE login=\"".mysql_real_escape_string($user)."\" AND password=ENCODE(\"".mysql_real_escape_string($pass)."\",\"".mysql_real_escape_string(ENCRYPTION_SEED)."\")";
$queryresult = $this->db->query($querystatement);
I will need to fix this issue before I can even test the functionality of the if logic using prepared statements.
Your are passing wrong variable for delete query
$stmt3 = $conn->prepare($sql3);
Please refer [ http://www.plus2net.com/php_tutorial/pdo-delete.php ]
When I change SELECT * to SELECT count(*) the script stops working altogether. How to I add a count(*) to this file and a statement if row count for $user >= 20 allow to INSERT else do nothing.
// Include needed files
include 'mysql.php';
// Connect to MySQL
connectMySQL();
//****** SECURITY CHECK *********
session_start();
if(isset($_SESSION['userid'])){
$user = mysql_real_escape_string($_SESSION['userid']);
//*******************************
// Retrieves variables through AJAX
$favid = mysql_real_escape_string($_GET['favid']);
// $favid = mysql_real_escape_string($_GET['favid']);
// Firstly, check if article is favourite or not
$query = mysql_query("SELECT * FROM ajaxfavourites WHERE user='$user' AND favid='$favid'");
$matches = mysql_num_rows($query);
// If it is not favourited, add as favourite
if($matches == '0'){
mysql_query("INSERT INTO ajaxfavourites (user, favid, exptime) VALUES ('$user', '$favid', CURRENT_TIMESTAMP)");
echo "";
}
// Instead, if it is favourited, then remove from favourites
if($matches != '0'){
mysql_query("DELETE FROM ajaxfavourites WHERE user='$user' AND favid='$favid'");
echo "";
}
} else {
// Someone tries to directly access the file!
echo "Invalid session!";
}
Thanks!
Please do necessary steps to avoid SQL injection, also try using mysqli_* functions instead of mysql_* functions
$query = mysql_query("SELECT COUNT(*) as cnt FROM ajaxfavourites WHERE user='$user' AND favid='$favid'");
$res = mysql_fetch_array($query);
// If it is not favourited, add as favourite
if($res[cnt] == 0){
mysql_query("INSERT INTO ajaxfavourites (user, favid, exptime) VALUES ('$user', '$favid', CURRENT_TIMESTAMP)");
echo "";
}
// Instead, if it is favourited, then remove from favourites
if($res[cnt] > 0){
mysql_query("DELETE FROM ajaxfavourites WHERE user='$user' AND favid='$favid'");
echo "";
}
I got it resolved. The reason it wasn't working was it took both values into consideration ($user and $favid). As a result it was always either 0 or 1.
I had to create another mysql query with just one value in it ($user) and then I was able to get the row count. Thanks everyone!
try to use below query, using below query if requested user's session will be 20+ then only insert statement will execute else insert statement will be ignore.
INSERT INTO ajaxfavourites(USER,favid ,exptime)
SELECT 1 AS USER, 1 AS favid, NOW() AS exptime
FROM ajaxfavourites WHERE USER=1 HAVING COUNT(*) >=20;
<?php
include('session.php');
?>
<?php
require_once('mysql_connect.php');
$query2 ="SELECT id, username, banned FROM login WHERE username ='$login_session'";
$result2 = mysql_query($query2) OR die($mysql_error());
$row = mysql_num_rows($result2);
if($row['banned'] == 1) {
die();
}
?>
Session.php
<?php
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "", "");
// Selecting Database
$db = mysql_select_db("", $connection);
session_start();// Starting Session
// Storing Session
$user_check=$_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql=mysql_query("select username from login where username='$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session =$row['username'];
if(!isset($login_session)){
mysql_close($connection); // Closing Connection
header('Location: login.php'); // Redirecting To Home Page
}
?>
As you can see , im trying to stop people who are banned from loading profile.php
it doesnt stop the profile page from loading
thanks fred, that worked – KIXEYE
make it to an answer, ill mark as answered as soon as i can – KIXEYE
As per the OP's wish:
You're using the wrong function for $row. Either use one that will fetch a row as an array, or change if($row['banned'] == 1) to if($row == 1) to work with mysql_num_rows.
Footnotes:
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
Example pulled from https://stackoverflow.com/a/6620252/
$user = "bob";
$user = mysql_real_escape_string($user);
$result = mysql_query("SELECT COUNT(*) AS num_rows FROM my_table WHERE username='{$user}' LIMIT 1;");
$row = mysql_fetch_array($result);
if($row["num_rows"] > 0){
//user exists
}
Edit:
If your banned row contains 1 or 0 to check if they're banned, then add another parameter to your where clause. I.e.: WHERE username ='$login_session' AND banned !=1 if banned column is an int type. If not, wrap 1 in quotes.
This translates to WHERE username exists and is 'John' and banned does NOT equal 1. Or make it 0, it's your choice.
Then why don't you just fetch user who are not banned:
$ses_sql = mysql_query("SELECT username FROM login WHERE username='$user_check' AND banned <> 1",$connection);
$numofresult = mysql_num_rows($ses_sql);
Then check if it has a result:
if($numofresult > 0){
/* SUCCESS */
}
else {
/* BANNED */
}
To compromise SQL injections, use mysql_real_escape_string() function.
$user = mysql_real_escape_string($username,$connection);
But a better recommendation is to use mysqli_* prepared statement or PDO.
if($stmt = $connection->prepare("SELECT username FROM login WHERE username='$user_check' AND banned <> 1")){
$stmt->execute();
$stmt->store_result();
$numofresult = $stmt->num_rows;
$stmt->close();
}
mysql_num_rows() returns a number of rows, not the rows themselves.
You should use mysql_fetch_assoc() or similar function.
So I have a log in script that creates a $_SESSION based on the username of the user logging in. On another page I wish to display content if the row for that user has a 1 in it. If it has a 0 in that row, then do not display the content. I am having issues here with no matter what I've tried, it does not display YES no matter the user I log in with.
test1 = 1
test2 = 0
<?
require_once 'dbinfo.php';
$sess = $_SESSION['authuser'];
$link = mysqli_connect($servername, $username, $password);
if (!$link) {
die('Could not connect: ' . mysqli_error($link));
}
mysqli_select_db($link, $database) or trigger_error(mysqli_error($link));
$acc = "SELECT username FROM admins WHERE username = '$sess'";
$result = mysqli_query($link, $acc) or trigger_error(mysqli_error($link));
ob_start();
while($row = $result->fetch_assoc())
{
if($row['access'] == 1)
{
echo 'YES';
}
elseif ($row['access'] == 0)
{
echo 'NO';
}
}
ob_end_flush()
?>
The solution was easy and Class pointed it out. Forgot to SELECT access... instead of username. Rookie mistake.
You have to write
session_start();
in all of your files that want to make use of $_SESSION .
And your select query will only output the username column, as you have selected only this one, try it with
SELECT * FROM admins WHERE username = '$sess'
or
SELECT username, access FROM admins WHERE username = '$sess'
instead.
What you absolutely should do is learning prepared statements, as your actual query is wide open to sql injections.
Prepared Statement example (from php.net)
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
$stmt->bind_param("s", $city);
$stmt->execute();
$stmt->bind_result($district);
$stmt->fetch();
$stmt->close();
}
$mysqli->close();
You can read more about mysqli prepared statements here
write access (column) and Try using isset() function and the operator === when you get 0 in a returned variable.
So I am trying to develop an app and I need an API, so I am trying now PHP in order to pass my variables from the app to the MYSQL. I am trying with $_GET first in order to see if everything works fine. I tried to pass variables to the database through MYSQL Workbench and then from the app and worked fine. But, when I emptied the table and tried again it didn't work! So I am guessing that my loop doesn't respond well to the fact that my table is empty(?)
This is the code that checks for the email and username if exists and if not insert the variables:
$result = 'notSet';
$query=mysql_query("SELECT * FROM project");
while ($row = mysql_fetch_assoc($query)) {
if(strcmp($row['email'],$email)==0){ //strcmp uses two strings and it returns an integer, if 0 then no differences if more than 0 then there are
$result = 'Email exists';
}else{
if(strcmp($row['username'],$username)==0){
$result = 'Username exists';
}else{
//encryption
$insert = mysql_query("INSERT INTO project VALUES ('$userid', '$fullname','$username','$password','$course','$year','$age','$email')");
$result = 'Registered';
session_start();
$session = session_id();
$SESSION['username']=$username;
}
}
}
Any ideas??
Your table is empty. $query is returning false. Because of this your loop is not executed. You should change the code like this:
if($query){
while(){
//check username and email
}
}
else{
// execute insert query
}
Can you try this code:
$result = 'notSet';
$query = mysql_query("SELECT * FROM project WHERE email = '$email' OR username = '$username' ");
if(mysql_num_rows($query) === 0 ){
$insert = mysql_query("INSERT INTO project VALUES ('$userid', '$fullname','$username','$password','$course','$year','$age','$email')");
$result = 'Registered';
session_start();
$session = session_id();
$SESSION['username']=$username;
}
else{
$result = 'Username or Email exists';
}
We should add single quotes ' only if field type is not integer type. For eg if userid field is integer type and rest of fields are not integer type then query will be
$insert = mysql_query("INSERT INTO project VALUES ($userid, '$fullname','$username','$password','$course','$year','$age','$email')") or die(mysql_error());
thanks
First: you should switch to PDO or mysqli, because the mysql_* functions are deprecated. Please follow the links in Shais comment.
To get the INSERT done, you've got to change your logic. With your code right now, it will never be executed for an empty resultset. You could do it so:
$query=mysql_query("SELECT * FROM project");
if (mysql_num_rows($query) > 0) {
// we've got results, let's loop through the resultset
while($row = mysql_fetch_assoc($query)) {
// do something with the result
}
}
else {
// we've got no results,
// do the insert
}
mysql_query will return a resource for SELECT type queries. A resource evaluates in PHP to true. You can use mysql_num_rows() to check, whether your resultset is not empty.
Excerpt from the linked manual:
Use mysql_num_rows() to find out how many rows were returned for a
SELECT statement
PS: Please consider the content of the red box.
<?php
$query=mysql_query("INSERT INTO project set id=$userid,
'fullname'=$fullname,
'username'=$username,
'password'=$password,
'course'=$course,
'year'=$year,
'age'=$age,
'email'=$email
");
?>