This is designed to help me understand what is going on with the query.
It should tell me what values are queried and print them.
It does not pull the userid for some reason, instead saying 0 or null.
It prints:
string(0) "" NULL string(11) "pwdhere" The userid is 0 and the password is pwdhere----oooo set as oooo----6179cbcdc21dd1b3c478e7e2226e0432
Should the session be these 32 characters or the userid/username?
Why is it not pulling userid?
AND WHY DOES IT WORK WHEN THE PASSWORD IS WRONG?
THANKS!!!
<?php
//Store the login in the session:
session_start();
?>
<?php
include ("connectionlinkhere.php");
//connection errors if any...
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//GETTING DATA FROM FORM
$userid = htmlentities($_POST['userid'], ENT_QUOTES);
$password = htmlentities($_POST['password'], ENT_QUOTES);
//create a prepared statement
if ($stmt = $mysqli->prepare("SELECT userid, username, password FROM admins WHERE userid=? and password=?"))
{
// bind parameters-define them...the -iss- is for integer, string, string
$stmt->bind_param("iss", $userid, $username, $password);
//execute...
$stmt->execute();
// bind result variables
$stmt->bind_result($userid, $username, $password);
//fetch value
$stmt->fetch();
//to see what the database query is actually pulling
var_dump($userid, $username, $password);
//tell it to format the query results and then print the sentence
$format = 'The userid is %d and the password is %s';
echo sprintf($format, $userid, $password);
//set session
$_SESSION['userid'] = $_POST['username'];
//just to break up the line
echo "----oooo set as oooo----" ;
//this is the 32 digit session value, although assigned as userid or username
echo session_id();
/* close statement */
$stmt->close();
}
// redirect the user
//header("Location: index.php");
else
{
echo "what are you doing...";
}
/* close connection */
$mysqli->close();
?>
You use bind_param() to replace ? in your query with what you are looking for. You use bind_result() to get the data from your query (which you have done correctly, from what I can see). Put the data you want to search for in bind_param() to replace the ?'s.
Was writing a comment, then realized this may be the issue... Thank you #EdCottrell.
Related
Sometimes it sucks when you have these ; " ' (semicolon, single and double quotation marks) everything in a string.
Question is simple what is the easiest way to send those sting into the database.
base64_encode();
base64_decode();
// Is not an option. I need to keep those data just same as it is.
You need
addslashes('your text') // in your php page
PDO statements is the best solution to your problem of executing SQL queries to your database with values that have single/double quotation marks... but more importantly PDO statements help prevent SQL injection.
To show you how this works, this very simple example gives you a basic understanding of how PDO statements work. All this example does is make the connection to the database and insert the username, email and password to the users table.
<?php
// START ESTABLISHING CONNECTION...
$dsn = 'mysql:host=host_name_here;dbname=db_name_here';
//DB username
$uname = 'username_here';
//DB password
$pass = 'password_here';
try
{
$db = new PDO($dsn, $uname, $pass);
$db->setAttribute(PDO::ERRMODE_SILENT, PDO::ATTR_EMULATE_PREPARES);
error_reporting(0);
} catch (PDOException $ex)
{
echo "Database error:" . $ex->getMessage();
}
// END ESTABLISHING CONNECTION - CONNECTION IS MADE.
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$hashed_password = password_hash($password, DEFAULT_BCRYPT);
//Validation on inputs here...
// Your SQL query... here is a sample one.
$query = "INSERT INTO users (userName, email, password) VALUES (:userName, :email, :password)";
$statement = $db->prepare($query);
// The values you wish to put in.
$statementInputs = array("userName" => $username, "email" => $email, "password" => $hashed_password);
$statement->execute($statementInputs);
$statement->closeCursor();
?>
You could put the establishing connection part in a separate file and require_once that file to avoid having to write the same code, again and again to establish a connection to your database.
Use mysqli_real_escape_string
$someText = mysqli_real_escape_string($con,"It's a test.");
where $con is your database connection variable.
I am trying to compare a MySQL table column which I have imported to my script and compare it with a PHP value which I have defined.
I am trying to make an if loop that checks if any of the values in the column are equal to the variable.
// Connect to database containing order information
$servername = "server";
$username = "user";
$password = "pass";
// Create connection
$conn = new mysqli($servername,$username,$password);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
// define variables and set to empty values
$name = $ordernumber = "";
// Load up data from the form
$ordernumber = ($_POST['order_number']);
// Get SQL info
$sql = "SELECT order_number FROM p_orders;";
if ($conn->query($sql) === TRUE)
{
echo "Checked Orders.....";
}
else
{
echo "Failed to check orders, please contact Support for assistance" . $conn->error;
}
// Checking Script
if ($ordernumber === $orders)
{
echo "Order Number Found.... Let's Select a Seat";
}
else
{
echo "Your Order was not found, either you did not order a reservation ticket, have not waited 3 days or you entered the number wrong. If issues persist then please contact Support."
};
The end part of the script should be like this...
$stmt = $mysqli->stmt_init();
if ($stmt->prepare('SELECT order_number FROM p_orders WHERE orderID = ?')) {
$stmt->bind_param('s',$_POST['order_number']); // i if order number is int
$stmt->execute();
$stmt->bind_result($order_number);
$stmt->fetch();
if (!empty($order_number))
echo "Order Number Found.... Let's Select a Seat";
}else {
echo "Your Order was not found...";
}
$stmt->close();
}
$mysqli->close();
...note that the query now looks for only the records that match and note the use of prepared statement to make safe the post variable from SQL Injection.
The reason to collect only the matching items from SQL is otherwise, if you have a million records, the database would return all of them and then PHP will need to loop through them (this can cause maximum execution, memory and other errors). Instead databases where built to look things up like this - note an index on this field would be good and also use of a "youtube style" id is recommended, which is why I've assumed the use of a string for it's instead of a number as the variable minght imply - and it's not the "id" which is good for a number of reasons... I've added a link to explain "youtube style" id which I'll not go into detail here but there is a lot of win in using that :)
UPDATED based on...
http://php.net/manual/en/mysqli-stmt.prepare.php
MySQL prepared statement vs normal query. Gains & Losses
https://www.youtube.com/watch?v=gocwRvLhDf8 (Will YouTube Ever Run Out Of Video IDs?)
Preferably use a WHERE clause searching for the order id and mysqli prepared statement, like below.
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$name = "";
// Load up data from the form
$ordernumber = $_POST['order_number'];
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT COUNT(*) FROM p_orders WHERE orderID=?")) {
/* bind parameters for markers */
$stmt->bind_param("i", $ordernumber ); // "i" if order number is integer, "s" if string
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($counter);
/* fetch value */
$stmt->fetch();
if ($counter>0) { // if order id is in array or id's
echo "Order Number Found.... Let's Select a Seat";
} else {
echo "Your Order was not found, either you did not order a reservation ticket, have not waited 3 days or you entered the number wrong. If issues persist then please contact Support."
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
I wrote the following code to retrieve data from the database
<?php
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'users';
$con = mysqli_connect($host, $username, $password, $database);
// catch the values that are passed by the POST method
$courseId=$_POST["courseId"];
$hall=$_POST["hall"];
$day=$_POST["day"];
$year=$_POST["year"];
$time=$_POST["time"];
$statement=mysqli_prepare($con,"SELECT * FROM Lectures WHERE day=? AND timeInterval=? AND courseId=? AND hall=? AND year=? ");
mysqli_stmt_bind_param($statement,"sssss",$courseId,$hall,$day,$year,$time);
mysqli_stmt_execute($statement);
// have to collect the results that are coming after the query is being executed
mysqli_stmt_store_result($statement); //storing the results in a buffer for temporary
// now we need to bind the results
mysqli_stmt_bind_result($statement,$day,$time,$courseId,$hall,$year,$noStudents,$courseRefName,$courseRefTelNo,$lecturer);
// to send the data via JSON string
$lectureDetails=array();
mysqli_stmt_fetch($statement);
$lectureDetails["day"]=$day;
$lectureDetails["time"]=$time;
$lectureDetails["courseId"]=$courseId;
$lectureDetails["hall"]=$hall;
$lectureDetails["year"]=$year;
$lectureDetails["noStudents"]=$noStudents;
$lectureDetails["courseRefName"]=$courseRefName;
$lectureDetails["courseRefTelNo"]=$courseRefTelNo;
$lectureDetails["lecturer"]=$lecturer;
// data are stored in the array. now we need to send them via a JSON string
echo json_encode($lectureDetails);
// the java file that calls this method will receive echo
//The PHP json_encode function returns a string, containing the JSON equivalent of the values passed to it
//so in here $lectureDetails array is passed throught throughe JSON String.
mysqli_stmt_close($statement); //closing the connection
mysqli_close($con); //closing the sql connection
?>
according to the working fetching file as below(this returns values as expected)
<?php
//database connection
$host = 'localhost';
$user1 = 'root';
$password1 = '';
$database = 'users';
$con = mysqli_connect($host, $user1, $password1, $database);
//checking the validity of the database
// if(!$con){
//die("connection Failed" . mysqli_connect_error());}
//echo "connected Successfully";
$userName=$_POST["userName"];
$password=$_POST["password"];
$statement=mysqli_prepare($con,"SELECT * FROM usersLogged WHERE userName=? AND password=?");
//to prevent from sql injection
mysqli_stmt_bind_param($statement,"ss",$userName,$password);
mysqli_stmt_execute($statement);
//after executing the command we will get all the results that were selected
mysqli_stmt_store_result($statement); //storing the results in a buffer for temporary
//we need to bind the results
mysqli_stmt_bind_result($statement, $userId, $userName, $firstName, $lastName, $password, $position,$birthDate,$qualification,$email);
//now we need to store them into an array inoder to send them via a JSON
$user=array();
mysqli_stmt_fetch($statement);
//fetch the result from a prepared statement into the variables bound by mysqli_stmt_bind_result.
//Data are transferred unbuffered without calling mysqli_stmt_store_result() which can decrease performance (but reduces memory cost).
//storing the values which are fetched from the database are kept in the array(#user)
$user["userName"]=$userName;
$user["firstName"]=$firstName;
$user["lastName"]=$lastName;
$user["password"]=$password;
$user["position"]=$position;
$user["birthDate"]=$birthDate;
$user["qualification"]=$qualification;
$user["email"]=$email;
//now we need to pass the content to the phone,we send the array in a json
echo json_encode($user); // the java file that calls this method will receive echo
//The PHP json_encode function returns a string, containing the JSON equivalent of the values passed to it
//so in here $user array is passed throught the JSON String.
mysqli_stmt_close($statement);
mysqli_close($con);
?>
but the above php file is not fetching data from the mysql database.
I have created a Lectures table at the current users database and day time courseId hall year courseRefName and lecuturer are of String data type , noStudents and courseRefTelNo are of integer datatype.
Is there any mistake in the mysqli_prepare or in the way this is encoded to JSON, because Iam not getting any return from this (above) php file to my java in android application
I found the problem, it was the mismatch between the data sent via POST and in the database had caused the problem. I have sent time in form of 08.00-10.00 and in database they were as 08-10 in form of 5 digits. So if anyone encounter problems like these be first check the data in the database and the values you passed through POST method
I'm setting up a blog type page for my business. Brand new to MySQL and PHP. Set up this login system. For some reason have no idea why the login is dropping. Suppose to check for errors then return 'good' through php if the email and password is right. If php returns good then it's suppose to redirect to the blog page.
Been dealing with this for a few months need desperate help please. Thank you.
Here is the php code that goes along with the jquery.
Link to test site is here.
test.toddprod.com/login
Would really appreciated the help.
Thanks
<?php
#fake mysql connection first
DEFINE ('DB_USER','usernamegoeshere');
DEFINE ('DB_PASSWORD','passwordhere');
DEFINE ('DB_HOST','hostnamehere');
DEFINE ('DB_NAME','andtheotherthinghere');
$dbc = mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) or die ('Could not connect to MySQL');
$db = mysql_select_db(DB_NAME, $dbc) or die('Could not select database.'.mysql_error());
$e = $_POST['email'];
$pass = $_POST['pass'];
$q = 'SELECT user_id from toddprod where email="'.$e.'" and pass= SHA1("'.$pass.'")';
$r = mysql_query($db, $q);
if( mysql_num_rows($r)==1 ){
setcookie ( 'user_id', $r);
setcookie ( 'email', '$e');
setcookie ( 'logged-in', 'true');
echo 'good';
}
else if (mysql_num_rows($r)==0) {
echo 'Your '.$e.' with password '.$pass;
};
mysql_close ($db);
?>
Umm there's a number of things I see wrong here...
First of all your query should be sanitized...
$email = mysql_real_escape_string ($_POST['email']); // escape the email
$pass = SHA1(mysql_real_escape_string ($_POST['pass'])); // escape and encrypt the pass
// now you can put it into the query safely
$query = "SELECT user_id from toddprod where email = '$email' and pass = '$pass' ";
Next you're executing the query wrong, the mysql_query function takes two arguments, the query and the database connection. You're passing the wrong arguments, you're passing the query and the result of the mysql_select_db function which is just a boolean value. So you have to $dbc not $db into that query, and even then you're passing the arguments in the wrong order. The query goes first, than the connection. So it should be...
$result = mysql_query($query, $dbc);
Next you're trying to set the return value from the mysql_query function as your cookie but that value is a resource, not the userid that you need. You have to actually read the value from the resource like this.
$row = mysql_fetch_array($result);
$userid = $row["user_id"];
setcookie('user_id', $userid);
Moving on... when you're setting the email cookie, you have the variable in single quotes, so the cookie will actually contain $e and not the actual email because single quotes store strings litterly (without parsing the variables). So you should either use double quotes, or no quotes at all. So either one of the following is fine...
setcookie('email', "$e");
setcookie('email', $e);
Last but not least, you should not have the semicolon at the end of your if-statement, and you again you need to pass the connection not the database-selection result into the mysql_close function, so it should be
mysql_close($dbc);
There, hope this gets you somewhere, try out these changes and if the problem persists i'd be happy to help you further.
Here are links that will help you out:
http://www.php.net/manual/en/function.mysql-query.php
http://www.php.net/manual/en/function.mysql-fetch-array.php
http://www.php.net/manual/en/function.mysql-real-escape-string.php
Edit:
Here, I have fixed the code according to the problems I found. Try it out, I could not test it so it might have some small syntax errors here and there, but it should give you something to compare with. Also for the future, I would suggest that you name your variables semantically/properly so it's easier for others to pickup and it will also keep you from getting confused like you were passing $db instead of $dbc into a few of your functions.
<?php
// keep the function names in lowercase, no reason, just looks better to me
define('DB_USER', 'usernamegoeshere');
define('DB_PASSWORD', 'passwordhere');
define('DB_HOST', 'hostnamehere');
define('DB_NAME', 'andtheotherthinghere');
// connect to the mysql server
$conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die ('Could not connect to MySQL');
// select the database, you don't need to store the result, it just returns true or false
mysql_select_db(DB_NAME, $conn) or die('Could not select database.' .mysql_error());
// escape the input
$email = mysql_real_escape_string($_POST['email']);
$pass = sha1(mysql_real_escape_string($_POST['pass']));
// create the query
$query = "SELECT user_id FROM toddprod WHERE email = '$email' AND pass = '$pass'";
// execute the query
$result = mysql_query($query, $conn);
$usercount = mysql_num_rows($result);
if($usercount == 1){
// read the results and get the user_id
$row = mysql_fetch_array($result);
$userid = $row['user_id'];
// set the cookies
setcookie('user_id', $userid);
setcookie('email', $email);
setcookie('logged-in', 'true');
// echo success message
echo 'good';
}elseif($usercount == 0) {
echo "You're $email with password $pass";
}
mysql_close($conn);
?>
First things first, you MUST sanitise user input with mysql_real_escape_string():
$e = mysql_real_escape_string ($_POST['email']);
$pass = mysql_real_escape_string ($_POST['pass']);
Read up a bit on SQL injection, you'll be very glad you did.
As for the main problem, could you provide a bit more context? How are you checking to see if the user is logged in?
So I am just doing a simple email verification for testing/learning purposes, however I cannot figure out what is wrong. Here is the problem:
The query works.. it updates the field in my table, but it should only do so if it active=0. So basically, it still echo's "success" even if active=1, which it should not be able to query, because its only supposed to grab WHERE active=0 ... this make sense? Here take a look
<?php
$connection = new mysqli('localhost', 'user', 'pass', 'db');
if (mysqli_connect_errno()) {
printf("Can't connect to MySQL Server. Errorcode: %s\n",
mysqli_connect_error());
exit;
}
$email = $_GET['email'];
$activation = $_GET['hash'];
$query = $connection->query("UPDATE users SET active = '1' WHERE
email='".$email."' AND activationCode='".$activation."' AND active='0'");
if ($query){
echo "success";
} else {
echo "fail";
}
$connection->close();
?>
The query returns true because the query was executed just fine, even if it didn't affect any rows. It only returns false if the query is invalid. You should look into retrieving the number of affected rows. (mysql_num_rows($query) for example.)
Also, you should use mysql_real_escape_string($getvalue) when using values from $_GET or $_POST in your queries to prevent MySQL injection.