Jump to content

I've tried to insert data inside an input's value but the input goes like it is hidden


Go to solution Solved by uumer93,

Recommended Posts

Hi guys!

I've tried to insert data inside an input's value but the input goes like it is hidden, When I inspect the page it shows that there is no input inside my form. I've tried to move the code to the top of page but nothing is changed always a hidden input while it is not hidden at all as you can see below:

<div class="mb-3">

  <?php
  //Checking if submit button is clicked
   if (isset($_POST['submit'])) {
     //database cn
      $db = new PDO("mysql:host=localhost;dbname=centrify","root","");
      $username = $_POST['user'];
      $stmt = $db->prepare("SELECT * FROM agencies_data WHERE agency_user = ".$username."");
      $stmt->execute();
 ?>
 
  <input class="form-control" type="text" name="oid" value="<?php while($item = $stmt->fetch()) { echo $item['agency_user']; } ?>"> <?php } ?>

</div>

I've tested a lot of placements but it doesnt work for me.

value="<?php while($item = $stmt->fetch()) { echo $item['agency_user']; } ?>"
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                     NO!     NO!      NO!
  1. You don't use a while loop when there is only a single row returned.
  2. The while loop fetches rows until there are none left, at which point item contains "false" (ie empty).
  3. You are using the prepared query incorrectly. The point of preparing queries is to avoid putting variables into the query.
  <?php
  if ($SERVER['REQUEST_METHOD'] == 'POST') {
     //database cn
      $db = new PDO("mysql:host=localhost;dbname=centrify","root","");
      $stmt = $db->prepare("SELECT * FROM agencies_data WHERE agency_user = ? ");
      $stmt->execute([ $_POST['user'] ]);
      $item = $stmt->fetch();

      if ($item) {
      ?>
 
      <input class="form-control" type="text" name="oid" value="<?= $item['agency_user']?>">

      <php  
      }
   }
   ?>

 

  • Like 1

Try this.  I had to reformat since I couldn't make sense out of it.

//Checking if submit button is clicked
if (isset($_POST['submit'])) 
{
	//database cn
	$db = new PDO("mysql:host=localhost;dbname=centrify","root","");
	$username = $_POST['user'];
	$stmt = $db->prepare("SELECT * FROM agencies_data WHERE agency_user ='$username'");
	$stmt->execute();
	echo '<div class="mb-3">';
	while($item = $stmt->fetch()) 
	{ 
		echo "<input class='form-control' type='text' name='oid' value='{$item['agency_user']}'><br>";
	}
	echo "</div>";
}

 

Edited by ginerjm

Not really. The $username is a string literal an would need to be inside quotes within a query. The query is probably failing with an "unknow column" error. The PDO options (what options!) don't implement exception reporting.

Oh, definitely got errors but perhaps we are showing him/her some better coding style with corrections to boot!

I really hate whoever first thought it was a good idea to use php tags inside of some html code.  Such a confusing way to put elements together instead of staying in php.   People have got to hate that when they first start using it but they continue on because they don't know of an easier way at this early stage of their programmer development....

Edited by ginerjm
$sql = "SELECT * FROM agencies_data WHERE agency_user =:username";

$stmt = $db->prepare($sql); // $db is the PDO Connection

$stmt->execute([':username' => $_POST['user']); // I am 99 percenct certain : in :username is not needed / just for clarity. 

while ($row = $stmt->fetch(PDO::FETCH_ASSOC) {
  // Process results though I do not understand having a form inside a
  // form that has been submitted
}

I would concentrate in getting  PDO  working then onward to the logic of what you are trying to accomplish.

I would pull the record one at a time to edit if that is what you are trying to accomplish?

$sql = "SELECT * FROM agencies_data WHERE agency_user =:username";

$stmt = $db->prepare($sql); // $db is the PDO Connection

$stmt->execute([':username' => $_POST['user']); // I am 99 percenct certain : in :username is not needed / just for clarity.

$result = $stmt->fetch(PDO::FETCH_ASSOC)
<input class="form-control" type="text" name="oid" value="<?= $result['agency_user'] ?>" >

though that would mean you have to modify the code somewhere else.

Edited by Strider64
  • Like 1

In this page of the PHP manual there is ample evidence of parms referenced without the colon.

https://www.php.net/manual/en/pdostatement.execute.php

Doesn't that make this choice documented?

so, now it is in the documentation. that's only in the latest. all previous, for the past ~17 years (i just checked), shows only the : usage and there's no change note for when the documentation change was made, only the now, optional comments in the examples. use at your own risk.

i don't know why people are still typing out the names, multiple times, for each place-holder in each query. named place holders only exist inside the PDO driver, where php converts them to positional place holders before sending the information to the database server. it's a lot of unnecessary typing and then extra processing for php.

Edit: here's something even more sad about this documentation change. in the bindParam and bindValue documentation, this same change was made in the examples, but the definition of the parameter wasn't changed and still states -

Quote

this will be a parameter name of the form :name. 

 

Edited by mac_gyver

Hello Guys!

I'm sorry for being a bit late, it's just because of exams that's why I cannot connect to keep learning more from you as I can see in your comment too much infos to save. I can't tell you how much I'm happy for all of this content you have posted, Thank you for your help I've noticed a lot of things here which means I must keep learning and try my best to understand more about php.

I've tried all of your codes and nothing has work for me which absolutely means the problem is from me that's why I need your help in terms of explaining what mistakes I did till now. I will post full content to explain you more about my issue.

I've analyzed all your codes and mine too. and I guess it can be made without the use of database actualy, if the user is logged in so I will just take his password which is a text code named "pasword" and insert it inside the input's value => BUT IT DIDN'T WORK WITH ME (-_-)

as you can see guys below I want to send a user after he logged in to another page which is called "formulaire" and recuperate the values there. You can notice there is no extension after the name's file because I'm working with .htaccess file and a redirection function so everyting works fine for me.

 

login.php

<?php

if (isset($_POST['submit'])) {
        $data = new CentersController();
        $data->authCenter(); //this method is to let the user login after pressing the submit btn. and it works fine.
}

//This include shows alerts in case the user type a wrong username or password.
include('./views/includes/alerts.php');

?>

<section class="login-dark">
    <form method="post" action="formulaire"> 
      <div class="illustration"><i class="icon ion-ios-locked-outline"></i></div>
        <div class="mb-3">
            <input class="form-control" type="text" name="user" placeholder="User">
        </div>
        <div class="mb-3">
          
          <?php //This a code as a text. I've just named it as "password" so it's not a password type in case you tought I'm wrong in input's type.  ?>
            <input class="form-control" type="text" name="password" placeholder="Action code">
        </div>
        <div class="mb-3">
            <button class="btn btn-primary d-block w-100" type="submit" name="submit">LOGIN</button>
        </div>
    </form>
</section>

 

And here is the other file:

 

formulaire.php

<?php //You can notice here there is no php code, because after testing all of your codes so I just removed everything to give you a clean view.  ?>

<div class="container" style="margin-top: 12px;">
        <div style="background: #f8f8f8;padding: 36px;border-radius: 38px;">
            <div class="row justify-content-center align-items-center">
                <div class="col-8">
                    <form method="post" action="sendingData">
                        <h2 class="text-center" style="padding: 24px;"><strong>Formulaire d'insértion.</strong></h2>
                        <div class="mb-3">
                            <select class="form-select" required name="civilite">
                                <optgroup label="Civilité">
                                    <option value="1" selected="">Monsieur</option>
                                    <option value="2">Madame</option>
                                    <option value="3">Mademoiselle</option>
                                </optgroup>
                            </select>
                        </div>
                        <div class="row">
                            <div class="col">
                                <div class="mb-3">
                                    <input class="form-control" type="text" name="nom" placeholder="Nom" required=""></div>
                            </div>
                            <div class="col">
                                <div class="mb-3">
                                    <input class="form-control" type="text" name="prenom" placeholder="Prénom" required=""></div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <input class="form-control" type="text" name="telephone" placeholder="Téléphone" required=""></div>
                        <div class="mb-3">
                            <input class="form-control" type="email" name="email" placeholder="Email" required></div>
                        <div class="mb-3">
                            <input class="form-control" type="text" name="codepostal" placeholder="Code postal" required></div>
                        <div class="mb-3">
                            <select class="form-select" required name="imposition">
                                <optgroup label="Imposition">
                                    <option value="1" selected="">Non imposable</option>
                                    <option value="2">Moins de 2000€</option>
                                    <option value="3">Moins de 2500€</option>
                                    <option value="4">Entre 2500€ et 3000€</option>
                                    <option value="5">Entre 3000€ et 5000€</option>
                                    <option value="6">Entre 5000€ et 10000 €</option>
                                    <option value="7">Plus de 10000€</option>
                                </optgroup>
                            </select>
                        </div>
                        <div class="mb-3">
<?php //So here is the problem as I told you before, I can't show the text typed in login password field => inside this field's value ?>
                        <input class="form-control" type="text" name="oid" value="" >

                        </div>
                        <div class="d-lg-flex justify-content-lg-center align-items-lg-center mb-3">
                            <button class="btn btn-success d-block w-100" type="submit" style="margin-right: 10px;margin-left: 10px;">ADD</button>
                            <a href="<?php echo BASE_URL; ?>clogout" class="btn btn-light d-block w-100" style="margin-right: 10px;margin-left: 10px;">LOGOUT</a>
                        </div>
                    </form>
                </div>
                <div class="col-4">
                    <div style="background: url(&quot;assets/img/nature.jpg&quot;) center / cover no-repeat;height: 476px;border-radius: 30px;"></div>
                </div>

            </div>
        </div>
    </div>

 

Thank you guys for your time, I appreciate all of your answers and your corrections.

42 minutes ago, uumer93 said:

because I'm working with .htaccess file

have you checked in formulaire.php if there's $_POST data at all? add var_dump($_POST);

next, why do you have a form in the login.php page that's going to another page with more form fields? you are creating a bad user experience, requiring the user to push more buttons and fill in fields, then if the username/password is not valid, you will need to go back to the login form, then go to the formulaire form to reenter the data again.

also, the php code is dealing with the user/username. you have now stated this field in the second form is for a password value. please clarify?

in short, what is the overall stated purpose of doing this? it looks like the formulaire data is profile information, that would  be requested when a user registers, not when a user logs in.

Edited by mac_gyver
21 minutes ago, Barand said:

Thank you, I've tried to print data and nothing is showed

I've used if submit is clicked then print data as value and as a result I got a hidden input.
And I 've try to show it directly without if statement I got this warning result => Undefinned array key.

6 minutes ago, mac_gyver said:

have you checked in formulaire.php if there's $_POST data at all? add var_dump($_POST);

next, why do you have a form in the login.php page that's going to another page with more form fields? you are creating a bad user experience, requiring the user to push more buttons and fill in fields, then if the username/password is not valid, you will need to go back to the login form, then go to the formulaire form to reenter the data again.

also, the php code is dealing with the user/username. you have now stated this field in the second form is for a password value. please clarify?

in short, what is the overall stated purpose of doing this? it looks like the formulaire data is profile information, that would  be requested when a user registers, not when a user logs in.

I've tried this and the result is an empty array => array(0) { }

 

to explain more, The formulaire page is a page you cannot use if you are not connected and it is not a register page.

So the main idea here is let the user connect using the login form
Then send the user to a new page that contains a form to let them insert data that will be sent via api to client's server and this is not the problem

The problem is impossible to store the value entred inside password field that is located in login.php page and show it as a value inside oid field located in formulaire.php page

And the array is 0 Why ?

10 minutes ago, mac_gyver said:

in short, what is the overall stated purpose of doing this? it looks like the formulaire data is profile information, that would  be requested when a user registers, not when a user logs in.

The normal convention is that only registered users can log in. You appear to be adding a "Catch 22" dimension to your application in that you have to log in in order to register.

it's pretty apparent that your url rewriting is not working (is probably a redirect) and there's no $_POST data for the code to use. 

2 minutes ago, uumer93 said:

So the main idea here is let the user connect using the login form
Then send the user to a new page that contains a form to let them insert data that will be sent via api to client's server and this is not the problem

No. the end result of the login process is to remember who the logged in user is, by storing the user id in a session variable. you would then use the existence of a remembered, logged in user to display any logged in specific navigation links, form, and enable the form processing code on a page.

I think the problem is from the function or inside the controller :

 

CentersController.php

<?php
public function authCenter(){
		if (isset($_POST['submit'])) {
			$data = array(
				'agency_user'=>$_POST['user'],
				'action_code'=>$_POST['password']
			);
			$result = Center::loginC($data);
			if ($result->agency_user === $_POST['user'] && $result->action_code === $_POST['password']) {
				$_SESSION['logged'] = true;
				$_SESSION['username'] = $result->agency_user;
				Redirect::to('formulaire');
			}else{
				Session::set('error','Utilisateur ou mot de passe est incorrect');
				Redirect::to('login');
			}
		}
	}
?>

 

And

Center.php

<?php
static public function loginC($data){
		$agency_user = $data['agency_user'];
		try {
			$query = 'SELECT * FROM agencies_data WHERE agency_user=:agency_user';
			$stmt = DB::connect()->prepare($query); 
			$stmt->execute(array(":agency_user"=>$agency_user));
			$usuario = $stmt->fetch(PDO::FETCH_OBJ);
			return $usuario;
			if ($stmt->execute()) {
				return 'ok';
			}
			} catch (PDOException $e) {
			echo 'Erreur '.$e->getMessage();
		}
	}
?>

 

I've tried to add $password = $data['password'] as a var and then insert it inside array located in Center.php but still got an empty Array in formulaire.php page.

30 minutes ago, uumer93 said:

I think the problem is from the function or inside the controller :

it's not. you don't have a clear definition of what the work-flow/steps are, so you haven't been successful at writing code that does what you want.

the work-flow/steps are -

  1. a user sits down at a computer/device and logs in. this stores the logged in user id in a session variable.
  2. a logged in user can now see and do things that requires a logged in user. this tests/uses the user id in the session variable.
  3. one of the things they can see and do is see/navigate to the formulaire form, fill it in, and submit it. this also tests/uses the user id in the session variable.

the form processing code for each form should be on the same page as the form. this results in the simplest code and the best user experience (you can repopulate the form field values upon an error so that the user doesn't need to keep reentering data over and over.) the way to get the form to submit to the same page it is on is to lever the entire action='...' attribute out of the form tag.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.