(PHP & mySQL) Treat rows as columns - php

I am working on PHP & mySQL based website. I am trying to setup the 'Settings' page in administration panel where I can enter different settings to manage the site. The settings can range upto 100 (or even more) depending upon the requirements. So instead of making 100 columns (and increase if I have to add more columns in future), I want to store the data in row wise format and fetch the values as if I am fetching it from columns.
REFERENCE:
I found a similar real life implementation of such feature in the most popular blogging tool 'Wordpress'. For reference, it is the 'wp_options' table that I am talking about.(Please correct me I am wrong)
EXAMPLE:
Here's a quick example of what (& why) I am trying to do it that way:
--Table settings
P.KEY option_name option_value
1 site_name XYZ site inc.
2 siteurl http://www.xyz.com
3 slogan Welcome to my XYZ site
4 admin_email admin#xyz.com
5 mailserver_url mail.xyz.com
6 mailserver_port 23
..... etc.
As you can see from above, I have listed very few options and they are increasing in number. (Just for the records, my installation of Wordpress has 902 rows in wp_options table and I did not see any duplicate option_name). So I have the feeling that I am well off if I apply the same working principle as Wordpress to accomodate growth of the settings. Also I want to do it so that once I save all the settings in DB, I want to retrieve all the settings and populate the respective fields in the form, for which the entries exist in DB.
ONE OF MY CODE TRIALS:
--
-- Table structure for table `settings`
--
CREATE TABLE IF NOT EXISTS `settings` (
`set_id` tinyint(3) NOT NULL auto_increment,
`option_name` varchar(255) NOT NULL,
`option_value` varchar(255) NOT NULL,
PRIMARY KEY (`set_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
--
-- Dumping data for table `settings`
--
INSERT INTO `settings` (`set_id`, `option_name`, `option_value`) VALUES
(1, 'site_name', 'XYZ site inc.'),
(2, 'slogan', 'Welcome to my XYZ site');
$result = mysql_query("SELECT option_name, option_value FROM settings");
$defaults = array('option_name', 'option_value');
while( list($n, $v) = mysql_fetch_array($result) )
{
$defaults['option_name'] .= $n;
$defaults['option_value'] .= $v;
}
echo $defaults['option_name'].'---'.$defaults['option_value'].'<br />';
//The above code gives me the following Output:
//site_nameslogan---XYZ site inc.Welcome to my XYZ site
When I run the above query, I also receive 2 PHP Notices that says:
Undefined index: option_name
Undefined index: option_value
I would appreciate any replies that could show me the PHP code to retrieve the options successfully and eliminate the Undefined index issues as well. Also, like I mentioned earlier, I want to retrieve all the existing settings and populate the respective fields in the form when I visit the settings page next, after storing the data.
Thanks fly out to all in advance.

PHP gives you warning because $defaults['option_name'] and $defaults['option_value'] are not being initialized before they are used in .= operation.
So just put
$defaults['option_name'] = '';
$defaults['option_value'] = '';
before the loop and warning will go away.
The rest of the code is completely correct, although you don't have to have set_id column at all since every setting will have unique name, that name (option_name column) can be used as primary key.
Another thing that you can improve your code, is to use $defaults differently, like so
$defaults[$n] = $v;
Then you can use every setting on its own without looking through two huge strings.
$site_url = $defaults['site_url'];
foreach ($defaults as $name => $value) {
echo $name, ' = ', $value, '<br>';
}

This should do the trick:
$defaults = array('option_name' => array( ), 'option_value' => array( ) );
while( list($n, $v) = mysql_fetch_array($result) )
{
$defaults['option_name'][] = $n;
$defaults['option_value'][] = $v;
}
Then in your view iterate over $defaults['option_name'] and $defaults['option_value']

Related

How to insert multiple select option in PHP MySQL when multiple='multiple' is enabled

I have a FORM with method POST. In the form I have two select drop-down with multiple='multiple' enabled in both so that user can make multiple selections.
Now I am using MySQL database to store data.
I am using foreach loop to iterate all the selections made.
Here is the image Select drop-down image
My code
$cid = $row['cid'];
$work_location = $_POST['work_location'];
$interest = $_POST['interest'];
foreach ($work_location as $value) {
$work = $value;
}
foreach ($interest as $value) {
$int = $value;
}
$insert_oth_data = "INSERT INTO resume_spec_data
(cid, work_location, interest)
VALUES('$cid', '$work', '$int')";
mysqli_query($con, $insert_oth_data);
echo var_export($work_location);
echo var_export($interest);
echo var_export($work);
echo var_export($int);
echo var_export( $insert_oth_data );
Here work_location and interest are the fields that will carry the multiple select values. I don't want to use implode function because it will make data extraction difficult as table grows. I want to store the values in saperate rows of database.
The problem I am facing is that data is being inserted, but the problem is when I select multiple options only one data is being inserted not all.
The result I get after inserting the data is:
array ( 0 => 'Delhi', 1 => 'NCR', )array ( 0 => 'Software development', 1 => 'Business analyst', 2 => 'Web development', )'NCR''Web development''INSERT INTO resume_spec_data(cid, work_location, interest) VALUES(\'1\', \'NCR\', \'Web development\')'
As you can compare from the image I have made multiple selections. But single data is being taken here
For reference
$work_location contains array ( 0 => 'Delhi', 1 => 'NCR', )
$interest contains
array ( 0 => 'Software development',
1 => 'Business analyst',
2 => 'Web development',
)
$work contains NCR
$int contains Web development only
$work and $int should also contains same as $work_location and $interest respectively.
One thing that I found here is that I have applied Insert query outside the foreach loop maybe that is why only one value is being taken. Since I am using multiple select drop-down here with multiple='multiple' enabled, I don't know how to do this to achieve the result I want.
Any help would be appreciated.
Your INSERT command happens once, and it occurs after your loops have all finished. So in the loops you're pointlessly re-assigning new values to the same variable, and then discarding them again without using them. Obviously if you wait until after a loop has finished, then you can't use the values which are present when the loop is running. You'll only ever see the last one which was assigned in the last run of the loop.
And you've explained that you're struggling to fix this because you don't know how to include the insert query inside the loops, because there are 2 different foreach loops.
So really I think the root cause here is that your database structure is flawed. It seems you permit different numbers of values in your form (e.g. 2 entries for work locations, then 3 entries for domains of interest, per your screenshot), and there's no particular relationship between them (e.g. does "Delhi" belong with "software development, or "business analyst", or the other one? There's no logic to explain that).
And yet, you're trying to store them in a table which inherently relates them together by storing them next to each other in rows. This will result in poor data quality because a) there's no way to decide which belongs with which, and b) if you have different numbers of entries in each field then you'll end up with gaps.
You need separate tables to store each list - one table for locations, and one table for interests, both with the Cid to link them to the master record.
This will then make it easy to use the data in you loops e.g.
foreach ($work_location as $value) {
$work = $value;
//...write query code to insert into work locations table
}
foreach ($interest as $value) {
$int = $value;
//...write query code to insert into interests table
}

osclass SQL Inserting data twice

i have this osclass table when I insert a data and then browse the table the data has been entered twice, so i get two id of the same table.
CREATE TABLE /*TABLE_PREFIX*/t_table_log(
pk_i_id INT NOT NULL AUTO_INCREMENT ,
fk_i_user_id INT NULL ,
fk_i_item_id INT NULL ,
s_email VARCHAR( 200 ) NULL ,
s_status VARCHAR( 20 ) NOT NULL ,
PRIMARY KEY(pk_i_id)
) ENGINE=InnoDB DEFAULT CHARACTER SET 'UTF8' COLLATE 'UTF8_GENERAL_CI';
this is my php code
$conn = getConnection();
$conn->osc_dbExec("INSERT INTO %st_table_log (fk_i_item_id, fk_i_user_id, s_email, s_status ) VALUES ('".$_SESSION['itemid']."','".$_SESSION['userid']."','".$response['senderEmail']."','".$response['status']."')", DB_TABLE_PREFIX) ;
$item_url = osc_item_url() ;
$name = osc_page_title() ;
$subject = (__("Hello",'osclass'));
$email = osc_logged_admin_email();
$messagesend =" my message";
$params = array(
'subject' => $subject
,'to' => $email
,'to_name' =>$name
,'body' => $messagesend
,'alt_body' => strip_tags($messagesend)
) ;
osc_sendMail($params) ;
Where's located your code?
You might want to check those things:
autocron: this is an Osclass-feature that runs Cron without the need to configure the crontab. Head to Settings > General and check if autocron is checked. It makes a new HTTP request for it, so your code might be running twice.
ajax: you might have some ajax query in one of your enabled plugins or theme that makes a request on each loading and run your code twice.
From what I see, you might want to use the 'init' hook to be sure it gets executed once. Something like this:
osc_add_hook('init', function () {
$session = Session::newInstance();
$userId = $session->_get('userid');
$itemId = $session->_get('itemid');
// Do something.
});
Also, try to take a look at DAO in Osclass and plugin development, here's a tutorial that will get you through Osclass plugin development and the use of DAO.

Mass assignment issue

I have a form with a lot of fields and each of them has to be added in a table as a different row.
My table looks like this:
| Category | Device | Value |
|----------|:-------|-------------|
| 2 | 1 | some value |
| 3 | 1 | other value |
| 7 | 3 | etc |
The Category and Device are actually foreign keys from the Categories and Devices tables. Also they should be unique, meaning that there can't be Category: 2 and Device: 1 twice. If they exists already, the value should be updated.
The categories and value are retrieved from the form and it looks like this:
{"2":"some value","3":"other value","5":"etc","6":"something","8":"can be empty"}
The device also comes from the form but it will be the same.
Now I need to enter everything in my database and I'm looking for a simple solution.
But it will do about 100 queries (one for each input) and I'm sure there must be a better solution.
If one of the values that comes from the form is empty, it should be ignored.
Here's my currently working code, maybe you can understand better:
public function postSpecs(Request $request)
{
$specs = $request->except(['_token', 'deviceid']);
foreach($specs as $key=>$val)
{
if($val == '') continue;
if(Spec::where('category', $key)->where('device', $request->deviceid)->exists())
{
$spec = Spec::where('category', $key)->where('device', $request->deviceid)->first();
$spec->value = $val;
$spec->save();
}
else
{
$spec = new Spec;
$spec->category = $key;
$spec->device = $request->deviceid;
$spec->value = $val;
$spec->save();
}
}
}
use the insert method like:
$model->insert([
['email' => 'taylor#example.com', 'votes' => 0],
['email' => 'dayle#example.com', 'votes' => 0]
]);
See also: http://laravel.com/docs/5.1/queries#inserts
EDIT:
Updated to your code:
public function postSpecs(Request $request)
{
$specs = $request->except(['_token', 'deviceid']);
$data = array();
foreach($specs as $key=>$val)
{
if($val == '') continue;
if(Spec::where('category', $key)->where('device', $request->deviceid)->exists())
{
$spec = Spec::where('category', $key)->where('device', $request->deviceid)->first();
$spec->value = $val;
$spec->save();
}
else
{
$data[]['category'] = $key;
$data[]['device'] = $request->deviceid;
$data[]['value'] = $val;
}
}
Spec::insert($data);
}
While this is not perfect, it will save you a lot queries. Else you have to use raw query something like (untested!):
INSERT INTO spec (id,category,device,value) VALUES (1,2,3),(4,5,6)
ON DUPLICATE KEY UPDATE id=LAST_INSERTED_ID(id)
A little more information on the on duplicate key update method because I think it deserves to be a possible solution if this is something that's going to happen a lot...
First, you would need to create the unique key. This will force those columns to be unique. I'd highly suggest adding the unique key no matter how you handle the inserts. It may help preserve your sanity in the future.
In a migration, you would do...
$table->unique(['Category', 'Device']);
Or in plain sql...
alter table category_device add unique index unique_category_device (Category, Device);
Now to insert into the table, you would simply use the query...
insert into category_device (Category, Device, Value) values ($category_id, $device_id, $value)
on duplicate key udpate Value = VALUES(Value)
If it's not a duplicate entry, mysql will simply insert the new record. If it is a duplicate, mysql will update the value column with whatever you tried to insert as the new value. This is very performance friendly as you will not be required to check for the existence of duplicates before trying to do the insert as it will simpy act like an update statement in the event there is a duplicate. The drawback here is laravel does not support on duplicate key update so you would need to actually write the SQL. I would suggest you still use data bindings though which can make it somewhat easier.
$sql = "insert into category_device (`Category`, `Device`, `Value`) values (:category_id, :device_id, :value)
on duplicate key udpate Value = VALUES(Value)";
$success = \DB::insert($sql, [
'category_id' => $category_id,
'device_id' => $device_id,
'value' => $value
]);
Also please note, if you have over 100 entries, you could loop through them and keep adding to the query and it should work just the same...
insert into category_device (`Category`, `Device`, `Value`)
values
(1, 1, 'some value'), (1, 2, 'some other value'), (1, 3, 'third value')...
on duplicate key udpate Value = VALUES(Value)";
If you are using this method, I would probably not worry about the data binding and just insert the values right into the query. Just make sure they are properly escaped beforehand.
If you had a hundred items to insert, which would be 200 queries (one for checking the existence of the record, and another for inserting/updating), this would turn that 200 queries into 1 query which obviously would be a huge performance gain.

SugarCRM Custom Dropdown Field

I have made a custom dropdown field in leads module. Its a dynamically fetching users from users table from the leads module as key => value pair.
The field works fine but when in the edit mode (create a new lead)...the value is not getting stored and instead the key is getting stored not value..
I mean like instead of 'James Bond' the id is getting stored ..which is like '7896877'
Now the funny thing is that in the detail view in sugarcrm (leads module) the name is displayed properly as i wanted it to work. ONly in the list view it displays the ID and also in the database its getting stored as KEY i.e the hash ID.
This is the function:
function getUSERS($bean) {
$resultArray = Array();
$query = "select id,(first_name + ' ' + last_name) AS Name from dbo.users ORDER BY first_name ASC";
$resultArray [''] = '';
$result = $bean->db->query($query);
while ($row = $bean->db->fetchByAssoc($result)) {
$resultArray[$row['id']] = $row['Name'];
}
return $resultArray;
}
Dropdowns in Sugar work as key/value pairing, the key is what is stored in the database and Sugar does the appropriate lookup to display the value. Except the list view seems to work differently for dynamic dropdowns.
Instead of building your array as $resultArray[$row['id'] ]= $row['Name'] you could use the username -$resultArray[$row['username'] ]= $row['Name']as usernames have to be unique but will be more meaningful to your users in the list view.
However, is there any reason you're not using a relate field to the Users module? That should solve all your problems without any coding.

How can I group by column value in a yii query?

I have a data table with 7 columns and 400 records. One of them is budget. I want to group the 400 rows by budget so that I get an array like this:
[budget]=>array(
[0]=>array(
[column1]=>'1',
[column2]=>'sand'
),
[1]=>array(
[column1]=>'2',
[column2]=>'clay'
)
)
[budget2]=>array(
[0]=>array(
[column1]=>'3',
[column2]=>'silt'
),
[1]=>array(
[column1]=>'4',
[column2]=>'stone'
)
)
So far I have been playing around with Yii's CdbCommand and CdbDataReader and PHP's PDOStatement but nothing is working right. I tried the following code
public function actionBidCostByBudget(){
$command = Yii::app()->db
->createCommand()
->Select('*')
->From('bid_cost')
# ->Query()
;
echo '<pre>';
echo get_class($command);
$pdostatement=$command->getPdoStatement();
if($pdostatement) echo get_class($pdostatement);
# print_r($statement->fetchall(PDO::FETCH_COLUMN|PDO::FETCH_GROUP));
# print_r($command->readall());
# print_r($statement->fetch());
# $columnsArray = BidCost::attributeLabels();
//print_r($rowsArray);
//$this->layout='\\layout';
}
The attempts to print_r all print out with nothing. getPdoStatement equals nothing. I have been trying to use PDO::FETCH_COLUMN|PDO::FETCH_GROUP as per the Php.net website, but it does not work either because I get nothing.
One of Yii's strengths is it's ActiveRecord, so why not use it?
Make your budget to a separate table (so you can generate a model from it). Reference it from your "datatable".
CREATE TABLE budget (
id INTEGER PRIMARY KEY,
name TEXT
);
CREATE TABLE datatable(
column1 TEXT,
column2 TEXT,
...
budget_id INTEGER,
FOREIGN KEY(budget_id) REFERENCES budget(id)
);
Next generate models with Gii, and now you can use your newly made relations like this:
$budget = Budget::model()->findByAttributes( ["name"=>"budget2"] );
foreach( $budget->datatables as $dt ) {
echo $dt->column1;
echo $dt->column2;
}
(I know. Not the array you asked for. Sorry if I'm way off with this.)
Alright, the bottom line is that I was not able to find a way to do this right thru Yii, so I did it with a more hands-on approach.
The first thing I did was basically initiate a database connection thru Yii.
$command = Yii::app()->db //outputs CDbConnnection
The next thing I did was get a PDO class from the connection:
$pdoinstance = $command->getPdoInstance(); //outputs PDO class
From this point, it was help obtained from PHP.net and another question posted on this forum:
$pdostatement=$pdoinstance->prepare('SELECT BUDGET_CODE,
PAY_ITEM, ITEM, DESCRIPTION FROM bidcost');
$pdostatement->execute();
//default fetch mode could not be set
# $pdostatement->setfetchmode(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);
//returns array
$testarray=$pdostatement->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);

Categories