Web-application related to session

I am doing my web app and the session variable drives me crazy, pls any one could help me. the only session variable I have is the user name which should be shown in all operations. this is the search.php code and it works just once and if i want to search again I lose the session variable:

 <?php
session_start(); 
if (isset($_POST['mynmae'])){
$_SESSION['myname']=$user;
$user=$_POST['mynmae'];
}
<form  action=""  method="post">
 <button type="submit"   ></button>
  </form>
 <?php

     if (isset($_SESSION['myname'] )) {

       echo( "Hi " .$_SESSION['myname']. " here are the search result.");

     } else {  
     };

 $conn = mysql_connect("localhost", "root", '');

  mysql_select_db("db103",$conn);

        $fname = '';

if (isset($_POST['search']))
{
    $fname = $_POST['search'];
}
else{}

if(isset($_SESSION["myname"])){
    $user='';
  $user=$_SESSION["myname"];  

 $sql = "SELECT * FROM telephone_guide where owner='$user' and (firstName like '%$fname%' or secondName like '%$fname%' or phonenumber like '%$fname%' or celnumber like '%$fname%')";


 $result = mysql_query($sql, $conn) ;

//  number of rows fetched
$num = mysql_num_rows($result);


echo("<table width=300 border=3 >");

echo("<th>Modify<th>First Name<th>Second Name<th>tele-Phone Number<th>cel_phone number<th>Date<th>Address");


 while ($arr = mysql_fetch_array($result)) {

$e="Modify";

echo("<tr><td><a href='update1.php?id1=$arr[0]'>$e</td><td>$arr[2]</td><td>$arr[3]</td><td>$arr[4]</td><td>$arr[5]</td><td>$arr[6]</td><td>$arr[7]</td></tr>");
 }
echo("</table>");

?>
<br>
<br>
<?php
echo("</div>");} else{ 

}

   ?>

the second one is my update code which dose not show my session variable, do not know why however edit and delete operations work correctly

<?php
session_start();



 $conn = mysql_connect("localhost", "root", '');
  mysql_select_db("db103",$conn);
     $id=$_GET['id1'];

 $sql = "SELECT * FROM telephone_guide where  id='$id' ";
 $result = mysql_query($sql, $conn) ;

$arr= mysql_fetch_array($result);


echo("<form name=f1 method='post'>");



     if (isset($_SESSION['myname'] )) {

       echo( "Dear " .$_SESSION['myname']. " you can change or delete<br>your info here.");

     } else {

     };
echo("<table>");
        echo("<tr><td><p> ID: </p><td><input  type=text name=id value=$arr[0] readonly></tr><br>");
echo("<tr><td><p>First Name:</p> <td><input type=text name=fn value=$arr[2]></tr>");
echo("<tr><td><p>second Name:</p><td><input type=text name=sn value=$arr[3]><tr>");
echo("<tr><td><p>Telephone:</p><td><input type=text name=tel value=$arr[4]></tr>");
    echo("<tr><td><p>celphone:</p><td><input type=text name=cel value=$arr[5]></tr>");
    echo("<tr><td><p>Birth date:</p><td><input type=text name=birth value=$arr[6]></tr>");
     echo("<tr><td><p>Address:</p><td><input type=text name=add value=$arr[7]></tr>");
echo("</table>");
?>       

<button type="submit" name="edit" id="edit"><b>Update</b></button>


        <?php
        if(isset($_REQUEST['edit'])){

            $f=$_REQUEST['fn'];
            $s=$_REQUEST['sn'];
            $t=$_REQUEST['tel'];
            $c=$_REQUEST['cel'];
            $b=$_REQUEST['birth'];
            $a=$_REQUEST['add'];
            $conn = mysql_connect("localhost", "root", '');
  mysql_select_db("db103",$conn);
            $sql = "update telephone_guide set id='$_POST[id]',firstName='$f',secondName='$s',phonenumber='$t',celnumber='$c',birth='$b',adress='$a' 
where id='$_REQUEST[id1]'";

             $result = mysql_query($sql, $conn) ;
            header('location:view.php');

        }

        if(isset($_REQUEST['delete'])){

            $f=$_REQUEST['fn'];
            $s=$_REQUEST['sn'];
            $t=$_REQUEST['tel'];
            $c=$_REQUEST['cel'];
            $b=$_REQUEST['birth'];
            $a=$_REQUEST['add'];
            ?>
        <script>
            if(window.confirm("Are you sure you want to delete this ?")) return true;
            <?php

            $conn = mysql_connect("localhost", "root", '');
  mysql_select_db("db103",$conn);
            $sql = "DELETE FROM telephone_guide WHERE id='$_REQUEST[id1]'";

             $result = mysql_query($sql, $conn) ;
            header('location:view.php');

        }
         echo("</form>");
        ?>
        </script>
        <?php
    echo("<form  method=post >");
    ?>
        <button type="submit" name="delete" ><b>Delete</b></button>

Hi @raghadatf and welcome to the forum.

Is this supposed to be mynmae or myname?

1 Like

‘myname’

Here you assign the session to the value of $user before you define user.
Should this be the other way around?
As well as fixing the typo.

There are also some security concerns with your code.

mysql is not included in any currently supported version of PHP. This means you must be using an out-dated version which is no longer supported and not getting any security patches.
You need to move to a newer version.
http://php.net/supported-versions.php

Take care with what you do with user input from $_POST and $_GET.

When outputting always escape to avoid script injections.

echo "Hi " .htmlspecialchars($_SESSION['myname']). " here are the search result.";

When building a query never put user input directly into the query string or you are prone to SQL injection. You should use prepared statements, available in mysqli or PDO found in current PHP versions.

2 Likes

You also have header redirects after you have sent output to the browser in one or two locations in the code - I would expect these are giving you an error. If you want to use a header redirect, you must do it before you send anything to the browser.

2 Likes

Thanks for your advice I will change the version and see what will happen

If you simply change to a current PHP version the script will fail because mysql will not work.
It is not a quick fix, it involves changing database interaction for the whole site/app.
So when you do change to an updated version you will have to use mysqli or PDO to communicate with your database.

1 Like

ok so in my syntax i will change all mysql to mysqli are there any other changes ?

There is a bit more than just adding the i on the end, some of the mysqli syntax is different to mysql. You will have to check the documentation, it is a long time since I used mysqli and switched to it from mysql. I use PDO now which is my preference.

To make the code safer from SQL Injection you should use prepared statements for the queries with variables in them.

This is going a bit off-topic, I could split this to another topic if you need to know more about this, but are still working on the original problem.
You should use

I upgrade my version to 7.0.33 and I replace the all mysql to mysqli and I use this also( $conn = mysqli_connect(“localhost”, “root”, ‘’,‘db103’); )
the point is that i did not got any errors but nothing is work and there are many things (like button and some of javascript effect also dose not work however it was working with the previous version )hiding I do not know why

OK, post your updated code and people will try to help. I can’t see any JavaScript in your original post, so obviously can’t help, but if that has happened since you converted to a more modern database library, then there may be issues with the changes you have made. In any case, let’s see the code and see what we can do. You’ll have to expand on “nothing is working”, though, with a bit more detail.

1 Like

in the php code I let it ,I just convert mysql to mysqli … like

`$conn = mysql_connect("localhost", "root", '');` I change it to 
`$conn = mysqli_connect("localhost", "root", ' ' ,'db103');` and delete
`**mysql_select_db("db103",$conn);**`

and the javascript code was working perfectly before updating( javascript include just fadeToggle effect).

And have you changed all the other lines, those that run queries, get results and so on? If not, you need to. If so, can you show us in case there’s a typo? Remember above:

That’s fine, but it’s difficult to try to help figure out why it’s stopped working when we can’t see what the code was before, and what it is now.

1 Like

thanks my friend I check mysqli library and I got the true syntax but it still give the same issue that I ask about in this post (so updating the php version has been updated correctly but nothing change ) please reread the main post . and thanks in advance

The trouble is - the original post doesn’t show the code you’re using now, so it would really help to see the current code. You also have typos in that original code, have you fixed them?

In here:

Capture

it looks as if there’s a space before your opening PHP tag, which means that the session_start() and header redirection won’t work, and should give you an error message if you have error reporting enabled.

2 Likes

I have no errors at all but whenever I search the first time it works but for the second time it does not and the variable does not show in update page . give just 2 minutes and I will edit the post and put the current code.

my search code

<?php
session_start(); 
 if (isset($_POST['myname'])) {
		$user = $_POST['myname'];
		$_SESSION['myname'] = $user;
		
	}   

      if (!isset($_SESSION['myname'])) {
		
}
 $conn = mysqli_connect("localhost", "root", '','db103');

        
  if (isset($_SESSION['myname'])) {
		
if (isset($_POST['search']) ){
    $user = $_SESSION['myname'];
    $fname = ' ';
       echo( "Hi " .$_SESSION['myname']. " here are the search result.");
       
    $fname = $_POST['search'];    
 $sql = "SELECT * FROM telephone_guide where owner='$user' and (firstName like '%$fname%' or secondName like '%$fname%' or phonenumber like '%$fname%' or celnumber like '%$fname%')";

 $result = mysqli_query($conn,$sql) ;

//  number of rows fetched
$num = mysqli_num_rows($result);

echo("<div class='styl'>");
echo("<table width=300 border=3 >");

echo("<th>Modify<th>First Name<th>Second Name<th>tele-Phone Number<th>cel_phone number<th>Birth Date<th>Address");


 while ($arr = mysqli_fetch_array($result)) {
  
$e="Modify";
 
echo("<tr><td><a href='update1.php?id1=$arr[0]'>$e</td><td>$arr[2]</td><td>$arr[3]</td><td>$arr[4]</td><td>$arr[5]</td><td>$arr[6]</td><td>$arr[7]</td></tr>");
 }
echo("</table>");
    
echo("</div>");} else{ 
}
}
   ?>

inserting code:

<?php
session_start();
$conn = mysqli_connect("localhost", "root", '',"db103");

if(isset($_SESSION['myname'])){
 $sql = "INSERT INTO telephone_guide values ('','$_SESSION[myname]','$_POST[fname]','$_POST[sname]','$_POST[telnum]','$_POST[celnum]','$_POST[date]','$_POST[address]')";

 if (mysqli_query($sql, $conn)) { 
 } else {

     echo (mysqli_error());

 }
 echo"<script type='text/javascript'>alert('Your information has been added!  ');
 window.open('tele.php','_self');
            </script>";
}else{
            echo"<script type='text/javascript'>alert('please create an acount!  ');
 window.open('tele.php','_self');
            </script>";
        }
 ?>

updating and deleting code

<?php
if(!isset($_SESSION)){
session_start(); }
if (isset($_SESSION['myname'])) {

	$user = $_SESSION['myname'];}
 $conn = mysqli_connect("localhost", "root", '',"db103");
 
     $id=$_GET['id1'];
    $user = $_SESSION['myname'];
 $sql = "SELECT * FROM telephone_guide where  id='$id' ";
  $result = mysqli_query($conn,$sql);

$arr= mysqli_fetch_array($result);

 echo("<div class='style'>");
echo("<form name=f1 method='post'>");
        
    
     if (isset($_SESSION['myname'] )) {
       echo"<b>"; 
       echo( "Dear " .$_SESSION['myname']. " you can change or delete<br>your info here.");
         echo"</b>";
     } else {
        
     };
echo("<table>");
        echo("<tr><td><p> ID: </p><td><input  type=text name=id value=$arr[0] readonly></tr><br>");
echo("<tr><td><p>First Name:</p> <td><input type=text name=fn value=$arr[2]></tr>");
echo("<tr><td><p>second Name:</p><td><input type=text name=sn value=$arr[3]><tr>");
echo("<tr><td><p>Telephone:</p><td><input type=text name=tel value=$arr[4]></tr>");
    echo("<tr><td><p>celphone:</p><td><input type=text name=cel value=$arr[5]></tr>");
    echo("<tr><td><p>Birth date:</p><td><input type=text name=birth value=$arr[6]></tr>");
     echo("<tr><td><p>Address:</p><td><input type=text name=add value=$arr[7]></tr>");
echo("</table>");

?>       
<button type="submit" name="edit" id="edit"  ><b>Update</b></button>
        <?php
        if(isset($_REQUEST['edit'])){
            
            $f=$_REQUEST['fn'];
            $s=$_REQUEST['sn'];
            $t=$_REQUEST['tel'];
            $c=$_REQUEST['cel'];
            $b=$_REQUEST['birth'];
            $a=$_REQUEST['add'];
            $conn = mysqli_connect("localhost", "root", ''.'db103');
            $sql = "update telephone_guide set id='$_POST[id]',firstName='$f',secondName='$s',phonenumber='$t',celnumber='$c',birth='$b',adress='$a' 
where id='$_REQUEST[id1]'";
            
             $result = mysqli_query($sql, $conn) ;
            header('location:view.php');
            
        }
       
        if(isset($_REQUEST['delete'])){
            
            $f=$_REQUEST['fn'];
            $s=$_REQUEST['sn'];
            $t=$_REQUEST['tel'];
            $c=$_REQUEST['cel'];
            $b=$_REQUEST['birth'];
            $a=$_REQUEST['add'];
            ?>
        <script>
            if(window.confirm("Are you sure you want to delete this ?")) return true;
            <?php

            $conn = mysqli_connect("localhost", "root", '','db103');

            $sql = "DELETE FROM telephone_guide WHERE id='$_REQUEST[id1]'";
            
           
            header('location:view.php');
            
        }
         echo("</form>");
        ?>
        </script>
        <?php
    echo("<form  method=post >");
    ?>
        <button type="submit" name="delete" ><b>Delete</b></button>
    <?php    
echo('</div>');

?>

view code

<?php
if(!isset($_SESSION)){
session_start(); 
    if (isset($_POST['mynmae'])){
$_SESSION['myname']=$_POST['mynmae'];
$user=$_SESSION['myname'];}
}

            $conn = mysqli_connect("localhost", "root", '',"db103"); 
$user=$_SESSION['myname'];
 $sql = "select * from telephone_guide where owner = '$user' " ;


 $result = mysqli_query($conn,$sql) ;

//  number of rows fetched
$num = mysqli_num_rows($result);
?>
<div class='style'>
<table  width="660px" border="1"  >
    <tr><td><b>first Name</b></td><td ><b>second name</b></td><td ><b>telePhone number</b></td><td ><b>celephone number</b></td><td style="width:80px;" ><b>Birth date</b></td> <td ><b>Address</b></td></tr>
<?php
 while ($arr = mysqli_fetch_array($result)) {

  
echo("<tr><td>$arr[2]</td><td>$arr[3]</td><td>$arr[4]</td><td>$arr[5]</td><td>$arr[6]</td><td>$arr[7]</td></tr>");

 }
           
?>

So, in your form, is it:

$_SESSION['myname']=$_POST['mynmae'];

or is it

$user = $_POST['myname'];

When you say that you have a problem searching the second time, does your results page re-draw the search form, or are you opening the search form from scratch each time?

Which variable does not show? The session variable, or the one you pass in via the URL? If the latter, does it show up correctly when you hover over the link from your results table?

At the start of your update code

if(!isset($_SESSION)){
session_start(); }

you have this, which surely isn’t going to work? Don’t you need to call session_start() before you can access $_SESSION in any case? So if I’m reading it correctly, you don’t call session_start() unless you can already see $_SESSION, which you won’t be able to until you call session_start(). So I think you need to get rid of the if() clause around it, and just call the function.

Once you have this sorted, you need to read up on “Prepared Statements”, a feature of mysqli and PDO that will add some security to your site. At the moment it is fairly well open to malicious users and you don’t check any user-provided data before using it.

1 Like

you have this, which surely isn’t going to work? Don’t you need to call session_start() before you can access $_SESSION in any case? So if I’m reading it correctly, you don’t call session_start() unless you can already see $_SESSION , which you won’t be able to until you call session_start() . So I think you need to get rid of the if() clause around it, and just call the function.

$_SESSION['myname']=$_POST['mynmae'];

so I drop the if () statement and start the page with (session_start(); ) and it still does not working .

the variable which I pass it in my URL (the id ) is shown correctly but the second one which is the session [‘myname’] does not view to the update page as I echo it in this line ( ```
echo( “Dear " .$_SESSION[‘myname’]. " you can change or delete
your info here.”);

ok I drop the if and start it with session_start(); and still dose not working.


in my main page there is a search bar it should be search whenever you type in it and show the result at the same page  but the problem is that work just for the first time (I think when I press the search button for the first time it give me the result but it refresh the page which destroy my variable session ['myname'] so when I want to search again there is no variable session to be tested and show the result depend on it ).

I edit my search code to this to make it more logical but it still working correctly just for the first time

<?php 
session_start(); 
if (!isset($_SESSION['myname'])) {
		
	}

	
        
 $conn = mysqli_connect("localhost", "root", '','db103');

        
  if (isset($_SESSION['myname'])) {
		
if (isset($_POST['search']) ){
    $user = $_SESSION['myname'];
    $fname = '';
       echo "<h1 style='color:#0e0e62;font-size:18px;padding-left:100px;'>";
   
       echo"<b>"; 
       echo( "Hi " .$_SESSION['myname']. " here are the search result.");
         echo"</b>";
     echo"</h1>";

    $fname = $_POST['search'];


    
 $sql = "SELECT * FROM telephone_guide where owner='$user' and (firstName like '%$fname%' or secondName like '%$fname%' or phonenumber like '%$fname%' or celnumber like '%$fname%')";


 $result = mysqli_query($conn,$sql) ;

//  number of rows fetched
$num = mysqli_num_rows($result);

echo("<div class='styl'>");
echo("<table width=300 border=3 >");

echo("<th>Modify<th>First Name<th>Second Name<th>tele-Phone Number<th>cel_phone number<th>Birth Date<th>Address");


 while ($arr = mysqli_fetch_array($result)) {

  
$e="Modify";
 
echo("<tr><td><a href='update1.php?id1=$arr[0]'>$e</td><td>$arr[2]</td><td>$arr[3]</td><td>$arr[4]</td><td>$arr[5]</td><td>$arr[6]</td><td>$arr[7]</td></tr>");


 }
echo("</table>");
    
?>
<br>
<br>
<?php
echo("</div>");} else{ 

}
}

   ?>