I have table user like:
user
=======
username
password
var
After login, I want to print variable var using username session like this, but have not had any success yet.
<?php
if(empty($_SESSION)){
header("Location: logout.php");
}
$username=$_SESSION['username'];
$link = mysql_connect("localhost", "root", "");
mysql_select_db("vhts", $link);
$var = mysql_query("SELECT var FROM user where username='$username'", $link);
echo $var;
?>
How can this be corrected?
mysql_query() returns a boolean or a resource. When the return value is a resource, the values can be fetched with a call to a function like mysql_fetch_assoc().
$result = mysql_query("SELECT var FROM user where username='$username'", $link);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$var = $row['var'];
echo $var;
?>
Important Note:
Warning
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_fetch_assoc()
PDOStatement::fetch(PDO::FETCH_ASSOC)
(Source: http://php.net/mysql_fetch_assoc)
So you should really consider using mysqli_query(), mysqli_fetch_array(), etc.
"SELECT var FROM user where username='$username'"
should work.., and the var would probably be in
$var['var']
and don't forget to add the fetch function
$var = mysql_fetch_assoc($var); // highly recommended to use mysqli / PDO
Related
if(isset($_POST['submit'])){
$uname=$_POST['username'];
$pwd=$_POST['password'];
$acc_type=$_POST['acc_type'];
$_SESSION['user_type']=$acc_type;
if($acc_type=='Teacher'){
$sql="select userid,password from teacherinfo where userid='$uname'";
}
else if($acc_type=='Student'){
$sql="select userid,password from studentinfo where userid='$uname'";
}
else if($acc_type=='Admin'){
$sql="select userid,password from admininfo where userid='$uname'";
}
$query = mysql_query($sql);
$count = mysql_num_rows($query);
if($count>0){
$row_data = mysql_fetch_row($query);
if($row_data[1]==$pwd){
$_SESSION['userid']=$row_data[0];
$url="profile.php";
header("Location:$url");
}
else{
echo "Password Miss match!";
}
}
else{
echo "User not Found!";
}
}
Notice: Undefined variable: sql in C:\xampp\htdocs\MJ\index.php on line 39 Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\MJ\index.php on line 40
Looking at the code from the PHP website you are not linking your sql statement to the connection you made to your database. Look at the code below and you will see that a variable is create called $link this is then supplied the database to be used and then placed in as a second variable in the sql statement variable $result.
<?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";
?>
You really do, as the comment state, need to stop using mysql and move over to PDO, this site should provide you with enough information to get your started and will secure the statements to the database - https://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
Further to this you also need to look at hashing your passwords, currently you are using plain text, this is not secure. Using something like password_hash() - http://php.net/manual/en/function.password-hash.php - would provide a much more secure way of storing passwords. Once they are stored securing you can use password_verify() to check them against supplied passwords in the future.
I have a problem while passing information with $_SESSION in php. Every time that I try it, it sends me a message saying "Array to string conversion".Here is the code:
<?php
session_start();
ob_start();
include("conexion3.php");
$con = mysql_connect($host,$user,$pw) or die("Error");
mysql_select_db($db,$con) or die("Error DB");
$sel2 = mysql_query("SELECT usuario_n,correo FROM usuarios WHERE usuario_n='machan'",$con);
$sesion = mysql_fetch_array($sel2);
$_SESSION['resultado'] = $sesion;
echo $_SESSION['resultado'];
?>
The answer lies in your last comment. The problem is, $_SESSION['resultado'] is an array and with echo $_SESSION['resultado']; you're trying to convert array to string, hence the message.
You can do something like this to get the values:
echo $_SESSION['resultado'][0]; // machan
echo $_SESSION['resultado']['usuario_n']; // machan
echo $_SESSION['resultado'][1]; // elver#gmail.com
echo $_SESSION['resultado']['correo']; // elver#gmail.com
Sidenote: Please don't use the mysql_ database extensions, they were deprecated in PHP 5.5.0 and were removed in PHP 7.0.0. Use mysqli or PDO extensions instead. And this is why you shouldn't use mysql_ functions.
You're trying to echo out an array. $session stores the array you fetched from your mysql db. Try the following instead of that echo statement:
print_r($_SESSION['resultado']);
http://php.net/manual/en/function.print-r.php
So I use to program in PHP my own way and then someone told me to start using his way.
This of course caused me to do a few mistakes.
So this is the code:
<?php
function SignIn()
{
$con = mysqli_connect('localhost','root','avi1574','test');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
session_start();
if(!empty($_POST['user_w']))
{
$query = mysql_query($con, "SELECT * FROM `Users` where `User` = '$_POST[user_w]' AND Password = '$_POST[pass_w]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
if(!empty($row['User']) AND !empty($row['Password'])){
$_SESSION['user_w'] = $row['Password'];
echo "Logged in.";
}
else{
echo "Sorry, wrong password."; } }}
if(isset($_POST['submit'])){
SignIn();
}
?>
<h1>My login page</h1>
<form action="tsql.php" method="POST" >
<input type="text" name="user_w" size="20"></input>
<input type="password" name="pass_w" size="20"></input>
<button type="submit" name="submit">Sumbit</button>
</form>
When I submit the form I get the following error:
Warning: mysql_query() expects parameter 1 to be string, object given in test-main/htdocs/test/tsql.php on line 10
Line 10 is: $query = mysql_query($con, "SELECT * FROMUserswhereUser= '$_POST[user_w]' AND Password = '$_POST[pass_w]'") or die(mysql_error());
Thank you in advance!
Many bad practice in there, let me point out a few things.
$_POST[pass_w]
This doesn't work as pass_w is not a constant. See this article. You must use quotes for the index: $_POST['pass_w'].
You are open to SQL injection and you should use prepared statements.
You also can't mix mysqli and mysql. Don't use mysql_ functions, they are not as secure and deprecated.
To your error message, you are simply trying to put a resource into mysql_query where function expects the query as a string, like SELECT.... You must switch the parameters.
When doing selects for password and username, ensure case sensitivity by using BINARY
and put LIMIT 1 at the end, to ensure only 1 record in return.
SELECT * FROM ... WHERE BINARY username = ... LIMIT 1
Also use some hashing function (not sha1 and not md5 please :-) for the password, with salt!
You should change the function you're using from mysql_query($con, "SELECT * FROMUserswhereUser= '$_POST[user_w]' AND Password = '$_POST[pass_w]'") to mysqli_query($con, "SELECT * FROMUserswhereUser= '$_POST[user_w]' AND Password = '$_POST[pass_w]'")
(mysqli_query instead of mysql_query).
While you're at it, you should also probably change mysql_fetch_array() to mysqli_fetch_assoc(), for two reasons:
you should use mysql and not mysqli since its deprecated
you're accessing $row's associative array keys, so you need the function to return associative array whild mysqli_fetch_array() returns numeric keys.
Many bugs
User = '$_POST[user_w]' should be User = ".$_POST['user_w']."
Here is some links which may be helpful
about mysql functions: http://php.net/manual/en/book.mysql.php
about mysqli functions: http://php.net/manual/en/book.mysqli.php
Mysql functions is the original function while Mysqli is the extension of Mysql functions
$query = mysql_query($con, "SELECT * FROM `Users` where User = '".$_POST['user_w']."' AND Password = '".$_POST['pass_w']."'");
but read the solution from DanFromGermany, because I gonna point out the same mistake, but as he already mention so no point,
Thanks
I ran this code and I got a Resource id #3 error where it should have showed the full movies table.
mysql_connect("localhost", "root", "password") or die(mysql_error());
mysql_select_db("treehouse_movie_db") or die(mysql_error());
$data = mysql_query("SELECT * FROM movies")
or die(mysql_error());
echo $data;
This is not an error Your query is getting executed and you are getting appropriate resource from mysql_query() as it should be returned.
To get the response you have to use mysql_fetch_array() or mysql_fetch_assoc()
mysql_connect("localhost", "root", "password") or die(mysql_error());
mysql_select_db("treehouse_movie_db") or die(mysql_error());
$data = mysql_query("SELECT * FROM movies")
or die(mysql_error());
while($row = mysql_fetch_assoc($data))
{
print_r($row);
}
SUGGESTION: mysql_* are no longer maintained .Try switching to mysqli_* or PDO
You're not getting an error, the MySQL API is just doing what you're asking it to: echoing the contents of $data, which is a MySQL query resource at this point. Extend the code to actually retrieve the results:
while($row = mysql_fetch_object($data))
var_dump($row);
And you'll see the output.
Note that the mysql_* API is deprecated since PHP 5.5 by the way.
Resourse id #3 means that the $data variable was used to open a resourse, it is not an error.
If you were to open another resourse, like a file, using:
$var=fopen('myfile','a+');
echo $var;
You would get Resourse id $4 as a result.
So to get the output you desire, you need to use a loop.
It is described in here.
I have a project (exisiting) and I am ordered to continue it
but there's something strange
in my connection
<?php
include "adodb5/adodb.inc.php";
$config['mysqlhost'] = 'localhost';
$config['mysqluser'] = 'xxx';
$config['mysqlpass'] = 'yyy';
$config['mysqldb'] = 'zzz';
$DB = ADONewConnection('mysql');
$DB->Connect($config['mysqlhost'],$config['mysqluser'],$config['mysqlpass'],$config['mysqldb'],true);
?>
and if I try to call query (same queries as below) from this page, it works (and when I echo, it shows the value)
So I go to other page
<?
include ("inc/con.php");
?>
<?php
$sql = ("SELECT * FROM table");
$query = mysql_query($sql)or die($myQuery."<br/><br/>".mysql_error());
$result = mysql_fetch_array($query);
echo $result ['table id'];
?>
and the result is
Notice: Undefined variable: myQuery in C:\xampp\htdocs\d88\www\mypage.php on line 9
No database selected
is there anything wrong with it?
since i try on con page, it works and when i include it to other page, it not working
You are not defining any $myQuery either in inc/con.php nor in the same file itself. Also you are not selecting any database with mysql_select_db:
mysql_select_db($config['mysqldb']);
You are suggest, also, not to use mysql_* functions as they are going to be deleted and are yet deprecated (and you can use PDO or mysqli).
Notice: I think $sql = ("SELECT * FROM table") gets evaluated as $sql = true.
You can not connect with ADODB connection and establish a query with mysql_query.
the syntax is something like this mysql_query ($query ,$con). $con is optional but if you do not specify it, the last link opened by mysql_connect() is assumed; but you have not any mysql_connect() statement before
because of my version of php, i must use <?php ?> instead of <? ?>
thanks for helping