Adding an increment variable along with id name for a textbox not working in yii1 PHP framework - yii

I am creating a table in controller and passing it to view as AJAX response.Inside this table there is dropdown for each rows.When I select 'Other' option value I have to show a textbox near that dropdown in same column itself and save the value in each textbox.
Inorder to make each textbox id unique I am appending an Incrementalvariable $s1 along with 'othermerits-'.e.g. - id="othermerits-2".But when I inspect the element it shows only id="othermerits".I am giving my code sample below written in my controller.Please refer 'else' part.
if (isset($_POST['date'])) {
$date = $_POST['date'];
$academic = Academic::model()>findByAttributes(array('status' => 1));
$students = Student::model()>findAllByAttributes(array('courseid' => $courseid, 'batchid' => $batchid));
$sendtable = "";
$sl = 1;
foreach ($students as $student) {//! for each student studentid,
student admission number and name is send to form
$teacher = Teachercomments::model()>findByAttributes(array('studentid' => $student->studentid, 'courseid' =>
$courseid, 'batchid' => $batchid, 'date' => $date, 'academicid' =>
$academic->academicid, 'userid' => Yii::app()->user->userid, 'usertypeid' =>
Yii::app()->user->usertypeid));
if (isset($teacher)) {
$sendtable = $sendtable . '<tr><td data-id="' .
$student->studentid . '">' . $sl . '</td><td>' . $student->student_firstname
. " " . $student->student_middlename . " " . $student->student_lastname .
'</td><td>' . '<input type="text" name="merits" id="merits" value="' .
$teacher->merit . '" class="merits"></td><td><input type="text" value="' .
$teacher->demerit . '" name="demerits" class="demerits"></td></tr>';
} else {
$sendtable = $sendtable . '<tr><td data-id="' . $students->studentid . '">'
. $sl . '</td><td>' . $students->student_firstname . " " . $students->student_middlename . " " . $students->student_lastname . '</td><td><select
name="merits" id="merits" class="merits"
onchange="GetSelectedTextValue(this,'.$s1.')"><option value="Good
Discipline">Good Discipline</option><option value="Good Listener">Good
Listener</option><option value="Other">Other</option></select><input
type="text" name="othermerits" id="othermerits-'.$s1.'" class="merits"
style=""/></td><td><select name="demerits" class="demerits"><option
value="Careless">Careless</option><option value="Bad Listener">Bad
Listener</option><option value="Other">Other</option></select></td></tr>';
}
$sl = $sl + 1;
}
echo $sendtable;
}

I don't know if it's a typo but on this tow lines you use $s1
<select name="merits" id="merits" class="merits" onchange="GetSelectedTextValue(this,'.$s1.')">
<input type="text" name="othermerits" id="othermerits-'.$s1.'" class="merits" style=""/>
and your imcrement variable is $sl
$sl = $sl + 1;

Related

How to Direct access through the database query to product name , product price and permalink and product photo columns

How do I get Direct access through the database query to product name , product price ,permalink , and image url of product in WordPress WooCommerce ?!
what's the sql query ?
global $wpdb;
$metas = array(
'_thumbnail_id', '_regular_price'
);
foreach ($metas as $i=>$meta_key) {
$meta_fields[] = 'm' . $i . '.meta_value as ' . $meta_key;
$meta_joins[] = ' left join ' . $wpdb->postmeta . ' as m' . $i . ' on m' . $i . '.post_id=' . $wpdb->posts . '.ID and m' . $i . '.meta_key="' . $meta_key . '"';
}
$request = "SELECT ID, post_title, " . join(',', $meta_fields) . " FROM $wpdb->posts ";
$request .= join(' ', $meta_joins);
$request .= " WHERE post_status='publish' AND post_type='product' AND $wpdb->posts.post_title like '%sample%'";
$product_details = $wpdb->get_row($request, OBJECT);
if(!empty($product_details)){
$qry = "SELECT guid FROM $wpdb->posts WHERE ID=" . $product_details->_thumbnail_id;
$uri_obj = $wpdb->get_row($qry, OBJECT);
$product_details->_thumbnail_id = $uri_obj->guid;
}
echo '<pre>';print_r($product_details);exit;

Create multiple variable from foreach loop

I have this script that gets weather data from a API.
But I need to have the temperatures of every day in seperate strings.
$day1Max, $day1Min, $day2Max, $day2Min, etc...
Is it possible to get these variables from a foreach loop?
<?php
$conditions_week = $forecast->getForecastWeek($latitude, $longitude);
echo "Forecast this week:\n";
foreach($conditions_week as $conditions) {
?>
<tr>
<th><?php echo $conditions->getTime('Y-m-d') . ': ' . $conditions->getMaxTemperature() . "\n"; ?></th>
<th><?php echo $conditions->getTime('Y-m-d') . ': ' . $conditions->getMinTemperature() . "\n"; ?></th>
</tr>
<?php
}
?>
This is the output:
Here is your solution :
<?php
class Conditions{
function __construct($min,$max){
$this->max = $max;
$this->min = $min;
}
function getMaxTemperature(){
return $this->max;
}
function getMinTemperature(){
return $this->min;
}
}
$conditions_week = array(new Conditions(5,10),new Conditions(-5,3));
echo "Forecast this week:\n";
foreach($conditions_week as $k=>$conditions) {
$varMin = "day".($k+1)."min";
$varMax = "day".($k+1)."max";
$$varMin = $conditions->getMinTemperature();
$$varMax = $conditions->getMaxTemperature();
?>
<tr>
<th><?php echo "Max : ". $conditions->getMaxTemperature() . "\n"; ?></th>
<th><?php echo "Min : ". $conditions->getMinTemperature() . "\n"; ?></th>
</tr>
<?php
}
echo "day1min : " . $day1min;
echo '<br>';
echo "day1max : " . $day1max;
echo "<hr>";
echo "day2min : " . $day2min;
echo '<br>';
echo "day2max : " . $day2max;
You to generate your php variables $day1min, $day1max... inside the foreach and then you can use it outside the loop.
Here's the full example : https://3v4l.org/vX5bW

How to resize image by imagine extension in yii2

I use the bellow function to resize images after upload to show on my post.
but it works just for images larger than 500px 300px. when I upload image smaller than this size, my website images row breaks down.
use yii\imagine\Image;
public function upload() {
$this->pictureFile->saveAs('../files/upload/' . $this->pictureFile->baseName . '.' . $this->pictureFile->extension);
Image::thumbnail('../files/upload/' . $this->pictureFile, 500, 300)
->save('../files/upload/thumbnail-500x300/' . $this->pictureFile->baseName . '.' . $this->pictureFile->extension,
['quality' => 70]);
unlink('../files/upload/' . $this->pictureFile->baseName . '.' . $this->pictureFile->extension);
}
Instead of Image::thumbnail, try the following
$imagine = Image::getImagine();
$image = $imagine->open('../files/upload/' . $this->pictureFile);
$image->resize(new Box(500, 300))->save('../files/upload/thumbnail-500x300/' . $this->pictureFile->baseName . '.' . $this->pictureFile->extension, ['quality' => 70]);
Haven't tested it but since yii's Image is just a wrapper over Imagine library, this should work with minor changes (if at all needed).
And yes, you need to use Imagine\Image\Box; in your file before using the code above.
Use resize method as below
use yii\imagine\Image;
use Imagine\Image\Box;
public function upload() {
$this->pictureFile->saveAs('../files/upload/' . $this->pictureFile->baseName . '.' . $this->pictureFile->extension);
Image::thumbnail('../files/upload/' . $this->pictureFile, 500, 300)
->resize(new Box(500,300))
->save('../files/upload/thumbnail-500x300/' . $this->pictureFile->baseName . '.' . $this->pictureFile->extension,
['quality' => 70]);
unlink('../files/upload/' . $this->pictureFile->baseName . '.' . $this->pictureFile->extension);
}
Yii::setAlias('newsfolder', dirname(dirname(__DIR__)) . '/frontend/web/extraimages/');
$model->img = UploadedFile::getInstance($model,'img');
if (!empty($model->img)){
$model->img->saveAs( Yii::getAlias('#newsfolder/').$filename.'.'.$model->img->extension );
$model->img = $filename.'.'.$model->img->extension;
$imagine = Image::getImagine();
$image = $imagine->open(Yii::getAlias('#newsfolder/'.$model->img));
$image->resize(new Box(500, 300))->save(Yii::getAlias('#newsfolder/'.$model->img, ['quality' => 70]));
}
$imagine = Image::getImagine();
$imagine = $imagine->open($openPath);
$sizes = getimagesize ( $openPath );
/*
[0] => 604
[1] => 244
[2] => 3
[3] => width="604" height="244"
[bits] => 8
[mime] => image/png
) */
$width = 200;
$height = round($sizes[1]*$width/$sizes[0]);
$imagine = $imagine->resize(new Box($width, $height))->save($savePath, ['quality' => 60]);

How can I convert this to use PDO?

I would like to use PDO for selecting (searching) a database.
The search 'form' has MULTIPLE fields that can be used.. 1 or many can be filled in to help refine the search. (or there can be many o them left blank/empty)
here is what I have been using (locally):
//localhost details
$db_username="root"; //database user name
$db_password="";//database password
$db_database="test"; //database name
$db_host="localhost";
mysql_connect($db_host,$db_username,$db_password);
#mysql_select_db($db_database) or die("Unable to connect to database.");
if(isset($_POST['submit'])) {
// define the list of fields
$fields = array('first', 'trialdate', 'wcity', 'wstate', 'plantif');
$conditions = array();
//loop through the defined fields
foreach($fields as $field){
// if the field is set and not empty
if(isset($_POST[$field]) && $_POST[$field] != '') {
// create a new condition while escaping the value inputed by the user (SQL Injection)
$conditions[] = "`$field` LIKE '%" . mysql_real_escape_string($_POST[$field]) . "%'";
}
}
//build the query
$query = "SELECT * FROM myTable ";
// if there are conditions defined
if(count($conditions) > 0) {
// append the conditions
$query .= "WHERE " . implode (' OR ', $conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
}
$result = mysql_query($query);
if(isset($_POST['submit'])) {
while($row = mysql_fetch_array($result)) {
echo $row['first'] . "<br />"; //individual value
//build panels that displays everything from row..etc
}
}
}
this has been working fine... but I'd like convert to using the PDO approach.
I gave it a few tries...but am missing something here..
heres what I've tried so far..
//localhost details
$db_username="root"; //database user name
$db_password="";//database password
$db_database="test"; //database name
$db_host="localhost";
//PDO DB connection
$conn = new PDO('mysql:host='.$db_host.'dbname='.$db_database.'charset=utf8', $db_username, $db_password);
if(isset($_POST['submit'])) {
$stmt = $conn->prepare('SELECT * FROM myTable WHERE first LIKE :first OR trialdate LIKE :trialdate OR wcity LIKE :wcity OR wstate LIKE :wstate OR plantif LIKE :plantif');
//build query placeholders (*note: use bindValue for $_POST values)
$stmt->bindValue(':first', '%' . $_POST['first'] . '%');
$stmt->bindValue(':trialdate', '%' . $_POST['trialdate'] . '%');
$stmt->bindValue(':wcity', '%' . $_POST['wcity'] . '%');
$stmt->bindValue(':wstate', '%' . $_POST['wstate'] . '%');
$stmt->bindValue(':plantif', '%' . $_POST['plantif'] . '%');
$stmt->execute();
foreach ($stmt as $row) {
// do something with $row
echo $row['first'] . "<br />"; //individual value
}
}
I could use help on getting the PDO example working with a displayed result/row/value?

shopping cart to email

I use simplecartjs to make a shopping cart on my website where you can select element and send it to your cart... next step, will be the checkout process, but for business reason, no checkout process will append, and a simple form with name and email and date for order pickup will be ask. Now the order must be send to an email address (at the company) that will fullfill the order.
The question : how to send the content of the cart to an email body or as attachement ?
This Will add the email order, suplimentary fields to the user "Phone and Adress",
Check during the CheckOut the the user is registered if not will redirect to registration.
WILL CLEAR Shopping cart only after succesful email order sent.
Will send 2 e-mail to the shop owner "shop#domain.com" and to the users email so he sees the order
Will need to make a new page for the Thank You part after succesful order is made
simplecartjs: around line 288 is in mine
me.emailCheckout = function() {
itemsString = "";
for( var current in me.items ){
var item = me.items[current];
itemsString += item.name + " " + item.quantity + " " + item.price + "\n";
}
var form = document.createElement("form");
form.style.display = "none";
form.method = "POST";
form.action = "sendjs.php";
form.acceptCharset = "utf-8";
form.appendChild(me.createHiddenElement("jcitems", itemsString));
form.appendChild(me.createHiddenElement("jctotal", me.total));
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
sendjs.php
<?php require( dirname(__FILE__) . '/wp-load.php' );
/* cheking is user is logged in*/
if ( is_user_logged_in() ) {
get_currentuserinfo(); /* getting user details*/
/* sending e-mail to the shop email */
$to = 'shop#domain.com';
$subject = 'New Order';
$jcitems = " Name: " . $current_user->user_lastname .
" \n First Name: " . $current_user->user_firstname .
" \n Email: " . $current_user->user_email .
" \n Phone: " . $current_user->phone .
" \n Adress: " . $current_user->adress ;
$headers = 'From: shop#domain.com' . "\r\n" .
'Reply-To: shop#domain.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $jcitems, $headers);
/* sending e-mail with the order to the users email*/
$to = $current_user->user_email;
$subject = 'Order copy from Domain';
$jcitems = "Thank you for you order. Below you have your ordered products".
" \n ORDER: \n\n " . $_POST['jcitems'] . "Total: " . $_POST['jctotal'] . " USD" .
"\n\n http://www.domain.com \nshop#domain.com";
$headers = 'From: shop#domain.com' . "\r\n" .
'Reply-To: shop#domain.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $jcitems, $headers);
/*Clearing the cart info after succesfull order is made*/
setcookie ("simpleCart", "", time() - 3600);
/*redirecting user to Thank you page from Wordpress*/
Header('Location: http://www.domain.com/thank_you/'); }
else { /*sending user to register*/
header( 'Location: http://www.domain.com/wp-login.php?action=register' ) ; exit; } ?>
You will need Register Plus plugin for wordpress to add the extra 2 fiels to the user "phone and address"
be sure to check
Add Registration Field
Add Profile Field
Required
You should add new checkout method to simplecartjs:
me.emailCheckout = function() {
itemsString = "";
for( var current in me.items ){
var item = me.items[current];
itemsString += item.name + " " + item.quantity + " " + item.price + "\n";
}
var form = document.createElement("form");
form.style.display = "none";
form.method = "POST";
form.action = "sendjs.php";
form.acceptCharset = "utf-8";
form.appendChild(me.createHiddenElement("jcitems", itemsString));
form.appendChild(me.createHiddenElement("jctotal", me.total));
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
This will create new form element and submit cart data to sendjs.php. Enable this checkout method by setting me.checkoutTo = 'Email' in simplecart options.
Now create a new sendjs.php file:
<?php
$to = 'you#example.com';
$subject = 'the subject';
$jcitems = $_POST['jcitems'];
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $jcitems, $headers);
Header('Location: thankyou.html');
?>
This will send the email message and redirect to thankyou.html page you should also create.