PHP SQL query doesnt return a result - php

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.

Related

tracking multiple users in CMS with $_SESSION

Hello I am trying to make multiple users in a CMS I made. I have all their data in a table and was using mysql_num_rows check if the records matched and then use session_register() to set a session. I have changed this to PDO commands.
I want to be able to track the user when they are using the CMS so that every record changed can have their usrID attached to it. So that at a later date I can see who made updates and eventually use this to show information about the author etc.
So for example when they use forms to update or add a new record a hidden input with have their session id echo'd into it which will be taken from their user record as they log in.
Is the best way to do this? Have a written the syntax in this login code correctly?
$con = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
$sql="SELECT * FROM $tbl_name WHERE the_username='$the_username' and the_password='$the_password'";
$result = $con->prepare($sql);
$result->execute();
$number_of_rows = $result->fetchColumn();
if($number_of_rows==1){
$info = $result->fetch(PDO::FETCH_ASSOC);
$_SESSION['username'] = $info['the_username'];
$_SESSION['id'] = $info['id'];
header('Location: admin.php');
}else{
echo "Wrong username or password, please refresh and try again.";
}
Would it perhaps be better to put?
if($number_of_rows==1 && $info = $result->fetch(PDO::FETCH_ASSOC)){MAKE SESSION}
Your usage of PDO functions is quite inconsistent, and it leads to some errors.
First of all, you cannot fetch the same data twice. And, as a matter of fact, you don't need such a double fetch at all.
Also, for some reason you are not using prepared statements which are the only reason for using PDO. So, the proper code would be
$sql="SELECT * FROM $tbl_name WHERE the_username=? and the_password=?";
$result = $con->prepare($sql);
$result->execute(array($the_username,$the_password));
# $number_of_rows = $result->fetchColumn(); <- don't need that
$info = $result->fetch();
if($info){
$_SESSION['username'] = $info['the_username'];
$_SESSION['id'] = $info['id'];
header('Location: admin.php');
}else{
echo "Wrong username or password, please refresh and try again.";
}
Yes the code and logic works fine. But don't use session_register() they are deprecated in new version of PHP.

mySQLi_affected_rows check not working, or is it...?

(Sorry, I don't really know what I am doing.)
I have this Unity game in an iframe on Facebook calling a php file in the same directory, and that much is working. What I want it to do is update the player record if it is there and make one if it isn't.
This script runs but it always returns a "not here" and when I check the database, it is in fact creating the records each time, identical but for the datetime field. So I don't understand why affected_rows is never coming back as "1".
<?php
$db = #new mysqli('••.•••.•••.••', '•••••••••••', '••••••••','•••••••••••');
if ($db->connect_errno)
{
echo("Connect failed "+mysqli_connect_error());
exit();
}
$inIP = $_POST["ip"];
$playerIP = mysqli_real_escape_string($db, $inIP);
$inUN = $_POST["un"];
$playerUN = mysqli_real_escape_string($db, $inUN);
$query = "UPDATE lobby SET whens=NOW(), wherefores='$playerIP', whys=0 WHERE whos='$playerUN'";
mysqli_query($db, $query);
if (mysqli_affected_rows($db) > 0)
{
echo "here";
}
else
{
$query2 = "INSERT INTO lobby (whens,whos,wherefores,whys) values (NOW(),'$playerUN','$playerIP',0)";
mysqli_query($db, $query2);
echo "not here";
}
if ($db)
{
$db->close();
}
?>
You have a typo:
wherefores=$playerip
it should be
wherefores=$playerIP
because of that
mysqli_affected_rows($db)
returns
-1
Sounds like you're experiencing the same problem as me, especially if you are running your code through a debugger. I've investigated the issue with Netbeans and Xdebug and it seems this is a bug in the MySQLi extension itself. An according bug report has been made. In the meantime you can instead use another expression, e.g.:
if (mysqli_sqlstate($dbc) == 00000) {
//your code
}
to continue debugging your remaining code.

php mysqli FRUSTRATION

I have to following code:
session_start();
if(isset($_SESSION['Username']))
{
//User has selected auto sign-in re-fill session variables.
$mysqli = new mysqli('****','****','****','****');
if($mysqli->errno)
{
//Error connecting
}
else
{
//No error connecting to database
$stmt = $mysqli->prepare("SELECT Expires FROM Subscribers WHERE UName=?");
$stmt->bind_param('s', $_SESSION['Username']);
$stmt->execute();
$stmt->bind_result($Expires);
$stmt->store_result();
while($row = $stmt->fetch())
{
if($Expires < time())
{
//Deny user
$pageToShow = "Payment";
}
else
{
//Accept
$pageToShow = "Content";
}
}
}
}
else
{ ... }
I am getting the error Fatal error: Call to a member function bind_param() on a non-object in /home/content/42/7401242/html/****/wp-content/themes/****/archive.php on line 15
I just had an error like this about 30min ago on a different page, and I had for gotten the FROM from the sql query, but I have read, re-read, re-checked, every single letter of the code, over and over. I am about to pull all of my hair out...
What am I doing wrong?
That's simple.
You're not handling errors.
And not even asking how to do that.
In your other question they showed you error itself instead of showing you the way how can you see the error yourself.
In the present question the answer is "check your query" which is not too helpful too.
Instead of asking other people to find typos in your queries, you have to ask mysqli to do that. That's way more efficient, especially because there could be another mistake, not in the query but somewhere else.
So, you have to check every database interaction result and translate it into PHP error.
$sql = "SELECT Expires FROM Subscribers WHERE UName=?";
$stmt = $mysqli->prepare($sql) or trigger_error($mysqli->error);
...
$stmt->execute() or trigger_error($mysqli->error);
so, you will immediately know what's going wrong.
The error tells you that your SQL query is returning an empty result.
two things you must do:
check that you are connected to the database properly and that you
have the permissions to access the data in the database
check your query and see if it returns any results in your SQL
database.

If Else to look into SQL permissions

So I'm trying to write a temp way to login to the admin panel using an if else statement while I read up on PDO. If someone could tell me where the error lies here it would be much appreciated.
I've updated my code after looking around a little bit, but I still have the issue of nothing showing up where my code belongs and pulling the information it should.
<?php
$admin = $_SESSION['admin_login'];
$con=mysql_connect("$server","$user","$pass");
if
(!$con)
{
die('Could not Connect' .mysql_error());
}
mysql_select_db($webdb, $con);
$result=mysql_query("SELECT * FROM permissions WHERE username= '$admin' ");
$row = mysql_fetch_assoc($result);
if ($row['permissions']=="3")
{
echo 'Admin Panel';
}
elseif ($row['permissions']=="1")
{
echo 'include acp_error.php';
}
?>
Is what I've updated to; Does anyone see any issue here?
mysql_query returns a statement HANDLE, not the value(s)/row(s) you're trying to select. YOu need to FETCH a row of data to be able to get the values you need to compare.
$result = mysql_query(...) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if ($row['somefield'] == 3) {
...
}
Please note that things like
"$webdb"
are pointless cargo-cult programming. A simple
$webdb
is all that's needed for such things. There is not point in creating a new string, whose sole contents are the contents of a variable - just use the variable itself.
As well, note that you're vulnerable to SQL injection via that $_SESSION value you're using in the query. If that's a text value, and contains user-supplied data, your server is trivial to pwn.

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 .

Categories