Jump to content

Any ideas why code is inserting just one character of each value?


sonnieboy

Recommended Posts

<?php

// Database connection
$conn = mysqli_connect("localhost","myuser","mypass","myDB");
if(!$conn) {
die('Problem in database connection: ' . mysql_error());
}

// Data insertion into database

$query = 'INSERT INTO `myDB`.`employees` ( `employeename`, `ttitle`, `email` )'
     . ' VALUES ( ? , ? , ? )';
if( $sth = mysqli_prepare($conn,$query) ) {
   mysqli_stmt_bind_param($sth,'sss'
      ,$_POST["employeename"]
      ,$_POST["ttitle"]
      ,$_POST["email"]
   );
   if( mysqli_stmt_execute($sth) ) {
     echo 'Successfully created employee record;';
   } else {
      printf("Error: %s\n",mysqli_stmt_error($sth));
   }
} else {
   printf("Error: %s\n",mysqli_connect_error($conn));
}

$lastID = mysqli_insert_id($conn);  //Insert this primary key from employees table to the myTable


$sql = 'INSERT INTO `myDB`.`myTable` ( `employeeID`'
     . ', `sourcename`, `sourceaddress`, `income`,`spousename`,`spouseAddress`,`spouseincome` )'
     . ' VALUES ( ? , ? , ? , ? , ? , ? , ? )';

if( $sth = mysqli_prepare($conn,$sql) ) {
    mysqli_stmt_bind_param($sth, 'sssssss',
        $lastID,
        $sourcename,
        $sourceaddress,
        $income,
        $spousename,
        $spouseAddress,
        $spouseIncome);

    for ($i=0; $i<count($_POST['sourcename']); $i++)
    {
        $sourcename = $_POST['sourcename'][$i];
        $sourceaddress = $_POST['sourceaddress'][$i];
        $income = $_POST['income'][$i];
        $spousename = $_POST['spousename'][$i];
        $spouseAddress = $_POST['spouseAddress'][$i];
        $spouseIncome = $_POST['spouseIncome'][$i];
  }
var_dump($_POST);
   if( mysqli_stmt_execute($sth) ) {
     echo '<h1>Success!</h1><br>Your record successfully submitted <br><br>");';
   } else {
      printf("Error: %s\n",mysqli_stmt_error($sth));
   }
} else {
   printf("Error: %s\n",mysqli_connect_error($conn));
}
?>

Greetings again.

 

I have made some good strides with this project I am very close to the finish line.

 

Right now, all my errors are gone and code is inserting data into the database.

 

However, I still have two problems.

 

One, when create for instance three records expecting all three to be inserted into the database, only one record gets inserted instead of three.

 

Second, of the record that got inserted, only the first character of each value gets inserted.

 

Others are cut off.

 

I tried var_dump() but no truncation.

 

Can you please assist again if possible?

 

Thank you.

 

 

Link to comment
Share on other sites

hmm, excellent point.

 

This is the markup on previous page where the FOR loop is based on.

 

Based on the point you just made, I revisited this page and notice that I had this:

<form action='final.php' method = 'POST'>
<?phpforeach ($rowIDs as $id) { ?>
<input type="hidden" name="employeename" value="<?php echo $employeename; ?>">
<input type="hidden" name="ttitle" value="<?php echo $ttitle; ?>">
<input type="hidden" name="email" value="<?php echo $email; ?>">
<php? } ?>
<input type="hidden" name="sourcename" value="<?php echo $_POST['sourcename' . $id]; ?>">
<input type="hidden" name="sourceaddress" value="<?php echo $_POST['sourceaddress' . $id]; ?>">
<input type="hidden" name="income[]" value="<?php echo $_POST['income' . $id]; ?>">
<?phpforeach ($row2IDs as $id) { ?>
<input type="hidden" name="spousename" value="<?php echo $_POST['spousename' . $id]; ?>">
<input type="hidden" name="spouseAddress" value="<?php echo $_POST['spouseAddress' . $id]; ?>">
<input type="hidden" name="spouseIncome" value="<?php echo $_POST['spouseIncome' . $id]; ?>">
<php? } ?>
<input type="submit" value="submit" />
</form>

I removed them and now have each as this:

<input type="hidden" name="sourcename[]" value="<?php echo $_POST['sourcename']; ?>">

with their various hidden form names of course. Now, the names are displaying in full but I still have the issue of one row instead of two or more.

 

This is the only issue that I have now.

 

Between the hidden form fields and the FOR loop, something is causing this immense grief.

 

I am hopeful you gurus can help me ride this out.

 

Thanks to you guys here for the continued assistance.

Link to comment
Share on other sites

Change your form field names to this structure

name="employee[<?=$id?>][employeename]"
name="employee[<?=$id?>][ttitle]"
name="employee[<?=$id?>][email]"

 . . . etc.

 

Then on your form processing code you can do this

$sql = "INSERT INTO table_name (employeename1, ttitle, email)
        VALUES(?, ?, ?)";
$sth = mysqli_prepare($conn,$sql
mysqli_stmt_bind_param($sth, 'sssssss',
    $employeename,
    $ttitle,
    $email);

//Iterate through each RECORD in the post data
foreach($_POST['employee'] as $employee)
{
    //Extract array fields into variables for prepared statement
    list($employeename, $ttitle, $email) = $employee;
    //Execute the query
    mysqli_stmt_execute($sth)
}

Note, I've left off a lot of error handling on this for brevity, but you should be able to see the concept.,

Edited by Psycho
Link to comment
Share on other sites

Hi Psycho,

 

Thank sir.

 

Just an fyi,

 

employeename, ttitle and email are not array.

 

These are displayed just once.

That's why they don't have the [] thing on them.

 

Do I still need to do them as you suggested.

 

I am so desperate to get working so I can catch up on sleep for just one night.

Link to comment
Share on other sites

Sorry, that was a failed attempt at recreating the reason for the one character record insert.

 

I just put the foreach at wrong place.

 

My sincere apology for that.

 

But going back to Psycho's code snippet, when I apply it to my part of the code that is an array as shown again, does his code replace this version?

 

Sorry but I am trying to understand how it replaces my version:

 

Anything that reduces confusion on my part only helps me to get this working finally.

 

Thanks all

    for ($i=0; $i<count($_POST['sourcename']); $i++)
    {
        $sourcename = $_POST['sourcename'][$i];
        $sourceaddress = $_POST['sourceaddress'][$i];
        $income = $_POST['income'][$i];
        $spousename = $_POST['spousename'][$i];
        $spouseAddress = $_POST['spouseAddress'][$i];
        $spouseIncome = $_POST['spouseIncome'][$i];
  }

Link to comment
Share on other sites

Great helpers,

 

Just to be sure that I followed your instructions correctly,

 

Here is the markup:

<input type="hidden" name="employeename" value="<?php echo $employeename; ?>">
<input type="hidden" name="ttitle" value="<?php echo $ttitle; ?>">
<input type="hidden" name="email" value="<?php echo $email; ?>">
<input type="hidden" name="sname[<?=$id?>][sourcename" value="<?php echo $_POST['sourcename']; ?>">
<input type="hidden" name="sname[<?=$id?>][sourceaddress]" value="<?php echo $_POST['sourceaddress']; ?>">
<input type="hidden" name="sname[<?=$id?>][income]" value="<?php echo $_POST['income']; ?>">
<input type="hidden" name="sname[<?=$id?>][spousename]" value="<?php echo $_POST['spousename']; ?>">
<input type="hidden" name="sname[<?=$id?>][spouseAddress]" value="<?php echo $_POST['spouseAddress']; ?>">
<input type="hidden" name="sname[<?=$id?>][spouseIncome]" value="<?php echo $_POST['spouseIncome']; ?>">

Then the processing page:

$sql = 'INSERT INTO `myDB`.`wp_myTable` ( `employeeID`'
     . ', `sourcename`, `sourceaddress`, `income`,`spousename`,`spouseAddress`,`spouseIncome` )'
     . ' VALUES ( ? , ? , ? , ? , ? , ? , ? )';

if( $sth = mysqli_prepare($conn,$sql) ) {
    mysqli_stmt_bind_param($sth, 'sssssss',
        $lastID,
        $sourcename,
        $sourceaddress,
        $income,
        $spousename,
        $spouseAddress,
        $spouseIncome);

    foreach($_POST['sname'] as $sname)
    {
       list($sourcename, $sourceaddress, $income, $spousename, $spouseAddress, $spouseIncom) = $sname;
  }

But I am getting:

Notice: Undefined offset: 1 in C:\xampp\htdocs\closures\forms\final.php on line 47

Edited by sonnieboy
Link to comment
Share on other sites

You need to learn basic debugging skills like how to inspect variables:

var_dump($sname);

This tells you exactly how $sname looks like, so you can stop guessing. Hint: It's an associative array.

 

You're also missing a closing bracket in the sourcename parameter, and your code has XSS vulnerabilities all over the place.

Edited by Jacques1
Link to comment
Share on other sites

Notice: Undefined offset: 0 in C:\xampp\htdocs\losures\forms\final.php on line 47
 array(6) { ["sourcename"]=> string(14) "Penny Hardaway" ["sourceaddress"]=> string(16) "21 Martin Street" ["income"]=> string(5) "71000" ["spousename"]=> string(14) "Andrew Jackson" ["spouseAddress"]=> string(17) "1 Presidents Road" ["spouseIncome"]=> string(6) "201000" } Error: Column 'sourcename' cannot be null 

I do have var_dump(...) on that code but you are right; what good is if I don't use it.

 

Even after fixing sourcename, I am still getting the error that sourcename cannot be blank.

 

I don't understand this.

 

I mean I know what the error means but I don't understand why.

 

This is what var_dum($sname) shows.

 

One thing that stands out is that I entered two sourcenames, two source addresses, two incomes, two spousenames, two spouseAddresses and two spouseIncomes but only one of each is showing up.

 

My gosh!

 

 

Link to comment
Share on other sites

As the error clearly states, you're trying to access the index 0 of an associative array (due to the list construct). That's obviously not possible.

 

You have an associative array, so the keys are strings:

$sourceStmt = $databaseConnection->prepare('
    INSERT INTO ...
');

foreach ($_POST['sname'] as $source)
{
    $sourceStmt->bind_param('issssss', $lastID, $source['sourcename'], $source['sourceaddress'], ...);
    $sourceStmt->execute();
}

Link to comment
Share on other sites

Man, as much as I truly, truly appreciate your help and time, I am officially fully confused now.

 

Do I get rid the following right after INSERT(..) VALUES(..) and replace $sourcestmt=$databaseonnection(...)?

 

And do I replace the line that begins with mysqli_stmt_bind_param(...$sth,'sssssss'... with your latest foreach?

 

I cant thank you enough for your help

if( $sth = mysqli_prepare($conn,$sql) ) {
  
mysqli_stmt_bind_param($sth, 'sssssss', 
Link to comment
Share on other sites

 

As the error clearly states, you're trying to access the index 0 of an associative array (due to the list construct). That's obviously not possible.

 

You have an associative array, so the keys are strings

 

Well, that's my fault. I use PDO and would just use the $sname in the execute statements instead of defining the values as defined variables. In my haste I threw in the list() function not thinking it only worked for numerically indexed arrays.

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.