Jump to content

Cannot insert $id into php pdo array


ace2go
Go to solution Solved by cyberRobot,

Recommended Posts

I have the following code to pass the $id value(integer) :

    $id = null;
    if ( !empty($_GET['id'])) {
        $id = $_REQUEST['id'];
    }
    
    if ( null==$id ) {
        header("Location: customers.php");
    }

Passes successfully according to this code in the body :

                        <?php
print_r($_GET);
if($_GET["id"] === "") echo "a is an empty string\n";
if($_GET["id"] === false) echo "a is false\n";
if($_GET["id"] === null) echo "a is null\n";
if(isset($_GET["id"])) echo "a is set\n";
if(!empty($_GET["id"])) echo "a is not empty";
?>

This code tries to insert data into a workorder table :

if ($valid) {
            $pdo = Database::connect();
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $sql = "INSERT INTO workorder (name, date, installer, salesman, category, status) values('$id', ?, ?, ?, ?, ?);";
            $q = $pdo->prepare($sql);
            $q->execute(array($date,$installer,$salesman,$category,$status));
            Database::disconnect();
            header("Location: workorders.php");
        }

Breakdown : the $date, $installer, $salesman, $category, $status are retrieved from the form(and inserted fine), the $id is called from a prior page, gets a correct value, but is not accepted into the table.  Does anyone have any ideas as to why that is? 

Link to comment
Share on other sites

You're mixing and matching SQL approaches. Replace this bit:

$sql = "INSERT INTO workorder (name, date, installer, salesman, category, status) values('$id', ?, ?, ?, ?, ?);";
$q = $pdo->prepare($sql);
$q->execute(array($date,$installer,$salesman,$category,$status));

with this:

$sql = "INSERT INTO workorder (name, date, installer, salesman, category, status) values(?, ?, ?, ?, ?, ?);";
$q = $pdo->prepare($sql);
$q->execute(array($id,$date,$installer,$salesman,$category,$status));

And it should work.

 

As an aside, why are you checking the id value in _GET and then assigning it from _REQUEST? If somehow there's an 'id' index in both _GET and _POST, one of them is going to overwrite the other. If the value is set in _GET, pull it from _GET.

Link to comment
Share on other sites

@maxxd How do I do this?  the values in the array are from form fields that the user sends upon clicking the "submit" button.  $id is an integer called from a prior page.  I tried your code, and it does not even insert the array.

Link to comment
Share on other sites

I can see the existence of $_GET['id'], the code I need is to set $id in the same script as the PDO query, that is already calling the other values from a form

 

I think I see what you're saying now. *I think*.

 

So, you're saying the initial two blocks of code in your original post are on the page with the form output, and the third block of code is on the processing page (the value of the form action property), correct?

 

My question is, where in the script are $date, $installer, $salesman, $category, and $status set and how? Are the values passed from the form via _POST or _GET? The id value should be in there, assuming it's in the form somewhere (this is usually done with a hidden field in the form itself or pulled directly from a session variable).

 

Perhaps it would help if you posted a bit more code, like the form itself and the code before the "if($valid){" line.

Link to comment
Share on other sites

my code as of yet :

<?php

    require 'database.php';
    
    $id = null;
    if ( !empty($_GET['id'])) {
        $id = $_REQUEST['id'];
    }
    
    if ( null==$id ) {
        header("Location: customers.php");
    }

    if ( !empty($_POST)) {
        // keep track validation $
        
        $dateError        = null;
        $installerError   = null;
        $salesmanError    = null;
        $categoryError    = null;
        $statusError      = null;
        
        // keep track post values
        
        $id          = $POST['name'];
        $date        = $_POST['date'];
        $installer   = $_POST['installer'];
        $salesman    = $_POST['salesman'];
        $category    = $_POST['category'];
        $status      = $_POST['status'];

        
        // validate input
        $valid = true;
        if (empty($date)) {
            $dateError = 'Please enter Date';
            $valid = false;
        }
        
        if (empty($installer)) {
            $installerError = 'Please enter Installer';
            $valid = false;
        }
        
        if (empty($salesman)) {
            $salesmanError = 'Please enter Salesman';
            $valid = false;
        }
        
        if (empty($category)) {
            $categoryError = 'Please enter Category';
            $valid = false;
        }
        
        if (empty($status)) {
            $statusError = 'Please enter Status';
            $valid = false;
        }
        
        // insert data
        if ($valid) {
            $pdo = Database::connect();
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $sql = "INSERT INTO workorder (name, date, installer, salesman, category, status) values($id, ?, ?, ?, ?, ?);";
            $q = $pdo->prepare($sql);
            $q->execute(array($date,$installer,$salesman,$category,$status));

            Database::disconnect();
            header("Location: workorders.php");
        }
    }
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link   href="css/bootstrap.min.css" rel="stylesheet">
    <script src="js/bootstrap.min.js"></script>
</head>

<body>
    <div class="container">
    
                <div class="span10 offset1">
                    <div class="row">
                        <h3>Create a Workorder</h3>
                        <?php
print_r($_GET);
if($_GET["id"] === "") echo "a is an empty string\n";
if($_GET["id"] === false) echo "a is false\n";
if($_GET["id"] === null) echo "a is null\n";
if(isset($_GET["id"])) echo "a is set\n";
if(!empty($_GET["id"])) echo "a is not empty";
?>
                    </div>
            
                    <form class="form-horizontal" action="createworkorder.php" method="post">
                      <div class="control-group <?php echo !empty($dateError)?'error':'';?>">
                        <label class="control-label">Date</label>
                        <div class="controls">
                              <input name="date" type="text"  placeholder="Date" value="<?php echo !empty($date)?$date:'';?>">
                              <?php if (!empty($dateError)): ?>
                                  <span class="help-inline"><?php echo $dateError;?></span>
                              <?php endif; ?>
                        </div>
                      </div>
                      <div class="control-group <?php echo !empty($installerError)?'error':'';?>">
                        <label class="control-label">Installer</label>
                        <div class="controls">
                              <input name="installer" type="text" placeholder="Installer" value="<?php echo !empty($installer)?$installer:'';?>">
                              <?php if (!empty($installerError)): ?>
                                  <span class="help-inline"><?php echo $installerError;?></span>
                              <?php endif;?>
                        </div>
                      </div>
                      <div class="control-group <?php echo !empty($salesmanError)?'error':'';?>">
                        <label class="control-label">Salesman</label>
                        <div class="controls">
                              <input name="salesman" type="text"  placeholder="Salesman" value="<?php echo !empty($salesman)?$salesman:'';?>">
                              <?php if (!empty($salesmanError)): ?>
                                  <span class="help-inline"><?php echo $salesmanError;?></span>
                              <?php endif;?>
                        </div>
                      </div>
                      <div class="control-group <?php echo !empty($categoryError)?'error':'';?>">
                        <label class="control-label">Category</label>
                        <div class="controls">
                              <input name="category" type="text"  placeholder="Category" value="<?php echo !empty($category)?$category:'';?>">
                              <?php if (!empty($categoryError)): ?>
                                  <span class="help-inline"><?php echo $categoryError;?></span>
                              <?php endif; ?>
                        </div>
                      </div>
                      <div class="control-group <?php echo !empty($statusError)?'error':'';?>">
                        <label class="control-label">Status</label>
                        <div class="controls">
                              <input name="status" type="text"  placeholder="Status" value="<?php echo !empty($status)?$status:'';?>">
                              <?php if (!empty($statusError)): ?>
                                  <span class="help-inline"><?php echo $statusError;?></span>
                              <?php endif; ?>
                        </div>
                      </div>
                      
                      <div class="form-actions">
                          <button type="submit" class="btn btn-success">Create</button>
                          <a class="btn" href="workorders.php">Back</a>
                        </div>
                    </form>
                </div>
                
    </div> <!-- /container -->
  </body>
</html>
Edited by ace2go
Link to comment
Share on other sites

Just to clarify, is the code shown in Reply 7 in a page called "createworkorder.php"?

 

Also, is there a step before the user fills out the form? Does that step pass a GET variable called "id"?

 

Note that if you're trying to pass the ID along with the form submission, you need to include it in the form somehow. You could, for example, add a hidden form field where $id / $_GET['id'] is the value.

Link to comment
Share on other sites

how do I add that hidden form field?  If I pass it along with the form results(in the form), how do I retain the value that was presented from the other page? 

 

@cyberRobot : Yes, the page is called "createworkorder.php", the values are passed from a page called "customers.php"

Edited by ace2go
Link to comment
Share on other sites

  • Solution

how do I add that hidden form field?  If I pass it along with the form results(in the form), how do I retain the value that was presented from the other page? 

 

Basically, you would add something like this:

<input type="hidden" name="name" value="<?php echo htmlentities($id); ?>">
 
 
                      <div class="form-actions">
                          <button type="submit" class="btn btn-success">Create</button>
                          <a class="btn" href="workorders.php">Back</a>
                        </div>
                    </form>
 
 
Note: with the hidden field added, you'll need to modify the code for setting $id to something like this:
<?php
//...
 
if(!empty($_GET['id']))      { $id = $_GET['id'];  }
elseif(!empty($_POST['id'])) { $id = $_POST['id']; }
else                         { $id = null;         }
 
//...
?>
 
That way the header() function doesn't get triggered. You'll also need to get rid of the following line so you're not overwriting $id:
$id          = $POST['name'];
Link to comment
Share on other sites

OK - there's a couple things I see right off the bat. First, your form doesn't have fields named 'name' or 'id', so those aren't getting passed via $_POST. You're checking $_GET['id'], then assigning $_REQUEST['id'] to $id, then overwriting that value with an apparently non-existent value: $_POST['name']. Where you've got the output checks for $_GET['id'] right before your form, add the following:

print(empty($id) ? "\$id is empty or null" : "This is \$id: {$id}");

and that should output '$id is empty or null'.

 

You're submitting the form to the same page via $_POST. Because you've specifically given the form an 'action' parameter, that means any $_GET variables aren't being carried over - check the location bar before and after you hit the submit button. You'll need to create a hidden input field and assign the value of 'id' to that field. Right after your opening form tag, insert this:

<input type='hidden' name='id' value='<?= htmlentities($_GET['id']); ?>' />

Assuming that there's a value in $_GET['id'], when you submit the form from that page, you can access the value using

$id = $_POST['id'];

Now, if you omit the 'action' parameter of the form, it'll post to itself by default - the interesting thing here is that it means the URL will still be intact including your $_GET variables. So, if you remove the "action='createworkorder.php'" parameter from your opening form tag, things should work as expected right up until the point where you overwrite the value with $_POST['name'], which (as stated above) doesn't actually exist.

Link to comment
Share on other sites

Now, if you omit the 'action' parameter of the form, it'll post to itself by default - the interesting thing here is that it means the URL will still be intact including your $_GET variables. So, if you remove the "action='createworkorder.php'" parameter from your opening form tag, things should work as expected right up until the point where you overwrite the value with $_POST['name'], which (as stated above) doesn't actually exist.

 

Technically, it's being overwritten by $POST['name'] which will never work with the form. Note the missing underscore.  :tease-01:

Edited by cyberRobot
  • Like 1
Link to comment
Share on other sites

Full working code :

<?php

    require 'database.php';
    
if(!empty($_GET['name']))      { $name = $_GET['name'];  }
elseif(!empty($_POST['name'])) { $name = $_POST['name']; }
else                         { $name = null;         }
 

    if ( !empty($_POST)) {
        // keep track validation $
        
        $dateError        = null;
        $installerError   = null;
        $salesmanError    = null;
        $categoryError    = null;
        $statusError      = null;
        
        // keep track post values
        
        $date        = $_POST['date'];
        $installer   = $_POST['installer'];
        $salesman    = $_POST['salesman'];
        $category    = $_POST['category'];
        $status      = $_POST['status'];

        
        // validate input
        $valid = true;
        if (empty($date)) {
            $dateError = 'Please enter Date';
            $valid = false;
        }
        
        if (empty($installer)) {
            $installerError = 'Please enter Installer';
            $valid = false;
        }
        
        if (empty($salesman)) {
            $salesmanError = 'Please enter Salesman';
            $valid = false;
        }
        
        if (empty($category)) {
            $categoryError = 'Please enter Category';
            $valid = false;
        }
        
        if (empty($status)) {
            $statusError = 'Please enter Status';
            $valid = false;
        }
        
        // insert data
        if ($valid) {
            $pdo = Database::connect();
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $sql = "INSERT INTO workorder (name, date, installer, salesman, category, status) values(?, ?, ?, ?, ?, ?);";
            $q = $pdo->prepare($sql);
            $q->execute(array($name,$date,$installer,$salesman,$category,$status));

            Database::disconnect();
            header("Location: workorders.php");
        }
    }
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link   href="css/bootstrap.min.css" rel="stylesheet">
    <script src="js/bootstrap.min.js"></script>
</head>

<body>
    <div class="container">
    
                <div class="span10 offset1">
                    <div class="row">
                        <h3>Create a Workorder</h3>
                    </div>
            
                    <form class="form-horizontal" action="createworkorder.php" method="post">
                    <input type="hidden" name="name" value="<?php echo htmlentities($name); ?>">
                      <div class="control-group <?php echo !empty($dateError)?'error':'';?>">
                        <label class="control-label">Date</label>
                        <div class="controls">
                              <input name="date" type="text"  placeholder="Date" value="<?php echo !empty($date)?$date:'';?>">
                              <?php if (!empty($dateError)): ?>
                                  <span class="help-inline"><?php echo $dateError;?></span>
                              <?php endif; ?>
                        </div>
                      </div>
                      <div class="control-group <?php echo !empty($installerError)?'error':'';?>">
                        <label class="control-label">Installer</label>
                        <div class="controls">
                              <input name="installer" type="text" placeholder="Installer" value="<?php echo !empty($installer)?$installer:'';?>">
                              <?php if (!empty($installerError)): ?>
                                  <span class="help-inline"><?php echo $installerError;?></span>
                              <?php endif;?>
                        </div>
                      </div>
                      <div class="control-group <?php echo !empty($salesmanError)?'error':'';?>">
                        <label class="control-label">Salesman</label>
                        <div class="controls">
                              <input name="salesman" type="text"  placeholder="Salesman" value="<?php echo !empty($salesman)?$salesman:'';?>">
                              <?php if (!empty($salesmanError)): ?>
                                  <span class="help-inline"><?php echo $salesmanError;?></span>
                              <?php endif;?>
                        </div>
                      </div>
                      <div class="control-group <?php echo !empty($categoryError)?'error':'';?>">
                        <label class="control-label">Category</label>
                        <div class="controls">
                              <input name="category" type="text"  placeholder="Category" value="<?php echo !empty($category)?$category:'';?>">
                              <?php if (!empty($categoryError)): ?>
                                  <span class="help-inline"><?php echo $categoryError;?></span>
                              <?php endif; ?>
                        </div>
                      </div>
                      <div class="control-group <?php echo !empty($statusError)?'error':'';?>">
                        <label class="control-label">Status</label>
                        <div class="controls">
                              <input name="status" type="text"  placeholder="Status" value="<?php echo !empty($status)?$status:'';?>">
                              <?php if (!empty($statusError)): ?>
                                  <span class="help-inline"><?php echo $statusError;?></span>
                              <?php endif; ?>
                        </div>
                      </div>
                      
                      <div class="form-actions">
                          <button type="submit" class="btn btn-success">Create</button>
                          <a class="btn" href="workorders.php">Back</a>
                        </div>
                    </form>
                </div>
                
    </div> <!-- /container -->
  </body>
</html>

Thanks to everyone for their help!!!

Link to comment
Share on other sites

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.