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

(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.

Related

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.

The mysql_num_rows function returns 0 on an older version of phpmyadmin

I am a beginning php-programmer and have tried to create a registration/login system with a database. The system works at home on the latest version of phpmyadmin but my school hasn't updated it to the latest version yet (don't worry, this isn't homework). The problem I have is that at school mysql_num_rows returns 0 when I try to login but returns 1 when I try to login at home. My teacher said the version of phpmyadmin might be causing this problem. Version at school is: 4.5.2.
Here's my login.php file:
<?php
include('connect.php');
session_start();
$error = "";
$emailaddress = $_POST["emailaddress"];
$password = $_POST["password"];
if(empty($emailaddress) || empty($password)){
$error = "Email or password is invalid!";
echo $error;
}
else{
$queryforlogin = mysql_query("SELECT * FROM users WHERE emailaddress='$emailaddress' AND password='$password'");
$rows = mysql_num_rows($queryforlogin);
if($rows==1){
$_SESSION['login_user'] = mysql_query("SELECT firstname FROM users WHERE emailaddress='$emailaddress'");
$username = mysql_fetch_array($_SESSION['login_user']);
echo "Welcome, " . $username['firstname'] . "!";
}
else{
$error = "Email or password not found!";
echo $error;
}
mysql_close($connect);
}
?>
If I click the login button on the webpage, it gives me the error: Email or password not found! (the last else-statement). It executes the code in the file but does not execute the code under if($rows==1).
Is there anything I can do to still get this code to work?
Again, this code does work at home but not at school on an older version. I asked my teacher if he could update phpmyadmin but other classes are working with phpmyadmin right now so that cannot be done.
I hope you understand my question.
Sorry for my english, it's not my native language.
You just try once like this by passing mysql_connect connection variable in mysql_query so you can get the rows
<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
?>
Lets get something right of the bat, PHPmyadmin has nothing to do with mysql_num_rows returning whatever it returns, PHPmyadmin is merely a tool to manage the database to which the server is linked to, everything happens on your server side.
I think you don't have the same username and password in your table at your school's database and hence the mysql_num_rows() returns 0, which is what it is supposed to do when the query does not yield any results,
OR it could be that your query returns more than 1 result, in that case the condition would fail again($rows==1).

mysql Duplicate error handling

I'm trying to use PHP to enter data from a form. When I try to enter duplicate data a bad message pops like
Something went wrong with this:
INSERT INTO customer VALUES('jamie9422','Jamie Lannister','sept of baelor','jamie#cersei.com',9422222222,0) Duplicate entry 'jamie9422' for key 'PRIMARY' "
Instead, I want to display a clean error message. How can I do that. Here's my code I've written so far...
<?php
include_once "dbConnect.php";
$connection=connectDB();
if(!$connection)
{
die("Couldn't connect to the database");
}
$tempEmail = strpos("{$_POST["email"]}","#");
$customer_id=substr("{$_POST["email"]}",0,$tempEmail).substr("{$_POST["phone"]}",0,4);
//$result=mysqli_query($connection,"select customer_id from customer where customer_id='$customer_id' ");
//echo "customer_id is".$result;
$query = "SELECT * FROM CUSTOMER WHERE CUSTOMER_ID='$customer_id'";
$customer_idcip = $customer_id-1;
echo $customer_idcip;
if ( mysql_query($query)) {
echo "It seems that user is already registered";
} else {
$command = "INSERT INTO customer VALUES('{$customer_id}','{$_POST["name"]}','{$_POST["address"]}','{$_POST["email"]}',{$_POST["phone"]},0)";
$res =$connection->query($command);
if(!$res){
die("<br>Something went wrong with this:{$command}\n{$connection->error}");
}
echo "Welcome ".$_POST["name"]." \nCongratulations on successful Registration. Refill your Wallet here";
//$cutomerRetrival = mysql_query("select from customer where customer_id='$customer_id'");
echo "<br>Please note your customer ID :".$customer_id;
}
/*if($result)
{
echo "Query Fired";
$dupentry = mysqli_num_rows($result);
if($dupentry==1)
{
echo "You are already Registered";
exit;
}
}*/
?>
The error code (number) is 1022.
You can e.g. define a constant for that (so that somebody else in x months has a chance to understand the code) like
define('ER_DUP_KEY', 1022);
and then do something like
if(!$res){
if ( <error code>==ER_DUP_KEY ) {
handleDuplicateEntryError();
}
else {
die("<br>Something went wrong with this:{$command}\n{$connection->error}");
}
}
since I don't know how $res =$connection->query($command); works (and what $connection is I can't tell you exactly how to implement <error code>==ER_DUP_KEY, could be by using mysql_errno.
But it seems to be somehow intermingled with mysql_query($query), i.e. the old, deprecated mysql_* extension and some custom class. You might want to fix that first.... ;-)
see http://docs.php.net/manual/en/mysqlinfo.api.choosing.php
Your code doesn't check for existing record properly
Change
if (mysql_query($query)) {
echo "It seems that user is already registered";
}
to
$result = mysql_query($query);
if (mysql_num_rows($result)) {
echo "It seems that user is already registered";
}
Also, PLEASE do not use $_POST variables without escaping them first, use something like mysql_real_escape_string() to escape each variable passed from the user, otherwise your website will be hacked really fast with SQL Injection.
Make some update into your and then try to get error message 'customer already registered.'
$query = "SELECT * FROM CUSTOMER WHERE CUSTOMER_ID='$customer_id'";
$res= mysql_query($query);
$customer_count = mysql_num_rows($res);
$customer_idcip = $customer_id-1;
echo $customer_idcip;
if ( $customer_count > 0 ) {
echo "It seems that user is already registered";
} else {
...................................
Thank you all.
Actually I was using mysqli API in my connectDB.php file..
Hence I needed to call functions on mysqli.
Instead I was calling mysql. i.e I was creating a new connection, thus the query wasn't getting fired at all.
Changed to mysqli->query($result) that is object oriented style
and it worked fine....
Use Try Catch instead.
try{
$res =$connection->query($command);
}catch(Exception $e){
die( "Write your error appropriate message here");
}

PHP code allows logging in without correct password

I'm writing a PHP code for my website. Currently, there's some problems with my code.
Here's my code. Ignore some Malay language used, I'd tried to translate most of them.
<?php
session_start();
include "../library/inc.connectiondb.php";
$txtUser = $_POST['txtUser'];
$txtPass = $_POST['txtPass'];
if(trim($txtUser) == "") {
echo "<b>User ID</b> is empty, please fill";
include "login.php";
}
else if(strlen(trim($txtPass)) <= 5) {
echo "<b>Password</b> is less then 6 characters, please fix";
include "login.php";
}
else {
$sqlPeriksa = "SELECT userID FROM admin WHERE userID='$txtUser'";
$qryPeriksa = mysql_query($sqlPeriksa, $sambung);
$hslPeriksa = mysql_num_rows($qryPeriksa);
if($hslPeriksa == 0) {
# If username doesn't exist
echo "<b>UserID</b> doesn't exist";
include "login.php";
}
else {
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPeriksa, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
if($hslPassword < 1) {
# If password is incorrect
echo "<b>Password</b> is incorrect";
include "login.php";
}
else {
# If login successful
$SES_Admin = $txtUser;
session_register('SES_Admin');
echo "LOGIN SUCCESSFUL";
# Redirect to index.php
echo "<meta http-equiv='refresh' content='0; url=index.php'>";
exit;
}
}
}
?>
The problem is this code allows me to login even if the password is wrong. I'd done some searches and it still doesn't solve my problem. I'm pretty sure that the problem is at line 27 onwards.
So, if anyone has a solution, please tell me quickly. I'm writing this code for my school, and it had to be finished before next year.
Edit
Ok, I'd already placed the mysql_real_escape_string in the code just like what many people told me. I don't know how this will help, but the mysql table for this was named "admin". It had 2 fields; userID and passID. To test the code, I'd inserted the value "admin" and "12345678" into the table.
This is where your problem is:
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPeriksa, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
You see, your mysql_query is executing $sqlPeriksa which is:
$sqlPeriksa = "SELECT userID FROM admin WHERE userID='$txtUser'";
Instead, your code should be like this:
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPassword, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
Please try this out and let us know what happens.
[edit/additional] : I strongly suggest that you look into the following:
Using PDO:
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
Using stored procedures:
http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html
Using PDO + stored procedures:
http://php.net/manual/en/pdo.prepared-statements.php (See example #4)
just plain troubleshoot is necessary. how many rows are returned? what are the values of userID and passID in the query that returns rows? put some breaks in and see what's going on. i don't see a problem, it but its hard to troubleshoot code posted here since it really can't be run without a db.
I don't see any reason this isn't working as you expected, I suspect the problem might be elsewhere. For example, I don't see you checking if a "SES_Admin" session is already registered. But at the very least you need to replace lines 5 and 6 with this, otherwise someone could potentially delete your entire user table, and do various other malicious things with your MySQL databases.
$txtUser = mysql_real_escape_string($_POST['txtUser']);
$txtPass = mysql_real_escape_string($_POST['txtPass']);
Please read the article on mysql_real_escape_string at http://php.net/manual/en/function.mysql-real-escape-string.php

Posting data from Database

I am validating a form (checking if field are empty etc and at the end I am using my last validation rule:
//Database Information
//Connect to database
mysql_connect($dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname)or die(mysql_error());
$email = mysql_real_escape_string($_POST['email']);
$cust_code = mysql_real_escape_string($_POST['cust_code']);
//validation e.g.
if (empty($email) + empty($cust_code) > 1){
....
//if everything is ok
$sql = "SELECT * FROM clients WHERE ID='$cust_code'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0){
$data = mysql_num_rows($result);
//get all fields from db and do something
}else{
//My error that is showing up
echo "<span class=\"difftext\">The customer code you have entered is not valid!
<br />
Please enter a valid Customer Code to procceed!
</span>";
Is anything wrong with that because even if I enter the correct cust_code I am getting my error msg instead of my data...
Thank you
EDIT...(I removed, as it is wrong) AND YOU DID WELL... I JUST REALISE WHAT I DID... SORRY...
I have corrected it above.
Thank you
HOW TO DEBUG
Do not put the query string immediately into the mysql method, echo it first
$sql = "SELECT * FROM clients WHERE ID='$cust_code'";
echo $sql;
$res=mysql_query($sql);
Are you even connected to the DB?
Error messages are written in English (if it is not MS error messages). Why would you ignore them? Put the error message, read it, try to understand what it says.
An advice, if you will write code that way, it is ok for very small application, for big ones, you need to take a different approach completely to code organization. Which is one of the problems/main problem frameworks are trying to solve for you.
Actually, you are wrong, your error is here, in this two lines:
$sql = mysql_query("SELECT * FROM clients WHERE ID='$cust_code'");
$result = mysql_query($sql);
You are running the query twice.
After the first time $sql holds the resource, then you refer to the resource as if it was a query string. To fix it, change it to:
$sql = "SELECT * FROM clients WHERE ID='$cust_code'";
$result = mysql_query($sql);
You might have more underlying errors, but fix this one first.

Categories