PhP session passing and combine variable and string - php

My login code:
<?php
session_start();
$f_usr= $_POST["userid"];
$f_pswd= $_POST["password"];
$_SESSION['user']=$f_usr;
$con=mysql_connect("localhost","root","");
if(! $con)
{
die('Connection Failed'.mysql_error());
}
mysql_select_db("finaltest",$con);
$result=mysql_query("select * from user");
while($row=mysql_fetch_array($result))
{
if($row["username"]==$f_usr && $row["password"]==$f_pswd)
header('Location: selectdata.php');
else
echo"Sorry : $f_usr";
}
?>
selectdata.php
<?php
session_start();
$s= $_SESSION['user'];
// Make a MySQL Connection
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("finaltest") or die(mysql_error());
$select="temperature".$s;
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM $select")
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>username</th> <th>password</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['username'];
echo "</td><td>";
echo $row['password'];
echo "</td></tr>";
}
echo "</table>";
?>
actually the session varibale is not getting parsed i am getting an error:
Notice: Undefined index: user in C:\xampp\htdocs\bars\selectdata.php on line 3
and i have an other problem i want to select a database named "temperaturexyz" where temperature i want to store in a string and xyz is variable that i am getting via the session i want to combine the both so that i can get a variable which i can use in the query

Regarding your session: It appears your session variable $_SESSION['user'] which you attempt to set in your login code is not correctly setting the variable as expected.
try:
<?php
session_start();
$f_usr= $_POST["userid"];
$f_pswd= $_POST["password"];
$_SESSION['user']=$f_usr;
echo $_SESSION['user'] //<-------- see if this echo's out the value you are expecting
As for your variable:
I assume you mean you want a variable name $temperaturexyz but you are creating the variable name dynamically. so
$select="temperature".$s;
$$select = /* Insert whatever value you need here*/ //<-- you can then call this variable like this (ie. $temperaturexyz)

Related

How to store value of an element in a session on click

I want to store value of <td> into a session which is clicked by user.
Is it possible?
Here is my code:
$sql = "SELECT * FROM users";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
$username = $row['user_name'];
$id = $row['id'];
echo "<table border='1'><tr><th>Id</th><th>UserName</th></tr><tr><th>$id</th><th>$username</th></tr>";
}
session_start();
$_SESSION['username'] = $username;
This is not possible with the approach you are using because you are fetching data using while loop and it will only load last username in $_SESSION
You can do it with arrays but how you will figure out which user has which session then and as you mentioned in comment What i actually want is to get td value on another page which is clicked by users so why using $_SESSION, you can pass what ever value to another page via link href
Change your approach to this
<?php
$sql = "SELECT * FROM users";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
$username = $row['user_name'];
$id = $row['id'];
?>
<table border='1'>
<tr>
<th>Id</th>
<th>UserName</th>
<th>Action</th>
</tr>
<tr>
<td><?php echo $id;?></td>
<td><?php echo $username;?></td>
<td>Go To Page With UserName</td>
</tr>
<?php } ?>
So here $username value passing to another page via link (or pass any other variable value you like to pass)
<td>Go To Page With UserName</td>
And on next page pagelink.php fetch username with $_GET from link
<?php
$username = $_GET["username"];
echo $username;
//Do what ever next you wana do
?>
OR if you want to load a session, do it like this
<?php session_start();
$username = $_GET["username"];
$_SESSION['username'] = $username;
echo $_SESSION['username'];
//Do what ever next you wana do
?>
Note: mysql library is deprecated, you should start using mysqli

Using PHP to submit a Vector onto MySQL to make a connection with 2 tables

i have a list of emails on a database, which are brought onto the screen, this is coming from a previous page where you choose the category to add emails into.
The idea is for the user to check in the emails he wants to add to a connecting table that will join those two.
But i seem to be having problems. I have tried editing the page where i think the problem is, which is the , but no clue as to how i should edit it.
<?php
mysql_connect("localhost","root","") or die("problema na conexao");
mysql_select_db("trabalho1");
$idcategoria = $_GET["id"];
$query = "SELECT nome,email,id FROM email";
$results = mysql_query($query) or die(mysql_error());
echo"<center>";
echo "<table border='2'>\n";
echo"<form id='formulario' name='formulario' method='post' onsubmit='return validar(this);' action='../inserir/inserirmailcat.php'>";
echo "<br>";
echo "<button type='submit'>Submeter</button>";
echo "<tr align='center'><td>Nome</td><td>Email</td><td>Adicionar a Categoria</td></tr>";
while ($row = mysql_fetch_assoc($results)) {
foreach ($row as $campo=>$valor) {
if($campo=="nome")
{
echo "<td><b></b>".$valor. "\n</td>";
}
if($campo=="email")
{
echo "<td><b></b>".$valor. "\n</td>";
}
if($campo=="id")
{
echo "<td><input name='nome[".$valor."]' type='checkbox' value='Adicionar'></td></tr>";
}
}
echo "<input type='hidden' name='categoria' value='".$idcategoria."'>";
echo "</form>\n";
}
echo "</table>\n";
echo"</center>";
?>
This first page receives the ID from the previous one, and it lists a series of emails, where i check out the ones i want to add to a new table. And i try to pass them through a vector.
<?php
mysql_connect("localhost","root","") or die("problema na conexao");
mysql_select_db("trabalho1");
$queryq = "SELECT id FROM email";
$resultsq = mysql_query($queryq) or die(mysql_error());
while ($rowq = mysql_fetch_assoc($resultsq)) {
foreach ($rowq as $campoq=>$valorq) {
$cat = $_POST["categoria"];
$username = $_POST['nome['.$valorq.']'];
if ($username != '')
{
$query = "INSERT INTO emailcategoria (email,categoria) VALUES ('".$username.",".$cat."')";
mysql_query($query) or die(mysql_error());
}
}
}
mysql_query($queryq) or die(mysql_error());
header("Location:../listar/listarcategoria.php");
?>
On this second page i try to add only the emails which have been selected onto a new table which will receive the email's ID and the category's ID, but it is giving me the following error "after a few different error's when i tried a diferent approach":
Notice: Undefined index: nome[8445] in C:\xampp\phpMyAdmin\trabalho\inserir\inserirmailcat.php on line 10
The error is given for all the email ID's.
UPDATED
Error is on this like
$username = $_POST['nome['".$valorq."']'];
Firstly, is it supposed to be 'nome' ?
Secondly change the syntax like this
$username = $_POST['nome['.$valorq.']'];
$username = $_POST['nome['".$valorq."']'];
Well that's wrong, as the syntax highlighting shows.
$username = $_POST['nome['.$valorq.']'];
Also, sanitise your input or (better) use prepared statements!
> xkcd

how can i display sql query in php? CLOSED

<?php
include 'config.php'; //connect to db
if(isset($_REQUEST["pwd"]) && isset($_REQUEST["name"])) {
$password = $_REQUEST['pwd']; //pass from previous page
$name = $_REQUEST['name']; //pass from previous page
$checkUserPass = mysql_query("SELECT * FROM validPersonnel WHERE Passkey = '$password' and Name = '$name'", $conn); //check if the user exist
if(mysql_num_rows($checkUserPass) == 1) {
$personnelId = mysql_query("SELECT PersonnelID FROM validPersonnel WHERE Passkey = '$password' and Name = '$name'", $conn); //query user id
while($row = mysql_fetch_assoc($personnelId)) {
echo $row['PersonnelD']; // print user id
}
mysql_close($conn);
//echo "<br/><br/>";
//echo "<script>alert('Logged In.')</script>";
//header("Refresh: 1; url=profile/profile.php?id="'.$id.');
//header('Refresh: 1; url=test.php?id=$personnelId');
} else {
echo "<br/><br/>";
echo "<script>alert('Wrong Password.')</script>";
header('Refresh: 1; url=personnelselect.php');
}
}
?>
i cannot echo the $row['PersonnelD'] the page shows blank. i cannot understand where did i go wrong. this page quesion have been solved
Looks like you have mistake in code:
echo $row['PersonnelD'];
shouldn't it be following?
echo $row['PersonnelID'];
check the mysql_fetch_assoc() function may be its parameter is empty so it can't enter the while loop
Try to debug and check the values came in the variables using var_dump() function. Ex: var_dump($row); in while loop.
In both your querys, you have
"SELECT * FROM validPersonnel WHERE Passkey = '$password' and Name = '$name'"
It should be:
"SELECT * FROM validPersonnel WHERE Passkey = '".$password."' and Name = '".$name."';"
PHP doesn't recognize the $var unless you close the quotes. The period adds the $var to the string.

Mysqli Query Echo result

Hi I am trying to make status of user so it will check how many post this user has and echo out the result, it was working fine when I was using mysql but after converting it to mysqli it giving me some errors
Here is my code:
<?php
if(!isset($_COOKIE['loggedin'])){
header("location:index.php");
}
session_start();
if(!isset($_SESSION['user'])){
header("location: index.php");
}
else {
?>
<?php
$con=mysqli_connect("localhost","root","123","user");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$resule = "SELECT count(ID) from save_data where username = '".$_SESSION['user']."'"
or die(mysql_error());
$result = $con->query($resule);
$row = $result->fetch_array(MYSQLI_NUM);
echo $row[0], $row[1];
?>
<?php }?>
Error:
Notice: Undefined offset: 1 in C:\xampp\htdocs\mysql_login\status.php on line 30
Try removing $row[1] from:
echo $row[0], $row[1];
As the error says the offset 1 is undefined. so its pretty simple that you should remove $row[1] from echo $row[0], $row[1];
The problem is $row[1] in echo $row[0], $row[1]; because the $result->fetch_array will only fill the $row[0], because the SQL Query
"SELECT count(ID) from save_data where username =
'".$_SESSION['user']."'"
will only return one result if username is unique.
What will be happened If your query doesn't return any values? So better you check
if($resesult)
{
$row = $result->fetch_array(MYSQLI_NUM);
echo $row[0];// remove $row[1] because it fills only the $row[0]
}

Error in retriving data from database

I'm trying to retrive my first name and last name for viewprofile.php but i'm getting resource ID#5 . I am CREATING session in Login page after successful authentication. And I am trying to use it here. I'm trying to use a session which has been created to fetch the data from the database.
<html>
<h1> My Profile</h1>
<?php
session_start();
require "config.php";
$con = mysql_connect("localhost", $db_user, $db_pass);
if(!$con)
{
die('cound not connect: '. mysql_error());
}
mysql_select_db($db_name, $con);
# include 'new.php';
echo $_SESSION['username'];
#$usname = $_SESSION['username'];
#echo 'local var: ', $usname;
$sql1 = "SELECT * FROM register WHERE uname='".$_SESSION['username']."'" ;
#echo $sql1 ;
$result= mysql_query($sql1)or die(mysql_error());
#echo "res: " . $result;
while($row = mysql_fetch_array($result))
{
echo $row['fname']." ".$row['lname'];
echo"</br>";
}
mysql_close($con);
?>
</html>
I'm getting resource ID#5. Searched numerous places no luck. Kindly help
Unless I'm mistaken mysql_fetch_array will give you values that can be expressed as $row[0], $row[1] etc whereas mysql_fetch_assoc is what you're trying to use to get $row['fname'] etc
Change your code to
while($row = mysql_fetch_assoc($result))
In either case a print_r($row) within your while loop will you how it's made up.

Categories