I found this piece of code from an answer on Several drop down list input to one field table. It really seems like something I can use in my current project. The current project is about populating a table with two dropdown boxes (which are populated themselves with tables). However, I don't understand what personal changes I need to do in order to make it work. attributes? :attributes? Can someone make sense of it?
$levels = $_POST['level1'][0].",".$_POST['level1'][1];
//Now you have a string called $levels
// Which contains a comma seperated list, to insert into db / one field
//Insert into your table...change your table and field names to real values...
$sql = "INSERT INTO yourTable (attributes) VALUES (:attributes)";
$q = $db->prepare($sql);
$q->execute(array(':attributes'=>$levels));
?>
:attributes is a bound parameter in a PHP prepared statement which inserts a row into a table with an attributes field, setting just that field.
Related
Example, I want the drop down value to be 1278|Toy Name
I would like to then separate via the | and spost the id "1278" in an id field
and "Toy 2" in a toy field.
I am actually using FormTools (formtools.org) for all of my forms and this is one thing I just can not get my head around.
A little background: This is for a client and needs to be this way. they need the ID submitted as well as the Toy Name into separate Db tables.
Any help would be greatly appreciated.
You could split the submitted value based on the | and use the retrieved values to insert into the database.
$toyInput = $_POST["toyInput"];
$toySplit = explode("|", $toyInput);
$toyID = $toySplit[0];
$toyName = $toySplit[1];
// Now insert $toyID and $toyName into your DB in separate fields.
Be aware that this has no validation, a user could easily put fake ID's, names, or a value with no "|" and cause your script to error out. Be sure to add extra checks for these cases!
You can also use list that assign values to a list of variables.
$toyInput = $_POST["toyInput"];
list($toyID, $toyName) = explode("|", $toyInput);
I am trying to build a dynamic set of comboboxes/listMenus getting data from a MySQL DB. My database has 5 fields, 1st being id and
topic, sub_topic, info and url
I want to make it so that until user selects a valid choice from box1 that the others are disabled. Once user selects from box 1 box 2 will be activated. Once you make a selection from box 2 then the info and url will be shown.
I have followed a tutorial http://www.ssdtutorials.com/tutorials/series/dependable-dropdown.html and so most of this code is not mine apart from the SELECT statements
I am having problems writing the MySQL for update.php as this populates the other boxes (currently I am sticking with the comboboxes until I have it working.)
I would be grateful for some help, due to the amount of code it can be seen here http://pastebin.com/QNbHR9JK
Thanks in advance.
The first thing I see is that in update.php query, you aren't actually using a where clause. When you execute the prepared query, you pass in a value array, but there aren't any placeholders in the prepared query.
I would expect something like:
$sql = "SELECT `topic`,`sub_topic`,`info`,`url`
FROM `links` WHERE sub_topic=?";
$statement = $objDb->prepare($sql);
$statement->execute(array($value));
One other thing I notice is that in your foreach in update.php, you are using $row['id'] but you aren't selecting that column in your query.
EDIT
I updated the query to use the proper column in where clause, and removed to group by clause based on discussion.
After much head-scratching, I've got this query working - but it looks clunky and feels slow when it runs.
I have a table called UserTable which has a field called 'Item' populated if the specific user says 'yes' to that item. I only want to add a row for that item into UserTable in that instance - in other words, I don't want to have lots of user_ID/Item/'no' relationships in the table, only the user_ID/Item/'yes' responses.
I've built some code which shows the user the whole dataset and allows them to change their preference and then press update. When they update, an array called $checkbox is output which includes the item numbers (eg "1","3","6") which they've ticked as 'yes'. If they don't tick anything, $checkbox is set to "".
Here's the relevant code - as I say, it's very clunky, with a WHILE inside a FOREACH as well as two validating IF statements. Can I get rid of one (or both!) of the loops and replace with a SELECT type command?
foreach($checkbox as $value)
{if($value!="") {
$sql= "SELECT count(Item) as row_exists
FROM UserTable
WHERE Item = '$value' and
User_ID = '$current_user_id'";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
while ($iteminfo = mysqli_fetch_array($result)) {
If ((int)$iteminfo['row_exists']==0) {
$sql = "INSERT INTO UserTable
(User_ID,Item,Date) VALUES
('$current_user_id','$value',now() )";
$add_new_row = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
}
}
}
}
Many thanks in advance.
You can eliminate both if statements:
Filter your checkbox array on != "" and loop over those results. That gets rid of the first if that checks for != "".
Augment your initial query to include row_exists = 0, and iterate over those results. That gets rid of the second if.
In fact, you could probably merge your two sql statements into one composite conditional insertion. You are allowed to do insertions of the form:
INSERT INTO table (SELECT ...)
So you could look at taking your first query and adapting/substituting it for the SELECT... part of the query above, and taking your second insertion and adapting/substituting it in place of the INSERT INTO... above.
So if one user can be associated with multiple items, it seems that you should normalize this and have probably three tables - one for users, one for items, and one many-to-many table relating users to items.
I'm currently trying to write a simple ORM with PHP and mysql. I want the orm class to be able to work with joined tables.
So here's my problem, the following code shows how I map the data the query yields into an array.
public function execute_query($db_connection)
{
$query = '';
foreach($this->sql_query as $query_part)
$query .= $query_part;
$result = $db_connection->query($query);
while($row = $result->fetch_assoc())
{
array_push($this->m_Data, $row);
}
}
db_connection is a mysqli object.
sql_query contains all the different query parts (e.g. sql_query['join'] etc.).
m_Data is the array that contains the data read from the db.
My specific problem now is when I'm using a join statement in my query this function will just override fields with the same name in my m_Data array. Also if I dont save the name's of the table the specific field data is coming from, I later can't update the tables with the same join statement.
tl,dr. I need to be able to not only save the table data like this: m_Data{ 'field_name' => 'value' } but I also need to save the table name the field is selected from. I could then save the data like this m_Data{ 'table_name.field_name' => 'value' } which enables me later to generate a query to update the joined tables successfully.
I cant seem to find any information on how to get the origin table name for each field I pull out of the result.
If it isnt possible with mysqli I'd much appreciate it if you point me in the right direction.
extra short problem statement:
I need to get a result set and read each row seperatly. For each row I need the following information for every field selected: field_name, table_name, value.
There must be a simple answer to this but I seem to be searching for the wrong keywords to find a solution.
I hope I've written this understandable enough.
Seems to me that you should store table column values in an object, so if you have a related table, the column values would be stored in a separate object - and so would not interfere with the values in your primary table.
In general you might work with the ORM this way:
// Make joined query
$rows = ...
foreach($rows as $row)
{
// $row just refers to the primary table
echo $row->id;
// You get a many:1 related table this way
echo $row->getRelatedRow()->value;
// You get a 1:many rows this way
$rows = $row->getOtherRelatedRows();
}
Depending on how you set up your query options, getting related data may or may not initiate further SELECTs to get the required data.
mysqli_result::fetch_fields has useful things:
http://www.php.net/manual/en/mysqli-result.fetch-fields.php
table
orgtable
field type
etc
I am working in the confines of a CMS system, which defines certain fields which can be used to make forms for use within the application in PHP.
I am making use of the inputSmartSearch field, which is basically similar to Google suggest.
It allows me to define an SQL query, and then displays records that match as I type in my search.
For my smartsearch, I have chosen it to search through three fields in a different table, and to display those fields concatenated together.
I use define my field like so:
$theinput = new inputSmartSearch($db, "chooseguests", "Choose Guests");
The last parameter is the name of the SQL query to execute.
This works fine, and a guest can be located by searching his last or first name.
However, I have implemented this smartsearch what is meant to be the page to add a sales order.
In each sales order stored in the sales table, distinct from the guest table, I also want to have the firstname and lastname of the guest making the order.
The design of the sales order table has two separate fields for firstname and lastname.
Using smartsearch, I cannot find any way to tokenize the selected input and insert it back into the field.
If I have a smartsearch and can search by firstname or lastname it shows the result as just one fields, and I want it to save the firstname to the firstname field and the lastname to the lastname field.
Each form defined has an include file which defines the function for inserting a record and such, like so:
function prepareVariables($variables){
// if ($variables["webaddress"]=="http://")
// $variables["webaddress"] = NULL;
return $variables;
}
function updateRecord($variables, $modifiedby = NULL, $useUuid = false){
$variables = $this->prepareVariables($variables);
return parent::updateRecord($variables, $modifiedby, $useUuid);
}
function insertRecord($variables, $createdby = NULL, $overrideID = false, $replace = false, $useUuid = false){
$variables = $this->prepareVariables($variables);
return parent::insertRecord($variables, $createdby, $overrideID, $replace, $useUuid);
}
However, I am unsure of how I could modify the insert or update functions to do what I need them to do, or if that is even the correct approach.
Should I be looking for a complex sql query? hidden fields with the content autopopulated from the result of my inputSmartSearch? Something else?
Not sure what's possible with the setup you've got going, but... my first reaction would be to return from the db the names combined with tokens - like - ',' So Smith, John. Then, when getting ready to send back, to split those up ( based upon the known token ). Now where that goes what you've got there, I do not know.
You just need to set the starting value of the smart search manually using the values from the database. Then when the data is posted to the server you can parse and append to the array that is used to store the data in the database. At least that seems like it should work.