PHP Bind_param fetch data - php

Guys im using Bind_param in php to retrieve Username and password from Login table. my question is how can i fetch all the info of user, and pass it to variable as an object? please see my code below
require 'dbc.php';
require 'security.php';
$myusername=trim($_POST['strusername']);
$mypassword=trim($_POST['strpassword']);
$myusername =escape($myusername);
$mypassword=escape($mypassword);
$sql = "SELECT * FROM login WHERE strusername=? AND strpassword=?";
$stmt = $db->prepare($sql);
$stmt->bind_param('ss',$myusername,$mypassword);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows){
echo "user verified, Access Granted.";
// while($row=$stmt->fetch_object()){
// $strfullname= $row->strfullname;
// $strcompany= $row->strcompany;
// $strdept= $row->strdept;
// $strloc= $row->strloc;
// $strposition= $row->strposition;
// $strauthorization= $row->strauthorization;
// $stremailadd= $row->stremailadd;
// $strcostcent= $row->strcostcent;
// $strtelephone= $row->strtelephone;
// };
// how to fetch all data in my query using param LIKE THIS
}else
{
echo "Invalid Username or Password";
}

Seems like what you're looking for is extract(), used with fetch_row(). So you'd end up with something like:
while ($row = $stmt->fetch_row()) {
extract($row, EXTR_OVERWRITE);
// your logic here...
}
As fair warning, this will overwrite any variables with the same name as your database columns. Since you're pulling from the database rather than a superglobal you at least know what you're getting into, but it's still a risk, particularly if you've got this code in global scope rather than inside a function/method.
As such, you may want to wrap your row-to-be-extracted in array_intersect_key(), like so:
$allowedFields = array_flip(['strfullname', 'strcompany', 'strdept',
'strloc', 'strposition', 'strauthorization', 'stremailadd',
'strcostcent', 'strtelephone']);
while ($row = $stmt->fetch_row()) {
extract(array_intersect_key($row, $allowedFields), EXTR_OVERWRITE);
// your logic here...
}
so your code documents which fields will suddenly turn into (local or global) variables.

Related

PHP MySQL SELECT WHERE statement not working properly

I've been debugging this small amount of code for hours and cannot solve it. I am trying to find a result inside the database table where the specified username exists.
if (empty($_POST['username'])) {
die("Enter a username please");
} else {
$username = $_POST['username'];
}
// check do username under that name already exists in db ?
function checker()
{
// including username and db variables from global scope
global $db;
global $username;
// making query
$query = "SELECT username FROM game.usersinfo WHERE username = :username";
$select = $db->prepare($query);
$select->execute(['username' => $username]);
return $select;
//expected value of select is false
}
// function call
checker();
The problem is due to PHP PDO->execute() documentation. It will throw an object on success and false on failure. I expect false to show to me, but the object always shows. There is no username in my database table that matches the username that I passed in the parameter. I tried already to use only pdo::query() method, but it didn't work.

PHP SQL query doesnt return a result

I have a button in a webapp that allows users to request a specially formatted number. When a user click this button 2 scripts run. The first that is fully functional, looks at a number table finds the largest number and increments it by 1. (This is not the Primary Key) the second script which is partially working gets the current date and runs a SQL query to get which period that date falls in. (Periods in this case not always equaling a full month) I know this script is at least partially working because I can access the $datetoday variable called in that script file. However it is not returning the requested data from the periods table. Anyone that could help me identify what I am doing wrong?
<?php
include 'dbh.inc.php';
$datetoday = date("Ymd");
$sql = "SELECT p_num FROM periods where '$datetoday' BETWEEN p_start AND p_end";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../quote.php?quotes=failed_to_write");
exit();
} else {
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
$pnum = $row;
mysqli_stmt_close($stmt);
}
If it helps any one I published my code to https://github.com/cwilson-vts/Quote-Appliction
So first off, I do not use msqli and never learned it. However, I believe I get the gist of what you want to do. I use PDO because I FEEL that it is easier to use, easier to read and it's also what I learned starting off. It's kinda like Apple vs. Samsung... no one product is exactly wrong or right. And each have their advantages and disadvantages. What I'm about to provide you will be in PDO form so I hope that you will be able to use this. And if you can't then no worries.
I want to first address one major thing that I saw and that is you interlacing variables directly into a mysql statement. This is not considered standard practice and is not safe due to sql injections. For reference, I would like you to read these sites:
http://php.net/manual/en/security.database.sql-injection.php
http://php.net/manual/en/pdo.prepared-statements.php
Next, I'm noticing you're using datetime as a variable name. I advise against this as this is reserved in most programming languages and can be tricky. So instead, I am going to change it something that won't be sensitive to it such as $now = "hello world data";
Also I'm not seeing where you would print the result? Or did you just not include that?
Another thing to consider: is your datetime variable the same format as what you are storing in your db? Because if not, you will return 0 results every time. Also make sure it is the right time zone too. Because that will really screw with you. And I will show you that in the code below too.
So now on to the actual code! I will be providing you with everything from the db connection code to the sql execution.
DB CONNECTION FILE:
<?php
$host = '127.0.0.1';
$user = 'root';
$pw = '';
$db = 'test'; // your db name here (replace 'test' with whatever your db name is)
try {
// this is the variable will call on later in the main file
$conn = new PDO("mysql:host=$host;dbname=$db;", $user, $pw);
} catch (PDOException $e) {
// kills the page and returns mysql error
die("Connection failed: " . $e->getMessage());
}
?>
The data file:
<?php
// calls on the db connection file
require 'dbconfig.php';
// set default date (can be whatever you need compared to your web server's timezone). For this example we will assume the web server is operating on EST.
date_default_timezone('US/Eastern');
$now = date("Ymd");
// check that the $now var is set
if(isset($now)) {
$query = $conn->prepare("SELECT p_num FROM periods WHERE p_start BETWEEN p_start AND :now AND p_end BETWEEN p_end AND :now");
$query->bindValue(':now', $now);
if($query->execute()) {
$data = $query->fetchAll(PDO::FETCH_ASSOC);
print_r($data); // checking that data is successfully being retrieved (only a troubleshooting method...you would remove this once you confirm it works)
} else {
// redirect as needed and print a user message
die("Something went wrong!");
}
$query->closeCursor();
}
?>
Another thing I want to mention is that make sure you follow due process with troubleshooting. If it's not working and I'm not getting any errors, I usually start at the querying level first. I check to make sure my query is executing properly. To do that, I go into my db and execute it manually. If that's working, then I want to check that I am actually receiving a value to the variable I'm declaring. As you can see, I check to make sure the $now variable is set. If it's not, that block of code won't even run. PHP can be rather tricky and finicky about this so make sure you check that. If you aren't sure what the variable is being set too, echo or print it with simply doing echo $now
If you have further questions please let me know. I hope this helps you!
I think I know what I was doing wrong, somebody with more PHP smarts than me will have to say for sure. In my above code I was using mysqli_stmt_store_result I believe that was clearing my variable before I intended. I changed that and reworked my query to be more simple.
<?php
include 'dbh.inc.php';
$datetoday = date("Ymd");
$sql = "SELECT p_num FROM periods WHERE p_start <= $datetoday order by p_num desc limit 1";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../quote.php?quotes=failed_to_write");
exit();
} else {
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while( $row = mysqli_fetch_assoc($result)) {
$pnum = $row['p_num'];
echo $pnum;
}
mysqli_stmt_close($stmt);
}
Thanks to #rhuntington and #nick for trying to help. Sorry I am such an idiot.

PHP Shows error when data inputted exist

I am currently learning PHP Programming,
I wanted to show error when the inputted data exists.
Can anyone show some example on how it doest work?
Here is code I used:
<?php
ob_start();
session_start();
require '../database/database.php';
// require '../database/inc_config2.php';
require ('p_nav.php');
if( !isset($_SESSION['user']) ) {
header("Location: index.php");
exit;
}
// select loggedin users detail
$res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
//Variable input data
//include_once 'dbconfig.php';
if(isset($_POST['btn-save']))
{
// variables for input data
$pcat = $_POST['pcat'];
if($pcat=='')
{
//javascript use for input checking
echo"<script>alert('Please enter Category')</script>";
// echo 'Empty Category';
header ("location:..\product\p_cat.php");
exit();
}
// variables for input data
//check if category is exist
//here query check weather if user already registered so can't register again.
$check_pcat_query="select * from pcategory WHERE pcat='$pcat'";
// $check_user_query="select * from users WHERE user_name='$user_name'";
$run_query=mysqli_query($dbcon,$check_pcat_query);
if(mysqli_num_rows($run_query)>0)
{
//echo "<script>alert('Category $pcat is already exist in our database, Please try another one!')</script>";
exit();
}
// sql query for inserting data into database
//temporary disabled
$sql_query = "INSERT INTO pcategory(pcat) VALUES('$pcat')";
mysql_query($sql_query);
//echo "Supplier Added Successfully";
//header ("location:..\product\index.php");
exit();
/*
$insert_user="insert into pcategory (pcat) VALUE ('$pcat')";
if(mysqli_query($dbcon,$insert_user))
{
// echo"<script>window.open('welcome.php','_self')</script>";
echo "Welcome";
} */
}
// sql query for inserting data into database
?>
There is an error, you are using both MySQL and MySQLi, using both is fatal error if you work on live server. Just focus on MySQLi as MySQL is deprecated officially and is not supported anymore.
Now come to your question. Your logic seems to be fine a bit. This is how you have to implement:
Fetch values from FORM
First clean the input using mysqli_real_escape_string() function.
Use above values and check the record existance in the database (here use SELECT statement)
If mysqli_num_rows() gives you result greater than 0 than;
(a) it means record already exists
(b) else, execute INSERT statement

PHP MYSQL Warning: mysql_query() expects parameter 1 to be string, resource given in

<?php
include 'connect.php';
include 'header.php';
$page = "signup.php";
// receive the invite code:
$code = $_POST['code'];
$sql = "SELECT codes FROM invites WHERE codes='$code'";
// check the table for matching codes
$result = mysql_query($sql);
// check if the request returned 1 or 0 rows from the database
if (mysql_query($result)) {
// end any previously defined sessions.
session_start();session_unset();session_destroy();
// start a new session
session_start();
// define the session variable.
// this allows us to check if it's set later and is required for
// the script to run properly.
$code = $_POST["code"];
mysql_query("DELETE FROM invites WHERE codes='$code'");
header('Location: '.$page);
exit;
} else {
echo "Invite invalid. Please try again later.";
echo $code;
}
include 'footer.php';
?>
I am trying to implement an invite system to a webpage I am working on. However when trying to evaluate if there is a row containing the invite code I keep either getting nothing or this warning. The warning in this case but if I change the if state to ==1, it allows everyone regardless of code and ==0 does throws different errors.
if (mysql_query($result)) {
Try mysql_num_rows there.
There are a few things wrong here.
1) SQL Injection vulnerabilities, don't ever pass a superglobal $_POST or $_GET or any other user-supplied variable directly inside your query!
Use at minimum mysql_real_escape_string() to the variable before letting it into the query, or better look into parametrized queries, it's the best way to avoid SQL vulnerabilities
2)
$result = mysql_query($sql);
// check if the request returned 1 or 0 rows from the database
if (mysql_query($result)) ....
This doesn't check if request returns 1 or 0 rows, you should use mysql_num_rows() here instead
if(mysql_num_rows() == 1) //or whatever you need to check
3)
session_start();session_unset();session_destroy();
// start a new session
session_start();
session_start() should be called before anything in your page. Don't know why this redundancy of calling, unsetting, destroying, recalling it here. If you want another id, just use session_regenerate_id();
And as already said by other, use some error reporting in your query, something like
$result = mysql_query($sql) or die(mysql_error())
to actually see what's failed, where and why.
Problem is your query. First of all check your statement and use this :
$result = mysql_query($sql) or die(mysql_error());
instead of this
$result = mysql_query($sql);
So, you can see are there any error at your SQL query .

how to get the session id

please help i have the following php code for my login session but i am trying to get the $_session['user_id'] instead of the $_session['email']. i tried print_f function to see what i can use but user_id array says 0 which cannot be right unless i read it wrong.
session_start();
$email = strip_tags($_POST['login']);
$pass = strip_tags($_POST['password']);
if ($email&&$password) {
$connect = mysql_connect("xammp","root"," ") or die (" ");
mysql_select_db("dbrun") or die ("db not found");
$query = mysql_query("SELECT email,pass FROM members WHERE login='$email'");
$numrows = mysql_num_rows($query);
if ($numrows!=0) {
// login code password check
while ($row = mysql_fetch_assoc($query)) {
$dbemail = $row['login'];
$dbpass = $row['password'];
}
// check to see if they match!
if ($login==$dbemail&&$password==$dbpass) {
echo "welcome <a href='member.php'>click to enter</a>";
$_SESSION['login']=$email;
} else {
echo (login_fail.php);
}
} else {
die ("user don't exist!");
}
//use if needed ==> echo $numrows;
} else {
die ("Please enter a valid login");
}
i am trying to get the $_session['user_id'] instead how can get this to use instead of $_session['email']. tried using $_session['user_id'] but instead i got undefined error msg.
Well, you don't define $_session['user_id'] anywhere in this script, so it's no surprise that it's not defined. You have to assign it a value before you can refer to it.
Also, note that there all kinds of security problems with this code.
You're running your MySQL connection as the root user. This is NOT a good idea.
You're trusting user input, which opens your script up to a SQL injection attack. Stripping HTML tags from the user input does not make it safe. Suppose that I came to your site, and filled in the "email" field with this:
bob#example.com'; GRANT ALL PRIVILEGES ON *.* TO 'evil_bob' IDENTIFIED BY '0wned_joo';
As currently written, your script would happily run its query as normal, and also create an account called "evil_bob" with full privileges to all the information in all of the databases on your server.
To avoid this, NEVER assume that user input is safe. Validate it. And to be extra sure, don't stick variables straight into SQL you've written. Use bound parameters instead. There are a few cases where it's hard to avoid -- for example, if you need to specify the name of a column rather than a piece of data, a bound parameter will not help and you'll have to do it some other way. However, for any piece of data you're using as part of a query, bind it.

Categories