Populating a pull down with a table, inserting into another, +1

  • (2 Pages)
  • +
  • 1
  • 2

23 Replies - 443 Views - Last Post: 03 February 2012 - 10:41 AM Rate Topic: -----

Topic Sponsor:

#1 MattRidge  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 27
  • Joined: 27-January 12

Populating a pull down with a table, inserting into another, +1

Posted 27 January 2012 - 07:33 AM

Hi, I am sorry this has to be my first post, but I am stuck on a script that works 80% of the way, and fails the other 20%... if you read below you will see my quandary. Thanks.

I have a code that has many fingers in it, with much musings about how to do what I am looking for it to do, unthankfully it does not. I am stuck at this point because my code skill does not reach this far, and I can't fix it on my own.. This originally started as a simple drop down menu, now it's become much more, and has gone well beyond my skill set it at now.

Here is what I am attempting to do:

In database Testbed I have two tables that are being interacted with this script.

The first is user the second is testbed.

The usertable has all the names that the pull down menu requires. These names reside in the field user.

The testbed table saves where the name selected in the pull down menu resides, it resides in field fab1

So originally the code is meant to do this:

The form this belongs to allows you to enter data and a make choices from a pull down menu. You select the name in the pull down menu, click submit, it posts to the testbed table under fab1 In this case the name is Andy Kahl which is meant to be in the first Fabricator slot. (the other two are for show right now) If a person needs to edit the name they select an edit option on another page, and a new page pops up with the data filled in that was entered into the testbedtable. This is what that page looks like: edit.php

The first name as said before is Andy Khal, the problem is that as you can see it's not showing up correctly.

This is a page just with the pull down menu script, and the rest to make it work.


<?php
require_once('tb/connectvars.php');
    $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
	$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); 
	$mysqli->select_db('testbed');



		echo '<div id="box4">';
echo '<h2>Fabricators</h2>';
			echo '<div id="fab1">';
if (!isset($_GET['id'])) {
    $query = "SELECT * FROM data WHERE id = '$id'";
  }
  else {
    $query = "SELECT * FROM data WHERE id = '$id'";
  }

$result = $mysqli->query("SELECT * FROM user"); 
echo "<select name='fab1'>\n";
while($row = $result->fetch_assoc())
{
    echo '<option value="' . $row['user'] . '"';
    if($row['user'] == $user)
    {
         echo ' selected';
    }
    echo '>' . $row['user'] . '</option>\n';
}
?>

<body>
<a href="http://kaboomlabs.com/testbed/box.php">Right Click and Save link as... for Code</a>

</body>



Now the problem is, at least I think it is, it does not access at any time the field $fab1 in the table testbed. Just user.So it doesn't know the name that it needs to pull and show as the original selection from the testbed table, from field fab1.

No I've attempted to get this working on my own, I don't want to use java or any other language to solve this if possible, but to me it seems like it is possible, but for whatever reason this seems like it has never been attempted before.

The reason I am doing this is because as you see on the original edit field there are companies in a pull down menu, there are hundreds of them. I am to use this script for that section as well, I don't want to manually edit the page so that it shows the name correctly, that will add hundreds of lines onto a code. I was hoping to have a table in where the names could be stored, a table where the name submitted would be posted, and an edit page which would pull the data from the posted table and say to the script, "The name in the posted table shows me this, make it so that when you pull the data from the name table that it shows this name as the choice, instead of --None-- first."..

But for some reason it seems impossible. I would not be asking for help if I could solve this on my own, so if anyone can help me it would be greatly appreciated.

Attached is a zip with all files required to make it work , so if you want to test it out on your own computer, please do.

Sorry, I made a mistake with the attachment, and I can't seem to find a way to edit it. I forgot to add the tables to the attachment. Here they are.

Attached File(s)

  • Attached File  post.zip (11.1K)
    Number of downloads: 10
  • Attached File  post.zip (13.18K)
    Number of downloads: 11


Is This A Good Question/Topic? 0
  • +

Replies To: Populating a pull down with a table, inserting into another, +1

#2 Jstall  Icon User is offline

  • Lurker
  • member icon

Reputation: 380
  • View blog
  • Posts: 961
  • Joined: 08-March 09

Re: Populating a pull down with a table, inserting into another, +1

Posted 27 January 2012 - 10:05 AM

Hi,

Forgive me, I may be off base on what you are trying to do, but I am going to base it off of this:\

Quote

The name in the posted table shows me this, make it so that when you pull the data from the name table that it shows this name as the choice, instead of --None-- first.


Assuming that the id that maps to the user is the id in your query string you would just need to do something like this:
$result = $mysqli->query("SELECT * FROM user"); 
echo "<select name='fab1'>\n";
while($row = $result->fetch_assoc())
{
    echo '<option value="' . $row['user'] . '"';
    //check to see if the primary key of the user table matches the id the query string
    if($row['userid'] == $_GET['id'])
    {
         echo ' selected';
    }
    echo '>' . $row['user'] . '</option>\n';
}



That being said it seems like your database schema may be a bit off. You shouldn't have three fields that hold the names of three possible users(I believe that is what fab1,fab2,fab3 fields are for now). Instead you should create an associative table that maps the user table to the testbed table.

user_testbed
--------------
user_testbed_id PK
userid FK
testbed FK


At the very least your fab1,fab2,fab3 fields should be foreign keys from the user table.

Hope this helps :)
Was This Post Helpful? 0
  • +
  • -

#3 MattRidge  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 27
  • Joined: 27-January 12

Re: Populating a pull down with a table, inserting into another, +1

Posted 30 January 2012 - 06:28 AM

View PostJstall, on 27 January 2012 - 10:05 AM, said:

Hi,

Forgive me, I may be off base on what you are trying to do, but I am going to base it off of this:\

Quote

The name in the posted table shows me this, make it so that when you pull the data from the name table that it shows this name as the choice, instead of --None-- first.


Assuming that the id that maps to the user is the id in your query string you would just need to do something like this:
$result = $mysqli->query("SELECT * FROM user"); 
echo "<select name='fab1'>\n";
while($row = $result->fetch_assoc())
{
    echo '<option value="' . $row['user'] . '"';
    //check to see if the primary key of the user table matches the id the query string
    if($row['userid'] == $_GET['id'])
    {
         echo ' selected';
    }
    echo '>' . $row['user'] . '</option>\n';
}



That being said it seems like your database schema may be a bit off. You shouldn't have three fields that hold the names of three possible users(I believe that is what fab1,fab2,fab3 fields are for now). Instead you should create an associative table that maps the user table to the testbed table.

user_testbed
--------------
user_testbed_id PK
userid FK
testbed FK


At the very least your fab1,fab2,fab3 fields should be foreign keys from the user table.

Hope this helps :)


Ok, I hate to ask this but how do I get it to make this happen?

Basically I have three fields with three different identifiers, fab1, fab2, and fab3, each one has it's own specific field in the database. The pull down menu is in another table all together.

What I want is that if a person's name (id#) if it needs to be that way, to be entered into the database, then the script to pull that data out and shows it as the option in the pull down menu, instead of the first line of the pull down menu...

Don't forget there are two tables.

Table 1 user.

Has id and user as the two tables, the pull down menu shows the user info, which are names, if need be when submitted I will have it save in table 2 the ID and pull the user name later.

Table 2 is testbed.

It has over 20 fields, the ones in question though are id, because each input of the table has to be unique. and fab1, fab2, and fab3, each one will have the data from the original pull down menu submitted, for now it shows names, but I will change it to show id numbers instead if need be.

There is an edit page which pulls the data from the table, it looks up the unique id number, and then pulls the data from said line. What needs to be done is this. It sees the name (or id) and instead of showing --None-- which is ID 1, from the pull down list, it needs to show the name that is in fab1, fab2, or fab3 as it's option in the pull down menu, so the person viewing the edit page will know that there is a name already in there. If there is none, well --None-- shows first.

Does this make any sense now?

I'm sorry if I am not getting what you say, but after a weekend of working on this, and attempting to learn what I need to, as someone told me to do in another form, I am more lost in what I need to do now then I ever was.
Was This Post Helpful? 0
  • +
  • -

#4 Jstall  Icon User is offline

  • Lurker
  • member icon

Reputation: 380
  • View blog
  • Posts: 961
  • Joined: 08-March 09

Re: Populating a pull down with a table, inserting into another, +1

Posted 30 January 2012 - 11:32 AM

Hi,

Ok, first of all, what is the id in the query string supposed to be? Is is supposed to be the id of a record in the testbed table?

The database schema changes I suggested have to do with normalization. You would not want to store a character representation of the user's name as a field in the testbed table, you would want to store the id of a user. Then you would use a join in your query to pull the data related to the user directly from the user table. You may want to read up on normalization. Here is an excellent tutorial on the subject.
Was This Post Helpful? 0
  • +
  • -

#5 MattRidge  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 27
  • Joined: 27-January 12

Re: Populating a pull down with a table, inserting into another, +1

Posted 30 January 2012 - 01:22 PM

View PostJstall, on 30 January 2012 - 11:32 AM, said:

Hi,

Ok, first of all, what is the id in the query string supposed to be? Is is supposed to be the id of a record in the testbed table?

The database schema changes I suggested have to do with normalization. You would not want to store a character representation of the user's name as a field in the testbed table, you would want to store the id of a user. Then you would use a join in your query to pull the data related to the user directly from the user table. You may want to read up on normalization. Here is an excellent tutorial on the subject.

Thanks for the link, I'll read up on it, but this is what I am doing now.

Ok, to give you an idea here:

http://kaboomlabs.co...ed/pulldown.php

This is pull down menu 1. Here is it's script:


<?php
  require_once('tb/connectvars.php');
      $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
    or die('Error connecting to MySQL server.');


if (isset($_POST['submit'])) {
    $fab1= mysqli_real_escape_string($dbc, trim($_POST['fab1']));

//Access the Database
$query = "INSERT INTO testbed (fab1) VALUES ('$fab1')";
    mysqli_query($dbc,$query)
        or die ('Data not inserted.');

//query and look for obvious errors
     echo "Query is : " . $query . "<br />";

// Clear the form data
$fab1= "";
}

//Pull Down menu script
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'>";
    echo '<div id="box2">';
        echo'<div id="fab1">';
            $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
        $mysqli->select_db('user');
                $result = $mysqli->query("SELECT * FROM user"); 
                    echo "<SELECT name='fab1'>\n";
                        while($row = $result->fetch_assoc()) {
                    echo "<option value='{$row['userid']}'>{$row['user']}</option>\n";}
                        echo "</select>\n";
        echo '</div>';
    echo '</div>';
echo '<div id="button3"><input type="submit" value="Submit Test" name="submit" /></div>';
echo '</form>';
$result->close();
?> 



From there you go to a list, the list will show the ID and the name that is meant to be there:
http://kaboomlabs.com/testbed/list.php


That is this script:


<!DOCTYPE html 
     PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Testbed</title>
<link rel="stylesheet" type="text/css" href="tb/postie.css" />
<body>
<?php
echo '<div id="admin">';
echo '<hr id="line">';
echo '<h2 id="title">Testbed </h2>';
    
  // Connect to the database 
    require_once('tb/connectvars.php');
  $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

  // Retrieve the data from MySQL
  $query = "SELECT * FROM testbed";
  $data = mysqli_query($dbc, $query);
    
  echo '<table>';
  echo '<tr class="desc"><th>ID</th><th>Actions</th></tr>';
        while ($row = mysqli_fetch_array($data)) { 
    // Display the data
    echo '<tr class="ncmrdata">';
        echo '<td>' . $row['id'] .'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp;&nbsp</td>';
        echo '<td class="editlist"><strong><a class="elist" href="box.php?id=' . $row['id'] . '">Edit</a>';
  echo '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp;&nbsp' . $row['fab1'] . '</td></tr>';
  }
  echo '</table>';
  
     mysqli_close($dbc);

?>
</body>
</html>



The edit code is this:

The page you get by pressing edit.

Now I changed it from a name to a number in the page above, so I need to find a way to make it show the name instead of the number, but that is another post: Once I get this working that is. This is where the scrip fails on multiple levels:

The first is that it doesn't show in the pull down menu the name that resides in $fab1 inside testbed.

The second part is that it doesn't post. But if I get the first part working, I think the second part may fall into place, but I'm not sure.



<?php
require_once('tb/connectvars.php');
    $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
    $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); 
        $mysqli->select_db('pawz_PDI');

        $id= mysqli_real_escape_string($dbc, trim(0));
            if(isset($_GET['id']))
        $id= mysqli_real_escape_string($dbc, trim($_GET["id"]));
            if (isset($_POST['submit'])) {
        $id= mysqli_real_escape_string($dbc, trim($_POST["id"]));
}
if (isset($_POST['submit'])) {
    $fab1= 'fab1';
$query = "UPDATE testbed SET fab1 = '" . mysqli_real_escape_string($dbc, $fab1) . "' WHERE id = '$id'";

// echo your raw query and look for obvious errors
     echo "Query is : " . $query . "<br />";

}
        echo '<div id="box4">';
echo '<h2>Fabricators</h2>';
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'>";
echo '<div id="fab1">';

$result = $mysqli->query("SELECT * FROM user"); 
echo "<select name='fab1'>\n";
while($row = $result->fetch_assoc())
{
    echo '<option value="' . $row['fab1'] . '"';
    if($row['userid'] == $id)
    {
         echo ' selected';
    }
    echo '>' . $row['user'] . '</option>\n';
}
echo '<div id="button3"><input type="submit" value="Submit Test" name="submit" /></div>';
echo '</form>';

?>



If you need a copy of the databases, please ask I have them at the ready.
Was This Post Helpful? 0
  • +
  • -

#6 MattRidge  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 27
  • Joined: 27-January 12

Re: Populating a pull down with a table, inserting into another, +1

Posted 31 January 2012 - 06:17 AM

Ok, I've gotten the script working sort of...

I am running into two issues, and they all pertain to one script.

The final script actually.

Let me start here by saying that this script has been hell for me, so if you get confused I won't blame you, but this is where I stand.

Step 1, you go to http://kaboomlabs.co...ed/pulldown.php to click on the name and submit. This enters the data into testbed. From there you go to here, http://kaboomlabs.com/testbed/list.php, to see the list of all inputted data. The first being the ID of the line, the second being the ability to edit, and the third line is the number instead of the person there being represented.

The list of people are as thus:


(1, '--None--', '0'),
(2, 'Andy Kahl', '0'),
(3, 'Anthony Ayoub', '0'),
(4, 'Bob Payne', '0'),
(5, 'Butch Laplante', '0'),
(6, 'Daryl Flynn', '1'),
(7, 'Derrick Clark', '0'),
(8, 'Dolores Drinkwater', '0'),
(9, 'Gary Capella', '0'),
(10, 'Gelia Moril', '0'),
(11, 'Gregg Tansino', '0'),
(12, 'Kevin Sullivan', '0'),
(13, 'Kurt Flynn', '1'),
(14, 'Matt Ridge', '1'),
(15, 'Matt Ross', '0'),
(16, 'Mike Sullivan', '0'),
(17, 'Patrick Walsh', '0'),
(18, 'Ralph Block', '0'),
(19, 'Rick Guay', '0'),
(20, 'Scott Hamel', '0'),
(21, 'Scott King', '0'),
(22, 'Scott Pazerbiak', '0'),
(23, 'Scott Zizza', '0'),
(24, 'Shaun Tardiff', '0'),
(25, 'Sherry Ryan', '0'),
(26, 'Terry Wilkins', '0'),
(27, 'Wade Page', '0');



When you go to the 2nd page you will see there are several posts, click the edit link and you will see the number is not represented by the name in question via above list.

That is part one, The other part is that the change is not posting, and I can't figure out why.

Here is that script as it stands now.



<?php
require_once('tb/connectvars.php');
	$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
	$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); 
		$mysqli->select_db('pawz_PDI');

		$id= mysqli_real_escape_string($dbc, trim(0));
			if(isset($_GET['id']))
		$id= mysqli_real_escape_string($dbc, trim($_GET["id"]));
			if (isset($_POST['submit'])) {
		$id= mysqli_real_escape_string($dbc, trim($_POST["id"]));
}
if (isset($_POST['submit'])) {
	$fab1= 'fab1';
$query = "UPDATE testbed SET fab1 = '" . mysqli_real_escape_string($dbc, $fab1) . "' WHERE id = '$id'";

// echo your raw query and look for obvious errors
     echo "Query is : " . $query . "<br />";

$fab1= "";

}
echo '<h2>Fabricators</h2>';
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'>";
	echo '<div id="box4">';
		echo '<div id="fab1">';
			$result = $mysqli->query("SELECT * FROM user"); 
		echo "<select name='fab1'>\n";
			while($row = $result->fetch_assoc())
{
		echo '<option value="' . $row['fab1'] . '"';
			if($row['userid'] == $id){
				echo ' selected';
				}
		echo '>' . $row['user'] . '</option>\n';
}
echo '<div id="button3"><input type="submit" value="Submit Test" name="submit" /></div>';
		echo '</div>';
	echo '</div>';
echo '</form>';

?>



I've come so far on getting this to work, but right now I'm so close, but I feel like I am very far away from getting this solved...

Any help would be appreciated.
Was This Post Helpful? 0
  • +
  • -

#7 Jstall  Icon User is offline

  • Lurker
  • member icon

Reputation: 380
  • View blog
  • Posts: 961
  • Joined: 08-March 09

Re: Populating a pull down with a table, inserting into another, +1

Posted 31 January 2012 - 07:44 AM

Hi,

Sorry, I may not understand exactly what you are trying to do here. If all you are trying to do is make the selected user still be selected in the drop down after you hit your "submit test" button you just need to access the user's id when the form is posted.

Right now you have this:
if (isset($_POST['submit'])) {
	$id= mysqli_real_escape_string($dbc, trim($_POST["id"]));
}




You are looking for "id" in the $_POST super global but you have no form element with the name "id". The form that your code generates looks like this:
<form method="post" action="/testbed/box.php"><div id="box4"><div id="fab1">
	<div>
		<select name="fab1"></select>
	</div>
	<div id="button3">
		<input type="submit" name="submit" value="Submit Test">
	</div>
</form>



The name of your select element is "fab1" so when the form is submitted to the server the value of that would be accessible through $_POST['fab1']. So changing your code to :
if (isset($_POST['fab1'])) {
	$id= mysqli_real_escape_string($dbc, trim($_POST['fab1']));
}



Would assign the value to $id that you are expecting.

I notice this line
// Clear the form data
$fab1= "";


I don't think that is doing what you think it does. All you are doing is setting the value of that variable to an empty string.

Quote

Let me start here by saying that this script has been hell for me


Try not to let it get you down. It is obvious to me that you are putting allot of effort into getting this working, as long as you keep that up things will fall into place eventually.

I know you are focused on just trying to make this work right now, but you should start looking into coding best practices. PHP can be very powerful and elegant but it can also be used in a way that creates code that is very difficult to maintain. One of the biggest culprits in my(and many others) opinion is the lack of code separation. This tutorial outlines the basics of code separation and why it should be done.

Hope this helps :)
Was This Post Helpful? 2
  • +
  • -

#8 MattRidge  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 27
  • Joined: 27-January 12

Re: Populating a pull down with a table, inserting into another, +1

Posted 31 January 2012 - 08:27 AM

View PostJstall, on 31 January 2012 - 07:44 AM, said:

Hi,

Sorry, I may not understand exactly what you are trying to do here. If all you are trying to do is make the selected user still be selected in the drop down after you hit your "submit test" button you just need to access the user's id when the form is posted.


You make it sound so easy, the problem is that people have "helped" me with this code without telling me how it works, so I am lost more than not on the full functionality. I know there is a simpler way of doing things, but people tend to make mountians out of mole-hills when doing so.

Too many cooks in the kitchen, as you can see. Originally this script was simple and fluid, at least to me, now with about 1/2 a dozen people telling me what to do and not explaining how, it has become what you see now.

Jstall said:

Right now you have this:
if (isset($_POST['submit'])) {
	$id= mysqli_real_escape_string($dbc, trim($_POST["id"]));
}




You are looking for "id" in the $_POST super global but you have no form element with the name "id". The form that your code generates looks like this:
<form method="post" action="/testbed/box.php"><div id="box4"><div id="fab1">
	<div>
		<select name="fab1"></select>
	</div>
	<div id="button3">
		<input type="submit" name="submit" value="Submit Test">
	</div>
</form>



I thought when from the list.php document the ID was pushed to the new page? Am I mistaken?

Jstall said:

The name of your select element is "fab1" so when the form is submitted to the server the value of that would be accessible through $_POST['fab1']. So changing your code to :
if (isset($_POST['fab1'])) {
	$id= mysqli_real_escape_string($dbc, trim($_POST['fab1']));
}



Would assign the value to $id that you are expecting.


I would, but this is part of a much, much larger script, this is only one part of it, and I can't do that, otherwise it would of been done a long time ago. I've had to keep it as
if (isset($_POST['submit'])) {
because when this is put into it's final place this is one part of a much, much, much longer script.

Jstall said:

I notice this line
// Clear the form data
$fab1= "";


I don't think that is doing what you think it does. All you are doing is setting the value of that variable to an empty string.


Probably not, I was told to clean out all inputs after they have been inserted so the code won't transfer or be saved in the browser by accident.

Jstall said:

Quote

Let me start here by saying that this script has been hell for me


Try not to let it get you down. It is obvious to me that you are putting allot of effort into getting this working, as long as you keep that up things will fall into place eventually.

I know you are focused on just trying to make this work right now, but you should start looking into coding best practices. PHP can be very powerful and elegant but it can also be used in a way that creates code that is very difficult to maintain. One of the biggest culprits in my(and many others) opinion is the lack of code separation. This tutorial outlines the basics of code separation and why it should be done.

Hope this helps :)


Thanks for the links, but right now I just want to finish this script, once I do I will go back and beautyfy it the way it is meant to be. The whole reason for the testbed section is to get things working, and to clean up code while the original code is working in the background untouched till all bugs and issues have been resolved.
Was This Post Helpful? 0
  • +
  • -

#9 Jstall  Icon User is offline

  • Lurker
  • member icon

Reputation: 380
  • View blog
  • Posts: 961
  • Joined: 08-March 09

Re: Populating a pull down with a table, inserting into another, +1

Posted 31 January 2012 - 08:50 AM

Hi,

Ok, I understand that your test page is part of a larger file but the technique would stay the same. Values for elements in a form submitted to the server that have the "POST" method are accessible in the $_POST superglobal array. $_POST is an associative array. You access posted form data by using the form element's name attribute as an index in $_POST e.g $_POST['myfield'].

The logic should stay the same even as part of a larger file.

You need to
1) Access the selected item's value from the drop down by doing something like:
$id = $_POST['drop_down_name'];


2) Look for that value when you are looping through your user table:
if($id == $row['userid'])


Was This Post Helpful? 1
  • +
  • -

#10 MattRidge  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 27
  • Joined: 27-January 12

Re: Populating a pull down with a table, inserting into another, +1

Posted 31 January 2012 - 10:35 AM

View PostJstall, on 31 January 2012 - 08:50 AM, said:

Hi,

Ok, I understand that your test page is part of a larger file but the technique would stay the same. Values for elements in a form submitted to the server that have the "POST" method are accessible in the $_POST superglobal array. $_POST is an associative array. You access posted form data by using the form element's name attribute as an index in $_POST e.g $_POST['myfield'].

The logic should stay the same even as part of a larger file.

You need to
1) Access the selected item's value from the drop down by doing something like:
$id = $_POST['drop_down_name'];


2) Look for that value when you are looping through your user table:
if($id == $row['userid'])



But isn't this code for that?:


     if(isset($_GET['id']))
       $id= mysqli_real_escape_string($dbc, trim($_GET["id"]));
     if (isset($_POST['submit'])) {
       $id= mysqli_real_escape_string($dbc, trim($_POST["id"]));


Was This Post Helpful? 0
  • +
  • -

#11 MattRidge  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 27
  • Joined: 27-January 12

Re: Populating a pull down with a table, inserting into another, +1

Posted 31 January 2012 - 10:43 AM

Also, the second part of your post, I found this:


	echo '<option value="' . $row['fab1'] . '"';
			if($row['userid'] == $id){
				echo ' selected';
				}
		echo '>' . $row['user'] . '</option>\n';}



It looks different than yours, I guess this is where the many chefs in the kitchen thing comes in. Is that correct or should it be changed?
Was This Post Helpful? 0
  • +
  • -

#12 Jstall  Icon User is offline

  • Lurker
  • member icon

Reputation: 380
  • View blog
  • Posts: 961
  • Joined: 08-March 09

Re: Populating a pull down with a table, inserting into another, +1

Posted 31 January 2012 - 11:40 AM

Arrayscan be used to store multiple variables. Values in an array are accessed by the arrays index. You access values in an arrays index with the syntax $array[index].

In PHP you can have numerically indexed arrays or associative arrays. When using numerically indexed arrays you access values via a number. They are zero based meaning that the first value is accessed via index 0, second by index 1 and so on.
// an array
$arr = array()
//adding some values
$arr[0] = "One";
$arr[1] = "Two";
$arr[2] = "Three";

echo $arr[2]; // outputs the string "Three"



Associative arrays use strings as their indexes but are accessed using the same syntax:
// our array
$arr = array():
$arr['name'] = "Bob";
$arr['age'] = 32;

echo $arr['name']; // outputs the string "Bob"



$_POST is an associative array. It is called a superglobal variable because it's scope spans an entire script.

View PostMattRidge, on 31 January 2012 - 03:35 PM, said:

But isn't this code for that?:


     if(isset($_GET['id']))
       $id= mysqli_real_escape_string($dbc, trim($_GET["id"]));
     if (isset($_POST['submit'])) {
       $id= mysqli_real_escape_string($dbc, trim($_POST["id"]));



Not quite, you are looking for $_POST['id'] there. The <select> element on your form has the name "fab1" therefore the value of the selected option will be in $_POST['fab1']. When a form is submitted to the server you access values in the form's elements by using their name as the index in the $_POST associative array.

If this form:
<form action = "my_file.php" action = "POST">
   <label>First Name:</label>
   <input type = "text" name = "first_name"/>
   <label>Last Name:</label>
   <input type = "text" name = "last_name" />
</form>


Was submitted to a server you would get the values of the text inputs like this:
  echo $_POST['first_name']; // value in the first_name textbox
  echo $_POST['last_name']; // value in the last_name textbox 



As far as this goes:

echo '<option value="' . $row['fab1'] . '"';
		if($row['userid'] == $id){
			echo ' selected';
			}
	echo '>' . $row['user'] . '</option>\n';}





In PHP we use ==to test for equality. If the expressions on both sides of the == operator are equal then the statement evaluates to true. Thus
if($row['userid'] == $id)


and
if($id == $row['userid'])



are the same.

Note that in PHP == ignores the datatype when checking for equality so
 5 == "5"


would evaluate to true.

Hope this helps :)
Was This Post Helpful? 0
  • +
  • -

#13 MattRidge  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 27
  • Joined: 27-January 12

Re: Populating a pull down with a table, inserting into another, +1

Posted 31 January 2012 - 11:57 AM

[/quote]


[quote name='Jstall']

View PostJstall, on 31 January 2012 - 11:40 AM, said:

Arrayscan be used to store multiple variables. Values in an array are accessed by the arrays index. You access values in an arrays index with the syntax $array[index].

In PHP you can have numerically indexed arrays or associative arrays. When using numerically indexed arrays you access values via a number. They are zero based meaning that the first value is accessed via index 0, second by index 1 and so on.
// an array
$arr = array()
//adding some values
$arr[0] = "One";
$arr[1] = "Two";
$arr[2] = "Three";

echo $arr[2]; // outputs the string "Three"



Associative arrays use strings as their indexes but are accessed using the same syntax:
// our array
$arr = array():
$arr['name'] = "Bob";
$arr['age'] = 32;

echo $arr['name']; // outputs the string "Bob"



Ok, so far I got you.

Jstall said:

$_POST is an associative array. It is called a superglobal variable because it's scope spans an entire script.

View PostMattRidge, on 31 January 2012 - 03:35 PM, said:

But isn't this code for that?:


     if(isset($_GET['id']))
       $id= mysqli_real_escape_string($dbc, trim($_GET["id"]));
     if (isset($_POST['submit'])) {
       $id= mysqli_real_escape_string($dbc, trim($_POST["id"]));



Not quite, you are looking for $_POST['id'] there. The <select> element on your form has the name "fab1" therefore the value of the selected option will be in $_POST['fab1']. When a form is submitted to the server you access values in the form's elements by using their name as the index in the $_POST associative array.


So would it be beneficial to add in those lines this code:

$id = mysqli_real_escape_string($dbc, trim($_POST["userid"]));
$id = mysqli_real_escape_string($dbc, trim($_GET["userid"]));



In their correct place of course, but into the code above?

Jstall said:

If this form:
<form action = "my_file.php" action = "POST">
   <label>First Name:</label>
   <input type = "text" name = "first_name"/>
   <label>Last Name:</label>
   <input type = "text" name = "last_name" />
</form>


Was submitted to a server you would get the values of the text inputs like this:
  echo $_POST['first_name']; // value in the first_name textbox
  echo $_POST['last_name']; // value in the last_name textbox 



As far as this goes:

echo '<option value="' . $row['fab1'] . '"';
		if($row['userid'] == $id){
			echo ' selected';
			}
	echo '>' . $row['user'] . '</option>\n';}





In PHP we use ==to test for equality. If the expressions on both sides of the == operator are equal then the statement evaluates to true. Thus
if($row['userid'] == $id)


and
if($id == $row['userid'])



are the same.

Note that in PHP == ignores the datatype when checking for equality so
 5 == "5"


would evaluate to true.


I just wanted to make sure, because there is a correct way of doing things, and unthankfully I've learned many bad habits it seems.

Jstall said:

Hope this helps :)


It helps, but I'm going to have to try some more things, but I may need help just writing the code correct... because although I may understand what you are saying to an extent, I may not know how to salvage this code the way it is written now.
Was This Post Helpful? 0
  • +
  • -

#14 MattRidge  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 27
  • Joined: 27-January 12

Re: Populating a pull down with a table, inserting into another, +1

Posted 31 January 2012 - 12:17 PM

Ok, after reading my code, and as I said with many fingers in it, I need to ask these questions, and also to comment just to make sure if it works the way I think it does...so bare with me please.

<?php
require_once('tb/connectvars.php');
	$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
	$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); 
		$mysqli->select_db('user');



Why doesn't $dbc above have a $dbc->seclect_db('testbed'); Or should it?

if(isset($_GET['id']))
	$id= mysqli_real_escape_string($dbc, trim($_GET["id"]));

if (isset($_POST['submit'])) {
	$id= mysqli_real_escape_string($dbc, trim($_POST["id"]));
	$fab1= 'fab1';
	$query = "UPDATE testbed SET fab1 = '" . mysqli_real_escape_string($dbc, $fab1) . "' WHERE id = '$id'";



Is this what you were talking about grouping things together?

// echo your raw query and look for obvious errors
echo "Query is : " . $query . "<br />";



This code above I understand, this tells me the output of the code so we can understand where the output errors are if any.

}
echo '<h2>Fabricators</h2>';
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'>";


this is to tell the page to post to itself.

	echo '<div id="box4">';
		echo '<div id="fab1">';



div identifiers.

			$result = $mysqli->query("SELECT * FROM user");



Should this be placed under the _GET? Also this gives the ability of result to look inside the user table correct?

		echo "<select name='fab1'>\n";
			while($row = $result->fetch_assoc()){
	echo '<option value="' . $row['fab1'] . '"';
			if($row['userid'] == $id){
				echo ' selected';



The majority of this code I'm lost at, except the userid, which tells me that it equals $id, but doesn't that override the beginning code?

		}
		echo '>' . $row['user'] . '</option>\n';}
		echo "</select>\n";
		echo '</div>';
	echo '</div>';


Again, lost here except the div, which closes the script.

echo '<div id="button3"><input type="submit" value="Submit Test" name="submit" /></div>';
echo '</form>';

?>


The final bit is the submit button and the closing of the form...

Tell me if I'm mistaken here, but the parts I can't figure out are probably the parts that I need to understand the most?
Was This Post Helpful? 0
  • +
  • -

#15 Jstall  Icon User is offline

  • Lurker
  • member icon

Reputation: 380
  • View blog
  • Posts: 961
  • Joined: 08-March 09

Re: Populating a pull down with a table, inserting into another, +1

Posted 31 January 2012 - 03:08 PM

Hi,

Quote

Why doesn't $dbc above have a $dbc->seclect_db('testbed'); Or should it?


the select_db() method accepts a database name as a parameter. If the database name is user then this is correct. The fact that no exceptions are thrown and the query you run after this is successful suggests that it is most likely the correct database name.

Quote

Is this what you were talking about grouping things together?
// echo your raw query and look for obvious errors
echo "Query is : " . $query . "<br />";


That line echos out the value of the $query variable, it is done so you can see the actual query that is being run against the database. This is useful for debugging.

Quote

Should this be placed under the _GET? Also this gives the ability of result to look inside the user table correct?


Because the code you are referring to is sending output to the browser moving it around in the file will throw the layout of the page off.

This line:
$result = $mysqli->query("SELECT * FROM user");



$mysqli is referencing an object of the mysqli class. It is invoking the query method and passing it the string "SELECT * FROM users" which gets every field for every record in the users table. The query() method returns a mysqli_result object which is assigned to the variable $result.

The line:
while($row = $result->fetch_assoc())



Uses a while loop . While loops are provided a condition and will execute the code defined in the loop as long as the condition evaluates to true. In this case the condition being tested is $row = $result->fetch_assoc(). The fetch_assoc() method returns an associative array if there are results left in the mysqli_result obect's result set and NULL when there are none. Each time the loop runs the associative array is assigned to the variable $row. The loop will run until it has gone through every record the query returned, when there are none less it will return NULL which makes the while loops condition evaluate to false.

Knowing that $row is an associative array you may be able to get a better understanding of how the code is working.

I hope this clears some things up for you :)
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2