Take data from one php page and echo it onto another page - php

I need to simply take data from one page, upon a condition, and echo it on another page. Here is my code and my other attempts which do not work.
<?php
session_start;
/* connect to database */
$db = mysql_connect("localhost", "root", "root");
if (!$db)
die('could not connect');
mysql_select_db('androidp2p')
or die("could not select database");
/* variables */
$from = mysql_real_escape_string($_POST['from']);
$to = mysql_real_escape_string($_POST['to']);
$message = mysql_real_escape_string($_POST['message']);
/* conditional code */
if ($_POST['to'])
{
/* user wants to send a message */
$query = "INSERT INTO messages (fromuser, touser, message) VALUES ('$from', '$to', '$message')";
mysql_query($query)
or die("\n\ndatabase error!\n". mysql_error());
echo "ok. Messages have been saved.";
}
else
{
/* user wants to retrieve his messages*/
$query = "SELECT * FROM messages WHERE touser='$from'";
/* echo1 */
echo $query;
$result = mysql_query($query)
or die("\n\ndatabase error!\n". mysql_error());
$mailbox = array();
while($row = mysql_fetch_assoc($result)){
$mailbox[] = $row;
}
/* echo2 */
echo "{ \"mailbox\":".json_encode($mailbox)." }";
$name = "{ \"mailbox\":".json_encode($mailbox)." }";
/* echo3 */
echo $name;
$_SESSION['myValue']=$name;
}
?>
And on the next php page, called test.php:
<?php
session_start;
echo $_SESSION['myValue'];
?>
My logcat shows that I am getting data in all three echos, but still nothing is being displayed on test.php(i.e. page2).
I also tried:
Attempt 1:
In page 1:
session_start();
$_SESSION['myValue']=$name;
And in page2 used:
session_start();
echo $_SESSION['myValue'];
Attempt 2:
In page 1:
session_start();
$_SESSION['name'] = $name ;
And in page2 used:
session_start();
$name = $_SESSION['name'];
Attempt 3:
In page 1:
header("Location: test.php?name=".$name);
And in page2 used:
$name = $_GET['name'] ;
But nothing is being displayed on test.php(In this last attempt3 I got a bunch of warnings and maybe errors). What am I doing wrong?
This is my logCat:
04-13 14:46:22.564: I/RESPONSE(4591): SELECT * FROM messages WHERE touser='r'
04-13 14:46:22.564: I/RESPONSE(4591): { "mailbox":[{"id":"117","fromuser":"qw","touser":"r","message":"zx","timestamp":"2013-04-13 01:30:59"}] }
Now above I want you to see that touser is r. This entry into the db is what I want, i.e. all entries where the field "touser" contains the value "r".
Now, this is my test.php page:
{ "mailbox":[{"id":"123","fromuser":"r","touser":"","message":"","timestamp":"2013-04-13 13:41:23"},{"id":"122","fromuser":"r","touser":"","message":"","timestamp":"2013-04-13 13:30:53"}] }
As you would see, it returned all entries where the fromuser was r. Why do the two contradict each other??

Not entirely sure what you are asking, but perhaps this will help.
In the beginning of your /* conditional code */
Use an isset condition....
<?php
session_start();
/* connect to database */
$db = mysql_connect("localhost", "root", "root");
if (!$db)
die('could not connect');
mysql_select_db('androidp2p')
or die("could not select database");
/* variables */
$from = mysql_real_escape_string($_POST['from']);
$to = mysql_real_escape_string($_POST['to']);
$message = mysql_real_escape_string($_POST['message']);
/* conditional code */
if (isset ($_POST['to']))
{
/* user wants to send a message */
$query = "INSERT INTO messages (fromuser, touser, message) VALUES ('$from', '$to', '$message')";
mysql_query($query)
or die("\n\ndatabase error!\n". mysql_error());
echo "ok. Messages have been saved.";
}
else
{
/* user wants to retrieve his messages*/
$query = "SELECT * FROM messages WHERE touser='$from'";
/* echo1 */
echo $query;
$result = mysql_query($query)
or die("\n\ndatabase error!\n". mysql_error());
$mailbox = array();
while($row = mysql_fetch_assoc($result)){
$mailbox[] = $row;
}
/* echo2 */
echo "{ \"mailbox\":".json_encode($mailbox)." }";
$name = "{ \"mailbox\":".json_encode($mailbox)." }";
/* echo3 */
//echo $name; no need to echo
$_SESSION['myValue']=$name;
}
?>

Related

error not outputting in login form

my code is
$query = "USE `davidedwardcakes`";
$result = mysql_query($query, $connect);
if(!isset($result)){echo 'no' . mysql_error();}
$query = "SELECT * FROM `users` WHERE uname = '$uname'";
$result2 = mysql_query($query, $connect);
if(!$result2){echo 'wrong username or password' . mysql_error(); var_dump($result2);}
while($row = mysql_fetch_array($result2))
{echo $row['uname'] . $row['pass']; var_dump($result2);}
echo 'submited';
I am trying to create a login form but i do not get any error output whenever i execute it with blank forms. Help please.
It is because the query will still run successfully if $uname is an empty string. It will just have a zero-row result set. As such, where you do this:
if(!$result2){echo 'wrong username or password' . mysql_error(); var_dump($result2);}
$result2 will have a truthy value and your code in the conditional will not execute.
You should check mysql_num_rows() to determine if you have a non-empty result set.
By the way, there is no reason to run an actual mysql_query() to select the DB to use. mysql_select_db() can be used for this purpose.
That being said, you should be using mysqli or PDO instead of mysql.
Let me convert first your code to at least MySQLi instead of deprecated MySQL.
<?php
/* ESTABLISH CONNECTION */
$connect=mysqli_connect("YourHost","YourUsername","YourPassword","yourDatabase"); /* REPLACE THE NECESSARY DATA INSIDE */
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
/* $query = "USE `davidedwardcakes`";
$result = mysql_query($query, $connect);
if(!isset($result)){echo 'no' . mysql_error();}
HIDE THIS FIRST, WHAT'S THE PURPOSE OF THIS CODE? */
*/
$uname=mysqli_real_escape_string($connect,$_POST['uname']); /* REPLACE THE NECESSARY POST DATA */
$query = "SELECT * FROM `users` WHERE uname = '$uname'"; /* ADD ALSO HERE THE PASSWORD */
$result2 = mysqli_query($connect,$query);
if(mysqli_num_rows($result2)==0){ /* IF MATCHES FOUND NONE, ERROR */
echo "Wrong username or password";
var_dump($result2);
} /* END OF IF RESULT2 IS O */
else {
while($row = mysqli_fetch_array($result2)){
echo $row['uname'] . $row['pass'];
} /* END OF WHILE LOOP */
echo 'submited';
var_dump($result2);
} /* END OF ELSE */
?>

how to display an auto increment value in a textbox using session

Login.php
session_start();
<?php
$username = "root";
$password = "tiger";
$hostname = "localhost";
//connection to the database
$dbhandle = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
/* #var $selected type */
$selected = mysqli_select_db($dbhandle,"sample")
or die("Could not select sample");
$name=(\filter_input(\INPUT_POST,'name'));
$phone=(\filter_input(\INPUT_POST,'phone'));
$email=(\filter_input(\INPUT_POST,'email'));
//$custno=(\filter_input(\INPUT_POST,'custno'));
if(!empty(\filter_input(\INPUT_POST,'continue')))
{
echo "<script type='text/javascript'>\n";
'check()';
echo "</script>";
$sql="insert into customersignin(name,phone,email)values('$name','$phone','$email')";
$result=mysqli_query($dbhandle,$sql) or die(\mysqli_error($dbhandle));
}
else
{
$sql1="insert into customersignin(custno)values(NULL)";
$result1=mysqli_query($dbhandle,$sql1) or die(\mysqli_error($dbhandle));
}
$sql2="select custno from customersignin";
$result2=mysqli_query($dbhandle,$sql2) or die (mysqli_error($dbhandle));
$row= mysqli_fetch_array($result2);
if(mysqli_num_rows($result2)>0)
{
echo "$_SESSION['custno']";
unset($_SESSION['custno'];
header('Location:customersvsoup.php');
}
mysqli_close($dbhandle);
$_SESSION[name]=(\filter_input(INPUT_POST,'name'));
customer.php
<body>
<?php session_start(); ?>
<input type="text" style="position: absolute;top:200px;" value="<?php echo $_SESSION["custno"]?>">
</body>
In the php file the customer log in is done,the custno is the auto generate field,i have 2 buttons called continue and skip,for both the auto generate works fine,after any of the button action is done,i need to display the custno in the text box of the next page using session.But the problem is the text box is empty when i run this code.But the session['name'] is working..Please help.
Your session_start(); should come at the beginning of the file in login.php. I see you using $_SESSION[custno] before it's called. That's why your textbox is empty.
Also it should be:
$_SESSION['custno']
$_SESSION['name']note the single quotes
Regarding your logical problem (in the comments) try:
$_SESSION['name'] = (filter_input(INPUT_POST, 'name'));
if (!empty(filter_input(INPUT_POST, 'continue')))
{
echo "<script type='text/javascript'>\n";
'check()';
echo "</script>";
$sql = "insert into customersignin(name,phone,email)values('$name','$phone','$email')";
$result = mysqli_query($dbhandle, $sql) or die(mysqli_error($dbhandle));
$sql2 = "select max(custno) as last_custno from customersignin";
$result2 = mysqli_query($dbhandle, $sql2) or die(mysqli_error($dbhandle));
if (mysqli_num_rows($result2) > 0)
{
$row = mysqli_fetch_assoc($result2);
$_SESSION['custno'] = $row['last_custno'];
header('Location:customersvsoup.php');
}
}
else
{
$sql1 = "insert into customersignin(custno)values(NULL)";
$result1 = mysqli_query($dbhandle, $sql1) or die(mysqli_error($dbhandle));
//since this bit of code is repeating,
//you could even use a function to shorten it
$sql2 = "select max(custno) as last_custno from customersignin";
$result2 = mysqli_query($dbhandle, $sql2) or die(mysqli_error($dbhandle));
if (mysqli_num_rows($result2) > 0)
{
$row = mysqli_fetch_assoc($result2);
$_SESSION['custno'] = $row['last_custno'];
header('Location:customersvsoup.php');
}
}
And please put the session_start(); inside after <?php. All php code should be within the PHP tags.
you have error in insert query:
$sql="insertintocustomersignin(name,phone,email)values('$name','$phone','$email')";
should be :
$sql="insert into customersignin(name,phone,email) values ('$name','$phone','$email')";
you should use quotes in array index :
$_SESSION[custno], $_SESSION[name] should be $_SESSION['custno'], $_SESSION['name']

How to detect whether users have accepted terms?

Basically I am writing a PHP and MYSQL script that will check whether a user has accepted the terms and conditions or not. In the databse every current user that has signed up is set to "unaccepted". When they log in the first page that they are directed to should have a scirpt on it that detects whether or not the status of the tos column in the users table is set to "accepted" or "unaccepted". If it is accepted they can continue, and if it is not they they will be forced to go to a page and accept them before they can continue to use the rest of my site. This is the code so far but it doesn't seem to be working. Any suggestions help.
<?php
$username=$_SESSION['username'];
$connect = mysql_connect('**', '**', '**', '**');
if (!$connect)
{
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db('**'))
{
die('Could not select database: ' . mysql_error());
}
$toschecker = mysql_query("SELECT `tos` FROM `users` WHERE `username` = '$username'");
if (!$toschecker)
{
die('Could not query:' . mysql_error());
}
mysql_close($connect);
$unaccepted='unaccepted';
if ($toschecker === $unaccepted)
{
header('Location: accepttos.php');
}
?>
For some reason this isn't directing them to the accepttos.php page. Thanks in advance.
Change MySQL to MySQLi. Explanations are in the comments.
<?php
$username = $_SESSION['username'];
$connect = mysqli_connect('Host', 'Username', 'Password', 'Database');
if (!$connect)
{
die('Could not connect: ' . mysql_error());
}
$toschecker = mysqli_query($connect,"SELECT `tos` FROM `users` WHERE `username` = '$username'"); /* SELECT TOS COLUMN */
while ($row = mysqli_fetch_array($toschecker))
{
$tos = $row['tos']; /* STORE TO A VARIABLE THE FETCHED TOS */
}
$unaccepted = 'unaccepted';
if ($tos == $unaccepted) /* COMPARE THE TOS VARIABLE IF UNACCEPTED */
{
header('Location: accepttos.php');
}
else {
header('Location: acceptedTOS.php'); /* IF TOS IS ACCEPTED. CHANGE THE LOCATION */
}
mysqli_close($connect);
?>
$toschecker is a resource , try the following under the mysql_query line to see the result of your query, which you can use to redirect accepttos.php etc..
if( $row = mysql_fetch_assoc($toschecker)) {
var_export($row['tos']);
}
You need to access the information in the fields of your database. Here is an example.
$toschecker = mysql_query($sql);
$row = mysql_fetch_array($toschecker);
$tos = $row['tos'];
if($tos == 'accepted'){
// go to regular page
}else {
// go to accept terms page
}

headers not working PHP

Page 1 abc.html.. on submit it will jump to this PHP page .
This is page PHP1.php here i am trying to validate user input if name and id in in data he will be forwarded to fill out second part of registration if not it will just give error.
<?php
session_start();
$_SESSION["acb"] = "good";
$_SESSION['team'] = $_POST['team_name'];
$con = mysql_connect("localhost", "user", "password");
if (!$con)
{die('Could not connect: ' . mysql_error());}
mysql_select_db("mydbName");
if(isset($_POST['team_name'],$_POST['id'])){
$team_name = mysql_real_escape_string($_POST['team_name']);
$id = mysql_real_escape_string($_POST['id']);
if (!empty($team_name)) {
$result= mysql_query("SELECT COUNT(`teamname`) FROM `table` WHERE `teamname`='$team_name' AND `id`='$id'");
$team_result = mysql_fetch_row($result);
if ($team_result[0] == '0') { //if does not exist print failed.
echo 'Varification failed';
} else {
header('Location: http://www.abc.com/REGISTERpart2.php');
}} } ?>
RegisterPART2.php is where i am checking my session exist or not (the one i started in last file). if not i want to redirect back to form one and fill that first then come to registration part 2
`<?php
session_start();
$name = $_SESSION['team']; //a value stored in session which i used on this page
if (($_SESSION["abc"] !== 'good')) {
header('Location: http://www.abc.com/page1.html'); //take back to stage 1 coz user did not fill first part.
}
else{
echo $name. 'you have completed register process part one you may continue!';
}
?>
If you're using the new MySQL version (MySQLi), so the first page will become:
<?php
session_start();
$_SESSION["acb"] = "good";
$_SESSION['team'] = $_POST['team_name'];
$con = new mysqli("localhost", "user", "password", "mydbName");
if (!$con) {
die('Could not connect: ' . $con->error());
};
if (isset($_POST['team_name'],$_POST['id'])) {
$team_name = $con->real_escape_string($_POST['team_name']);
$id = $con->real_escape_string($_POST['id']);
if (!empty($team_name)) {
$result = $con->prepare("SELECT COUNT(`teamname`) FROM `table` WHERE `teamname`='$team_name' AND `id`='$id'");
$result->execute();
$result->bind_result($one,$two,$three,$etc);
$result->fetch();
if (empty($one) and empty($two) and empty($three) and empty(etc)) { // may be and/or (pick one)
echo 'Varification failed';
} else {
header('Location: http://www.abc.com/REGISTERpart2.php');
}
}
}
?>
You may use the following alternative to header.
prinf('<script>window.location = "URL HERE"</script>');
It should do the same thing as header does.

Undefined Index - Even with Isset If statement

Can anyone tell me why I am getting an Undefined Index error on my code here.
I have used this setup using the if(isset) condition in other parts of my project after
researching my original Undefined Index errors and ISSET fixed my problems. But it is not working here for some reason and I cannot see why.
This form is POSTING the input:
<form action="addAlbum_Processed.php" method="POST">
<p>Enter artistID of Artist<input type="number" name="artist_id" maxlength="2" size="2"></p>
<p>Enter name of Album to be created<input type="text" name="album_name" size="20"></p>
<input type="submit" name="submit" value="submit"></form>
and this page is processing the form input and updating the albums table in my database:
<?php
$connection = mysql_connect('localhost','root','')
or die(mysql_error());
echo "Connected to php Server <br>";
or die("Could not select assi2 database");
echo "Connected to assi2 database <br>";
if(isset($_POST['submit']))
{
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
}
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
$sqlQuery = "SELECT * FROM albums WHERE album = '{$album_name}'";
$result = mysql_query($sqlQuery, $connection) or die("Selection Query Failed !!!");
if (mysql_num_rows($result) != 0)
{
header ("Location: Album_Exists.html");
}
else
{
$sqlInsert = "INSERT INTO albums (ArtistID, Album, delete_marker)
VALUES ('{$artist_id}','{$album_name}','delete_marker = 0')";
$result = mysql_query($sqlInsert, $connection) or die("Selection Query Failed !!!");
header ("Location: addAlbum_Processed.php");
}
mysql_close($connection);
?>
I cannot see where I am going wrong. Regards, TW
This is a tiny example of your problem:
if(isset($_POST['submit']))
{
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
}
You check whether a submit form field was posted before using the other fields. So far, so good. (I would check for the fields that were going to be used, but at least you're checking something.)
But then:
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
You use the fields anyway.
What's more...you don't keep from trying to insert stuff if a form isn't being posted. So any time some rogue spider visits your page, you end up with a blank album in your database.
And that's not even mentioning the fact that you're still using mysql_query.
if(isset($_POST['submit']))
{
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
}
|__________________________| first
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
|_________________________| Repeated
you are fetching variables twice.only one that is if condition is enough.Also use isset for both the variables.
if(isset($_POST['submit']))
{
if isset($_POST['album_name'])
$album_name = $_POST['album_name'];
if isset($_POST['artist_id'])
$artist_id = $_POST['artist_id'];
}
Try something like in addalbam_process.php
<?php
$connection = mysql_connect('localhost','root','')
or die(mysql_error());
echo "Connected to php Server <br>";
or die("Could not select assi2 database");
echo "Connected to assi2 database <br>";
if(isset($_POST['submit']))
{
if(isset($_POST['albam_name']){$album_name = $_POST['album_name']};
if(isset($_POST['artist_id']){$artist_id = $_POST['artist_id']};
}
$sqlQuery = "SELECT * FROM albums WHERE album = '{$album_name}'";
$result = mysql_query($sqlQuery, $connection) or die("Selection Query Failed !!!");
if (mysql_num_rows($result) != 0)
{
header ("Location: Album_Exists.html");
}
else
{
$sqlInsert = "INSERT INTO albums (ArtistID, Album, delete_marker)
VALUES ('{$artist_id}','{$album_name}','delete_marker = 0')";
$result = mysql_query($sqlInsert, $connection) or die("Selection Query Failed !!!");
header ("Location: addAlbum_Processed.php");
}
mysql_close($connection);
Please, use MYSQLI or PDO to Prevent SQL INJECTION
here </form> is missing
and try something like this
if(isset($_POST['submit']))
{
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
}
A few things.
This line 'delete_marker = 0' should most probably read as
VALUES ('{$artist_id}','{$album_name}','0')
or VALUES ('{$artist_id}','{$album_name}',0)
As I read it 'delete_marker = 0' you are attempting to actually write this value inside the delete_marker column (ArtistID, Album, delete_marker)
Or, you're attempting to use a WHERE delete_marker = 0 clause, which can't be used in an INSERT INTO, but an UPDATE or SELECT rather.
And your if(isset($_POST['submit'])) conditional statement should be wrapping your entire code, instead of just your 2 form variables, because it's basically saying "Ok, assign these 2 variables, then ignore the rest if it's NOT set."
Plus, you're repeating those 2 input variables.
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
(I wrapped your entire code inside the if(isset($_POST['submit'])) conditional statement, btw.
Side note: If you're having a DB connection issue, use this instead:
$connection = mysql_connect('localhost', 'root', '');
if (!$connection) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
PHP Give this a try:
Sidenote: If this line fails VALUES ('{$artist_id}','{$album_name}', 0) put quotes around the 0 as in '0'
<?php
$connection = mysql_connect('localhost','root','')
or die(mysql_error());
echo "Connected to php Server <br>";
or die("Could not select assi2 database");
echo "Connected to assi2 database <br>";
if(isset($_POST['submit']))
{
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
$sqlQuery = "SELECT * FROM albums WHERE album = '{$album_name}'";
$result = mysql_query($sqlQuery, $connection) or die("Selection Query Failed !!!");
if (mysql_num_rows($result) != 0)
{
header ("Location: Album_Exists.html");
}
else
{
$sqlInsert = "INSERT INTO albums (ArtistID, Album, delete_marker)
VALUES ('{$artist_id}','{$album_name}', 0)"; // or add quotes around the zero
$result = mysql_query($sqlInsert, $connection) or die("Selection Query Failed !!!");
header ("Location: addAlbum_Processed.php");
}
} // closing brace for if(isset($_POST['submit']))
mysql_close($connection);
?>

Categories