Show a part of a text according to user - php

I have a form that has 3 types of options:
<form action="main.php?page=values" method="post">
<select name=values>
<option value="A">1</option>
<option value="B">2</option>
<option value="C">3</option>
</select>
</form>
In the page "values", there is the insert into a MySql db, and every option has a sample text.
if (query('get',$_POST['values'])=='A') {
$text = "Text A (Sub-text A)";
} elseif (query('get',$_POST['values'])=='B') {
$text = "Text B (Sub-text B)";
} elseif (query('get',$_POST['values'])=='C') {
$text = "Text C (Sub-text C)";
}
query_ok("INSERT INTO chat (id, user, text) VALUES ('$id', '$login', '$text')");
When I have to select and show this insert, I would like to show this text in 2 different ways:
a) If user = $login -> Text A/B/C (Sub-text A/B/C)
b) If user != $login -> Text A/B/C
What can I do in order to have this result.
This is the select part:
$show= query_ok("SELECT chat.*, user.*
FROM chat
LEFT JOIN user ON user.name = chat.user
WHERE chat.id = ".$_SESSION['id_chat']."
ORDER BY id", 'result');
while ($row = query_ok($show, 'fetch'))
{
//results
}

Use array, ex :
if (query('get',$_POST['values'])=='A') {
$text = [
'user' => 'Text A (Sub-text A)',
'not_user' => 'Text A'
];
} elseif (query('get',$_POST['values'])=='B') {
$text = [
'user' => 'Text B (Sub-text B)',
'not_user' => 'Text B'
];
} elseif (query('get',$_POST['values'])=='C') {
$text = [
'user' => 'Text C (Sub-text C)',
'not_user' => 'Text C'
];
}
AND
a) If user = $login -> $text['user]
b) If user != $login -> $text['not_user]

Related

repeating a php code without coding multiple times

This is my code:
if (preg_match('/^\/start (.*)/', $text, $match) or preg_match('/^\/get_(.*)/', $text, $match)) {
$id = $match[1];
if (isJoin($from_id)) {
$fileData = mysqli_query($db, "SELECT * FROM `file` WHERE `id` = '{$id}'");
$file = mysqli_fetch_assoc($fileData);
if (mysqli_num_rows($fileData)) {
if ($file['password']) {
sendMessage($from_id, "please send pass :", "markdown", $btn_back, $message_id);
mysqli_query($db, "UPDATE `user` SET `step` = 'password', `getFile` = '$id' WHERE `from_id` = '$from_id'");
} else {
$downloads = number_format($file['downloads']);
$downloads++;
$caption = urldecode($file['caption']);
Ilyad("send{$file['type']}", [
'chat_id' => $from_id,
$file['type'] => $file['file_id'],
'caption' => "📥 count : <code>{$downloads}</code>\n{$caption}\n Thanks",
'parse_mode' => "html",
]);
Ilyad("send{$file['type']}", [
'chat_id' => $from_id,
$file['type'] => $file['file_id2'],
'caption' => "📥 count : <code>{$downloads}</code>\n{$caption}\n Thanks",
'parse_mode' => "html",
]);
mysqli_query($db, "UPDATE `file` SET `downloads` = `downloads`+1 WHERE `id` = '$id'");
mysqli_query($db, "UPDATE `user` SET `step` = 'none', `downloads` = `downloads`+1 WHERE `from_id` = '$from_id'");
}
} else sendMessage($from_id, "hi welcome to bot", 'markdown', $btn_home, $message_id);
} else {
joinSend($from_id);
mysqli_query($db, "UPDATE `user` SET `getFile` = '$id' WHERE `from_id` = '$from_id'");
}
}
so what i want to do is repeat this code like 24 times but each time the number at the end of file_id changes like file_id1, file_id2, file_id3, ..., file_id24.
and the values for file_id1, ... and others are stored on my SQL database.
Now if you see there is two codes repeating and the only change is the number at the end of file_id so i want to make it 24 codes but instead of just repeating it I want to do it with one code.
and another thing I said 1 to 24 can i also do something so it reads the last number from a database value to like loop from 1 to x and x is the number i entered in database.
sorry i'm new to programming.
All you need to do is wrap that code in a for loop that increments 1..N. Then in the body of the loop, append / interpolate the loop increment variable where you need it.
for ($i = 1; $i <= 24; $i++) {
// ...
("send{$file['type']}", [
'chat_id' => $from_id,
$file['type'] => $file["file_id$i"],
'caption' => "📥 Count : <code>{$downloads}</code>\n{$caption}\n🟡 Thanks",
'parse_mode' => "html",
]);
}

multi insert row & table codeigniter

i have 1 form new customer, which will insert into 2 table('tbcust' & 'tbcp'). I add button 'add new contact person' for insert row in table 'tcp', the button save in form will insert multiple table. table 'tbcust' is ok, but row 'nama_pt' in table 'tbcp' just passing 1 character.
CONTROLLER
public function post_multiple_table(){
$this->load->model('Multiple_model', 'multi_model', TRUE);
$cust_input_data = array();
//$cp_input_data = array();
$cust_input_data['nama_pt'] = $this->input->post('nama_pt');
$cust_input_data['tipe'] = $this->input->post('tipe');
$cust_input_data['alamat'] = $this->input->post('alamat');
$cust_input_data['email_cust'] = $this->input->post('email_cust');
$cust_input_data['notelp'] = $this->input->post('notelp');
$cust_input_data['nofax'] = $this->input->post('nofax');
$this->form_validation->set_rules('nama_orang[]', 'nama_orang', 'required|trim|xss_clean');
$this->form_validation->set_rules('nama_pt', 'nama_orang', 'required|trim|xss_clean');
$this->form_validation->set_rules('nohp[]', 'nohp', 'required|trim|xss_clean');
$this->form_validation->set_rules('email[]', 'email', 'required|trim|xss_clean');
if ($this->form_validation->run() == FALSE){
echo validation_errors(); // tampilkan apabila ada error
}else{
$nm = $this->input->post('nama_orang');
$result = array();
foreach($nm AS $key => $val){
$result[] = array(
"nama_orang" => $_POST['nama_orang'][$key],
"nama_pt" => $_POST['nama_pt'][$key],
"nohp" => $_POST['nohp'][$key],
"email" => $_POST['email'][$key]
);
}
model
public function create_multiple_tabel($nama_pt, $nama_orang){
$this->db->insert('tbcust', $nama_pt);
$this->db->insert_batch('tbcp', $nama_orang);
}
and this the form & database
Check in table tbcp if your row nama_pt have length set 1, and put 15 or higher if need.

Prepare SQL statements and enter only if not duplicates

I am creating a Sales Order form for the small business I work for. I have a form that connects to a database for drop-down menus and then text boxes to add new data if needed. There are four more sections that can appear if all data boxes are filled in in the section prior.
The inputs that link to the database include Company, Customer, Tool and Part And then there is a Description to enter on work to be done. So once Tool, Part, and Description have been filled in, a second section with another Tool, Part, and Description come into view. I have a script I have called Update.php that determines what fields have been filled and thus what to enter into the database. What I have been trying to do is to avoid duplicate entries. So if on the first section a UpdateNewTool has been inputted and then on the second section that is put into that field again to associate another Part with it, that data will be inserted twice. How can I go about throwing out one of those input statements?
My update.php code:
<?php
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "Sales_Orders";
$UpdateCompany=$_POST['UpdateCompany'];
$UpdateNewCompany=$_POST['UpdateNewCompany'];
$UpdateCustomer=$_POST['UpdateCustomer'];
$UpdateNewCustomer=$_POST['UpdateNewCustomer'];
$UpdateTool=$_POST['UpdateTool'];
$UpdateTool2=$_POST['UpdateTool2'];
$UpdateTool3=$_POST['UpdateTool3'];
$UpdateTool4=$_POST['UpdateTool4'];
$UpdateNewTool=$_POST['UpdateNewTool'];
$UpdateNewTool2=$_POST['UpdateNewTool2'];
$UpdateNewTool3=$_POST['UpdateNewTool3'];
$UpdateNewTool4=$_POST['UpdateNewTool4'];
$UpdateNewPart=$_POST['UpdateNewPart'];
$UpdateNewPart2=$_POST['UpdateNewPart2'];
$UpdateNewPart3=$_POST['UpdateNewPart3'];
$UpdateNewPart4=$_POST['UpdateNewPart4'];
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$data = [];
// BEGIN CONDITIONAL STATEMENTS
// New Company added by itself
if (!empty($UpdateNewCompany)) {
$data[] = [ '1', $UpdateNewCompany, $UpdateNewCompany, NULL ];
$data[] = [ '2', '', '', $UpdateNewCompany ];
$data[] = [ '3', '', '', $UpdateNewCompany ];
}
//Using the Company Drop-down box
if (!empty($UpdateCompany)) {
$UpdateNewCompany = $UpdateCompany; // If there is no new company inserted, $UpdateNewCompany becomes $UpdateCompany
if (!empty($UpdateNewCustomer)) {
$data[] = [ '2', $UpdateNewCustomer, $UpdateNewCustomer, $UpdateNewCompany ];
}
if (empty($UpdateTool)) { //If there is a new tool to add
if (!empty($UpdateNewTool)) {
$data[] = [ '3', $UpdateNewTool, $UpdateNewTool, $UpdateNewCompany ];
$data[] = [ '4', '', '', $UpdateNewTool ];
}
if (!empty($UpdateNewPart)) {
$data[] = [ '4', $UpdateNewPart, $UpdateNewPart, $UpdateNewTool ];
}
}
if (!empty($UpdateTool)) { // If there is no new tool to add
$UpdateNewTool = $UpdateTool;
if (!empty($UpdateNewPart)) {
$data[] = [ '4', $UpdateNewPart, $UpdateNewPart, $UpdateNewTool ];
}
}
//Part 2
if (empty($UpdateTool2)) { //If there is a new tool to add
if (!empty($UpdateNewTool2)) {
$data[] = [ '3', $UpdateNewTool2, $UpdateNewTool2, $UpdateNewCompany ];
$data[] = [ '4', '', '', $UpdateNewTool2 ];
}
if (!empty($UpdateNewPart2)) {
$data[] = [ '4', $UpdateNewPart2, $UpdateNewPart2, $UpdateNewTool2 ];
}
}
if (!empty($UpdateTool2)) { // If there is no new tool to add
$UpdateNewTool2 = $UpdateTool2;
if (!empty($UpdateNewPart2)) {
$data[] = [ '4', $UpdateNewPart2, $UpdateNewPart2, $UpdateNewTool2 ];
}
}
//Part 3
if (empty($UpdateTool3)) { //If there is a new tool to add
if (!empty($UpdateNewTool3)) {
$data[] = [ '3', $UpdateNewTool3, $UpdateNewTool3, $UpdateNewCompany ];
$data[] = [ '4', '', '', $UpdateNewTool3 ];
}
if (!empty($UpdateNewPart3)) {
$data[] = [ '4', $UpdateNewPart3, $UpdateNewPart3, $UpdateNewTool3 ];
}
}
if (!empty($UpdateTool3)) { // If there is no new tool to add
$UpdateNewTool3 = $UpdateTool3;
if (!empty($UpdateNewPart3)) {
$data[] = [ '4', $UpdateNewPart3, $UpdateNewPart3, $UpdateNewTool3 ];
}
}
//Part 4
if (empty($UpdateTool4)) { //If there is a new tool to add
if (!empty($UpdateNewTool4)) {
$data[] = [ '3', $UpdateNewTool4, $UpdateNewTool4, $UpdateNewCompany ];
$data[] = [ '4', '', '', $UpdateNewTool4 ];
}
if (!empty($UpdateNewPart4)) {
$data[] = [ '4', $UpdateNewPart4, $UpdateNewPart4, $UpdateNewTool4 ];
}
}
if (!empty($UpdateTool4)) { // If there is no new tool to add
$UpdateNewTool4 = $UpdateTool4;
if (!empty($UpdateNewPart4)) {
$data[] = [ '4', $UpdateNewPart4, $UpdateNewPart4, $UpdateNewTool4 ];
}
}
}
$insert = $conn->prepare("INSERT INTO Sales_Orders_dynlist_items (listid,name,value,parent) VALUES (?, ?, ?,?)");
if ( $insert === false ) {
echo "Error:".$conn->error;
die;
}
foreach ( $data as $item ){
if ( $insert->bind_param("ssss", ...$item) === false ) {
echo "Error:".$conn->error;
}
if ( $insert->execute() === false ) {
echo "Error:".$conn->error;
}
}
$conn->close();
?>
I'm pretty sure the place that needs work will be:
foreach ( $data as $item ){
if ( $insert->bind_param("ssss", ...$item) === false ) {
echo "Error:".$conn->error;
}
if ( $insert->execute() === false ) {
echo "Error:".$conn->error;
}
}
So for instance, sometimes we will need different parts with the same tool number. Therefore, if the user puts in a new job number such as "1234" and Part "abcd" then a description as to what's done. Then in the next section, "1234" isn't in the dropbox yet as it hasn't been added to the database yet. So the user puts "1234" in the tool again but "dcba" as the part and another description. Once submitted there will be two entries in the database with ['3', '1234', '1234', 'Whatever Company'];
Thanks for any input!
So I decided to take a different approach at this. What I ended up doing was set up a javascript script that determined if the NewTool input box was empty and if not, add that input value as an option to the Tool2 and so on boxes. The javascript is as follows:
function addOpTool() {
if(document.getElementById('NewTool').value != '') {
var x = document.getElementById("Tool2");
var y = document.getElementById("Tool3");
var z = document.getElementById("Tool4");
var test = document.getElementById("NewTool");
var option = document.createElement("option");
var option2 = document.createElement("option");
var option3 = document.createElement("option");
option.text = test.value;
option2.text = test.value;
option3.text = test.value;
x.add(option);
y.add(option2);
z.add(option3);
}
}
function addOpTool2() {
if(document.getElementById('NewTool2').value != '') {
var y = document.getElementById("Tool3");
var z = document.getElementById("Tool4");
var test = document.getElementById("NewTool2");
var option2 = document.createElement("option");
var option3 = document.createElement("option");
option2.text = test.value;
option3.text = test.value;
y.add(option2);
z.add(option3);
}
}
function addOpTool3() {
if(document.getElementById('NewTool3').value != '') {
var z = document.getElementById("Tool4");
var test = document.getElementById("NewTool3");
var option3 = document.createElement("option");
option3.text = test.value;
z.add(option3);
}
}
I added these functions to the appropriate onchange of NewTool, NewTool2, and NewTool3.
So for instance the user inputs "1234" in NewTool and "LH-Side" in NewPart. Then in the following form section there is now an option of "1234" in the Tool2 dropdown box and the user can just select that and then input "RH-Side" in NewPart2.
When submitting the form, only ONE instance of the tool# "1234" will be put into the database, solving the problem I was running into!

CButtonColumn approve button executes PHP code without being clicked

I have this code that would create and populate a table in Yii CGridView.
My problem is the function located in the 'approve'=>array('options'=>array('onclick')) is being called for every refresh of the page even if the approve button isn't clicked.
I determined the mistake occurs by printing the value of the counter. The counter should only increment by 1 when approved is clicked not for every refresh of the page.
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'registrants-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'user_id',
'first_name',
'middle_name',
'last_name',
'gender',
'shirt_size',
'receipt_number',
'category',
array(
'class'=>'CButtonColumn',
'template'=>'{approve}, {update},{delete}',
'buttons'=>array(
'approve' => array(
'label'=>'Approve',
'options'=>array(
'onclick'=> $model->approveRegistrants($model->user_id, $model->category),
//ending approve-option array
),
//ending approve-button array
),
//ending buttons array
)
//ending table-last-column array
),
//ending table-columns array
),
//ending zii.widgets.grid.CGridview
));
?>
This is my function in my model.
public function approveRegistrants($user_id, $category){
$db = new PDO('mysql:host=localhost; dbname=secret; charset=utf8', 'Andy', '*****');
$getCounter = "SELECT registrants FROM counter order by registrants desc limit 1;";
$bool = false;
$show = '0';
do{
$result = $db->query($getCounter);
// $registrants = $db->query($getCounter);
// $result->setFetchMode(PDO::FETCH_ASSOC);
// $registrants = '1';
foreach ($result as $value){
$registrants = $value['registrants'];
echo 'hello'.$registrants.'</br>';
}
// $registrants = $result['registrants'];
// print_r($registrants);
$max_registrants = '3400';
if($max_registrants > $registrants){
// pdo that will use $updateCounterByOne
$updateCounterByOne = "UPDATE counter set registrants = registrants + 1 WHERE registrants = ". $registrants .";";
$updateCounter = $db->prepare($updateCounterByOne);
$updateCounter->execute();
// return affected rows
$returnAffectedRows = $updateCounter->rowCount();
$bool = true;
// break;
}
else{
echo "No more slot Available";
// break;
}
}while($returnAffectedRows == '0');
if($bool = true){
//sql syntax
$selectApprovedUser = "SELECT user_id FROM registrants WHERE user_id = '". $user_id ."';";
//pdo that will use $selectApprovedUser
$updateApprovedUser = "UPDATE registrants set approved = 'YES' where user_id = ". $selectApprovedUser .";";
$updateApproved = $db->prepare($updateApprovedUser);
$updateApproved->execute();
//pdo that will use $insertApprovedUser
$insertApprovedUser = "INSERT INTO approved_registrants (user_id, category, approved_date) VALUES ('".$user_id."', '".$category."', 'curdate()');";
$insertApproved = $db->prepare($insertApprovedUser);
$insertApproved->execute();
//execute trial
$selectSomething = "SELECT registrants from counter where tandem = '0'";
$doSelect = $db->prepare($selectSomething);
$doSelect->execute();
$hello = $doSelect->fetchAll();
echo $hello[0]['registrants'];
}
}
What I'm trying to achieve is when approve button is clicked it will get the user_id and will do the PDO commands such as the update and insert.
If you see CButtonColumn, it states that 'options' takes in key-value pairs for the HTML tag attributes. Therefore, you should not place PHP code here like what you did here, unless you want them executed immediately. This is wrong:
'options'=>array(
'onclick'=> $model->approveRegistrants($model->user_id, $model->category),
),
What you want is a TbToggleColumn column from YiiBooster extension to approve/unapprove items:
array(
'class' => 'bootstrap.widgets.TbToggleColumn',
'toggleAction' => 'user/toggleApproved',
'name' => 'isApproved',
'header' => 'Approved?'
),
You will also need a corresponding action in the controller. Don't forget to add 'toggleApproved' to the controller filters. In this example, I have simply inverted the value of a single column, but you may do other stuff with this action.
public function actionToggleApproved($id) {
$model = $this->loadModel($id);
if(!is_null($model) && $model->hasAttribute('isApproved')) {
$model->isApproved = $model->isApproved == 0 ? 1 : 0;
$model->update(); // no validation
}
}

Hook to Add a Value in a SugarCRM Custom Field

I am new to SugarCRM. I've created a custom field named 'account name' in the Meetings module so that if we select Contacts from related to field, the 'account name' of that Contact is automatically added to the field.
Here's my code:
$hook_array['after_retrieve'] = Array();
$hook_array['after_retrieve'][] = Array(1, 'Add custom account',
'custom/modules/Meetings/AddAccount.php','AddAccount', 'addAcc');
LogicHook:
class AddAccount
{
public function addAcc(&$bean, $event, $arguments)
{
global $current_user;
global $db;
echo "<pre>";
$meeting_id = $_REQUEST['record'];
$query = "SELECT * FROM `meetings_contacts` WHERE `meeting_id` LIKE '$meeting_id'";
$result = $bean->db->query($query, true, " Error filling in additional detail fields: ");
if ($bean->db->getRowCount($result) > 0) {
while ($row = $bean->db->fetchByAssoc($result)) {
$contact_id = $row['contact_id'];
}
if (isset($contact_id)) {
$query1 = "SELECT * FROM `accounts_contacts` WHERE `contact_id` LIKE '$contact_id'";
$result1 = $bean->db->query($query1, true, " Error filling in additional detail fields: ");
while ($row1 = $bean->db->fetchByAssoc($result1)) {
$account_id = $row1['account_id'];
}
$query2 = "SELECT * FROM `accounts` WHERE `id` LIKE '$account_id'";
$result2 = $bean->db->query($query2, true, " Error filling in additional detail fields: ");
while ($row2 = $bean->db->fetchByAssoc($result2)) {
$account_name = $row2['name'];
}
$update_custom_account = "UPDATE `meetings_cstm` SET `accountname_c` = '$account_name' WHERE `meetings_cstm`.`id_c` = '$meeting_id';";
$Change = $bean->db->query($update_custom_account);
}
}
}
}
The problem is that the field is getting added but the "i" in the ListView has stopped working. Is there a simpler way than this long query?
Thanks in advance.
This is a better way of doing the above.
custom/modules/Meetings/logic_hooks.php
// position, file, function
$hook_array['after_retrieve'] = Array();
$hook_array['after_retrieve'][] = Array(1, 'Add custom account', 'custom/modules/Meetings/AddAccount.php', 'AddAccount', 'getAccountName');
$hook_array['after_save'] = Array();
$hook_array['after_save'][] = Array(1, 'Add custom account', 'custom/modules/Meetings/AddAccount.php', 'AddAccount', 'getAccountName');
custom/modules/Meetings/AddAccount.php
class AddAccount {
public function getAccountName(&$bean, $event, $arguments) {
if ($bean->parent_type == 'Contacts') {
$contact = BeanFactory::getBean('Contacts', $bean->parent_id);
$contact->load_relationship('accounts_contacts');
$account = BeanFactory::getBean('Accounts', $contact->account_id);
$bean->account_name_c = $account->name;
}
}
}
This way, you are using the bean and not SQL.
EDIT:
To add the new field, you can create this file…
custom/Extension/modules/Meetings/Ext/Vardefs/account_name_c.php
<?php
$dictionary['Meeting']['fields']['account_name_c'] =
array (
'name' => 'account_name_c',
'vname' => 'LBL_ACCOUNT_NAME_C',
'type' => 'varchar',
'len' => '255',
'unified_search' => true,
'comment' => 'Account name for meeting',
'studio' => 'true',
);
Then after a Repair/Rebuild, go to Studio > Meetings > Layouts > ListView and drag/drop the new field from 'Hidden' to 'Default.' Select the 'Save & Deploy' button, and after saving the Meeting record, your account name will appear in the list view.

Categories