php while loop error db - php

function DisplayPoints()
{
$con = mysql_connect("localhost", "grame2_admin", "password") ;
if (!$con) {
die("Can not connected: " . mysql_error());
}
mysql_select_db("grame2_webpage",$con);
$sql = "SELECT points FROM tablename WHERE username = $username";
$myData = mysql_query($sql,$con);
while($record = mysql_fetch_array($myData)){
It echo out info, that there is error in line 164, LINE ABOVE THIS.
echo $record['points'] ;
}
mysql_close($con);
}
the main idea is to echo out INT from specific user in webpage. Please help! :)

Change
$sql = "SELECT points FROM tablename WHERE username = $username";
to
$sql = "SELECT points FROM tablename WHERE username = '$username'";
^ ^
On a side note use prepared statements with either mysqli or PDO. mysql extension is deprecated and is no longer supported.
UPDATE The other problem is that your $username variable is not initialized. You probably need to pass it to your function as a parameter
function DisplayPoints($username)
{
...
}
And when you call your function pass a value
DisplayPoints('user1');
or
$username = $_POST['username'];
// here should go code to validate and sanitize $username
DisplayPoints($username);

Related

PHP / MySQL: Login form doesn't work

I've got a login.php file which looks like this:
include "myfuncs.php";
$connect = dbConnection();
$username = $_POST["username"];
$passwort = md5($_POST["password"]);
$query = "SELECT username, password FROM user WHERE username LIKE '$username' LIMIT 1";
$ergebnis = mysql_query($query);
$row = mysql_fetch_object($result);
if($row->password == $passwort)
{
echo "Hi $username";
$_SESSION["username"] = $username;
echo "Login successfully";
}
else
{
echo "Login doesn't work";
}
and a myfuncs.php file which looks like this:
function dbConnection()
{
$servername = "...";
$username = "...";
$password = "...";
$dbname = "...";
$db_connect = new mysqli($servername, $username, $password, $dbname);
if ($db_connect->connect_error)
{
die("Connection failed: " . $db_connect->connect_error);
}
return $db_connect;
}
Unfortunately the login form doesn't work - it always gives the error "Login doesn't work" even when the username and password matches with the database entry.
Arg, you are mixing a mysqli with class mysql functions. I dont think it works...
It works this way : PHP MySQLI
$stmt = $mysqli->prepare($query)
while ($stmt->fetch()) {
(...)
}
I see you have error in your variable name in line #6.
try this:
$query = "SELECT username, password FROM user WHERE username LIKE '$username' LIMIT 1";
$result= mysql_query($query);
$row = mysql_fetch_object($result);
There are several problems with your code. In myfuncs.php you use mysqli and after that, in your code you use mysql (without "i"). mysql (without "i") is deprecated, so you should use mysqli everywhere.
More than that, in your code you have:
$query = "SELECT username, password FROM user WHERE username LIKE '$username' LIMIT 1";
$ergebnis = mysql_query($query);
$row = mysql_fetch_object($result);
Please see the bold text from next two lines (it should be the same variable):
$ergebnis = mysql_query($query);
$row = mysql_fetch_object($result);
You should have
$result = mysql_query($query);
if you will use mysql.

PHP MySQL login setup error

This is all really new to me and I only know the very basics. I'm creating a frontend login for a webpage (obviously security isn't a huge deal or I wouldn't be doing it). I keep getting in issue with my "where" clause, stating that the "user" does not exist. Database is setup like this:
dbname=connectivity
table=users
users has id, user, and pass.
Anyone want to give me some pointers? Thanks in advance.
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'connectivity');
define('DB_USER','root');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Ya done goofed: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Ya done goofed: " . mysql_error());
function SignIn()
{
session_start();
if(!empty($_POST['user']))
{
$query = mysql_query("SELECT * FROM users where user = `$_POST[user]` AND pass = '$_POST[pass]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
if(!empty($row['user']) AND !empty($row['pass']))
{
$_SESSION['user'] = $row['pass'];
echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE...";
}
else
{
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
}
}
}
if(isset($_POST['submit']))
{
SignIn();
}
?>
Please stop using mysql_*. use mysqli_* or PDO. Have a look to the code:-
<?php
// Force PHP to show errors
error_reporting(E_ALL); // Get all type of errors if any occur in code
ini_set('display_errors',1); // Display those errors
session_start(); // start session
define('DB_HOST', 'localhost');
define('DB_NAME', 'connectivity');
define('DB_USER','root');
define('DB_PASSWORD','');
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME) or die("connection not established"); Or use $con = mysqli_connect('localhost','root','','connectivity') or die("connection not established");
if(isset($_POST['submit'])){
SignIn();
}
function SignIn(){
if(!empty($_POST['user'])) {
$username = mysqli_real_escape_string($con , $_POST['user']); // prevent form SQL injection
$password = mysqli_real_escape_string($con , $_POST['pass']); // prevent form SQL injection
$query = mysqli_query($con,"SELECT * FROM users where user = '".$username."' AND pass = '".$password."'") or die(mysqli_error($con));
if(mysqli_num_rows($query) > 0){ // check count of resultset
$_SESSION['user'] = $_POST['pass'];
echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE...";
}else{
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
}
}
}
?>
There are some issues here:
SELECT * FROM users where user = `$_POST[user]` AND pass = '$_POST[pass]'
The quote styles are all over the place. Try this:
SELECT * FROM `users` WHERE `user` = '$_POST[user]' AND `pass` = '$_POST[pass]'
Also, you should pre-process for SQL injection if you're not already.
This is the correct formatted SQL.
$query = mysql_query("SELECT * FROM `users` WHERE `user` = `'".$_POST["user"]."'` AND pass = '".$_POST["pass"]."'") or die(mysql_error());
One thing to note is that you MUST escape and validate all global variables. For more information I strongly recommend you to read this SO post: How can I prevent SQL injection in PHP?
There are multiple things wrong with your code check it down below:
<?php
session_start(); // This needs to be on top of every page
define('DB_HOST', 'localhost');
define('DB_NAME', 'connectivity');
define('DB_USER','root');
define('DB_PASSWORD','');
// Use mysqli_* as mysql_* is depracted and will be removed
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die("connection not established");
// Add a bit of security
$user = mysqli_real_escape_string($con, $_POST['user']);
$pass = mysqli_real_escape_string($con, $_POST['pass']);
function SignIn($user, $pass) {
// Add backticks ` around column and table names to prevent mysql reserved word error
$query = mysqli_query($con, "SELECT * FROM `users` WHERE `user` = '$user' AND `pass` = '$pass'");
// No need to fetch the data you already have
// Check if the query returns atleast 1 row (result)
if( mysqli_num_rows($query) >= 1 ) {
$_SESSION['user'] = $pass;
echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE...";
} else {
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
}
}
if(isset($_POST['submit']) && !empty($user) && !empty($pass) ) {
SignIn($user, $pass);
} else {
echo "SORRY... THERE ARE EMPTY FIELDS... PLEASE RETRY...";
}
?>
Just changed your code like follows:
SELECT * FROM users where user ='$_POST[user]'AND pass = '$_POST[pass]'
That line need to rewrite like follows:
SELECT * FROM users WHERE user = '".$_POST[user]."' AND pass = '".$_POST[pass]."'
I believe that should work in every server without any kind of trouble.
You are missing quotations
Corrected code:
$query = mysql_query("SELECT * FROM `users` WHERE `user` = `'".$_POST["user"]."'` AND pass = '".$_POST["pass"]."'") or die(mysql_error())

php mysql query with hyphen character

I have a query problem with hyphen character.
$user = "test-user";
$q = #mysql_query("SELECT id FROM table WHERE user='$user'");
echo mysql_error(); //no error message
test-user record is in table but query result coming empty. Also mysql error message is empty. What is wrong?
EDIT:
Thank you for answers. I apologize to everyone. I found the problem and I see now the problem is not in the query. Problem coming form regex.
if (preg_match("/^[a-z0-9]+$/i", $user)) //dash character not in regex
{
$q = #mysql_query("SELECT id FROM table WHERE user='$user'");
}
I've corrected the problem as follows:
if (preg_match("/^[a-z0-9\-]+$/i", $user)) //added \- to regex for dash
{
$q = #mysql_query("SELECT id FROM table WHERE user='$user'");
}
Just use mysql_real_escape_string to escape the data string.
$user = "test-user";
$user = mysql_real_escape_string($user);
$q = #mysql_query("SELECT id FROM table WHERE user='$user'");
echo mysql_error(); //no error message
But I would also recommend using or die() syntax instead of the #mysql_query you have in place.
$user = "test-user";
$user = mysql_real_escape_string($user);
$q = mysql_query("SELECT id FROM table WHERE user='$user'") or die ("Error: " . mysql_error());
$p = mysql_query("SELECT id FROM table WHERE user='$user'");
if (!$p)
{
die('Could not query:' . mysql_error());
}
else
{
echo mysql_result($p>0);
}
try it
Try this:
$user = "test-user";
$q = mysql_query("SELECT id FROM `table` WHERE user='".$user."'")
or die(mysql_error());//no error message;
Full example with mysqli_:
$host = "";
$user = "";
$password = "";
$database = "";
$user_name_query = "test-user"; // If this value is from a form please read more about sql-injection.
// open connection to database
$link = mysqli_connect($host, $user, $password, $database);
IF (!$link){
echo ("Unable to connect to database!");
}
ELSE {
// SELECT QUERY
$query = "SELECT id FROM `table` WHERE user='".$user_name_query."'";
mysqli_query($link,$query) or die("Query failed");
}
// close connection to database
mysqli_close($link);
Any difference if you change the query to:
$q = mysql_query("SELECT id FROM table WHERE user='".$user."'");
Unless I'm having a very slow Sunday I think you're searching for the literal string $user rather than the variable value.

Selecting certain row in mysql

I am completely new to MYSQL and PHP, so i just need to do something very basic.
I need to select a password from accounts where username = $_POST['username']... i couldn't figure this one out, i keep getting resource id(2) instead of the desired password for the entered account. I need to pass that mysql through a mysql query function and save the returned value in the variable $realpassword. Thanks!
EDIT:
this code returned Resource id (2) instead of the real password
CODE:
<?php
$con = mysql_connect('server', 'user', 'pass');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
echo '<br/> ';
// Create table
mysql_select_db("dbname", $con);
//Variables
//save the entered values
$enteredusername = $_POST['username'];
$hashedpassword = sha1($_POST['password']);
$sql = "SELECT password from accounts where username = '$enteredusername'";
$new = mysql_query($sql,$con);
echo "$new";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con);
?>
It will be a lot better if you use PDO together with prepared statements.
This is how you connect to a MySQL server:
$db = new PDO('mysql:host=example.com;port=3306;dbname=your_database', $mysql_user, $mysql_pass);
And this is how you select rows properly (using bindParam):
$stmt = $db->prepare('SELECT password FROM accounts WHERE username = ?;');
$stmt->bindParam(1, $enteredusername);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$password = $result['password'];
Also, binding parameters, instead of putting them immediately into query string, protects you from SQL injection (which in your case would be very likely as you do not filter input in any way).
I think your code looks something like this
$realpassword = mysql_query("SELECT password
from accounts where username = '$_POST[username]'");
echo $realpassword;
This will return a Resource which is used to point to the records in the database. What you then need to do is fetch the row where the resource is pointing. So, you do this (Note that I am going to use structural MySQLi instead of MySQL, because MySQL is deprecated now.)
$connection = mysqli_connect("localhost", "your_mysql_username",
"your_mysql_password", "your_mysql_database")
or die("There was an error");
foreach($_POST as $key=>$val) //this code will sanitize your inputs.
$_POST[$key] = mysqli_real_escape_string($connection, $val);
$result = mysqli_query($connection, "what_ever_my_query_is")
or die("There was an error");
//since you should only get one row here, I'm not going to loop over the result.
//However, if you are getting more than one rows, you might have to loop.
$dataRow = mysqli_fetch_array($result);
$realpassword = $dataRow['password'];
echo $realpassword;
So, this will take care of retrieving the password. But then you have more inherent problems. You are not sanitizing your inputs, and probably not even storing the hashed password in the database. If you are starting out in PHP and MySQL, you should really look into these things.
Edit : If you are only looking to create a login system, then you don't need to retrieve the password from the database. The query is pretty simple in that case.
$pass = sha1($_POST['Password']);
$selQ = "select * from accounts
where username = '$_POST[Username]'
and password = '$pass'";
$result = mysqli_query($connection, $selQ);
if(mysqli_num_rows($result) == 1) {
//log the user in
}
else {
//authentication failed
}
Logically speaking, the only way the user can log in is if the username and password both match. So, there will only be exactly 1 row for the username and password. That's exactly what we are checking here.
By seeing this question we can understand you are very very new to programming.So i requesting you to go thru this link http://php.net/manual/en/function.mysql-fetch-assoc.php
I am adding comment to each line below
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1"; // This is query
$result = mysql_query($sql); // This is how to execute query
if (!$result) { //if the query is not successfully executed
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) { // if the query is successfully executed, check how many rows it returned
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) { //fetch the data from table as rows
echo $row["userid"]; //echoing each column
echo $row["fullname"];
echo $row["userstatus"];
}
hope it helps
try this
<?php
$con = mysql_connect('server', 'user', 'pass');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
echo '<br/> ';
// Create table
mysql_select_db("dbname", $con);
//Variables
//save the entered values
$enteredusername = mysql_real_escape_string($_POST['username']);
$hashedpassword = sha1($_POST['password']);
$sql = "SELECT password from accounts where username = '$enteredusername'";
$new = mysql_query($sql,$con);
$row = mysql_fetch_array($new) ;
echo $row['password'];
if (!$new)
{
die('Error: ' . mysql_error());
}
mysql_close($con);
?>
<?php
$query = "SELECT password_field_name FROM UsersTableName WHERE username_field_name =".$_POST['username'];
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo $row['password_field_name'];
?>
$username = $_POST['username'];
$login_query = "SELECT password FROM users_info WHERE users_info.username ='$username'";
$password = mysql_result($result,0,'password');

undefined variable php updating mysql data [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 9 years ago.
This is the code for attempting to do a update on mysql data errors stating undefined variable
mysql_connect ("localhost", "root", "");
mysql_select_db("supplierdetails");
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
//Run a query
$result = mysql_query ("SELECT * FROM users WHERE id= '$id'");
while ($row = mysql_fetch_array($result))
{
$username=$row['username'];
$password=$row['password'];
}
$query = "UPDATE users SET username = '$username', password = '$password' WHERE id = '$id'";
$result = #mysql_query($query);
//Check whether the query was successful or not
if($result) {
header("message= Users Updated");
}else {
die("Query failed");
}
?>
You miss the $id value?
And can use echo to debug or check script result, not header
http://php.net/manual/en/function.header.php
Please be more specific with regards to which variable is undefined.
In the code you've posted $username and $password are only set if $result returns a result, if it doesn't then your while loop will not run and therefore $username and $password will never be set.
Also $id doesn't look as if that has been set either, unless this has been set outside of the code which you have included in your question.
Hope this helps :)
you used 2 connect no need to do while and you forgot $id
$con = mysql_connect("localhost", "root", "");
mysql_select_db("supplierdetails");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$id = $_POST['id'];
$username=$_POST['username'];
$password=$_POST['password'];
$query = "UPDATE users SET username = '".$username."', password = '".$password."' WHERE id = '".$id."'";
$result = mysql_query($query);
//Check whether the query was successful or not
if($result) {
echo "message= Users Updated";
}else {
die("Query failed");
}
?>

Categories