if condition in sql | codeigner - sql

I have 2 table, one for:
user information
second for:
"user last activity"
I have code to fetch and display all user on the page, each user should display his state, - everything is work as shown in my code
BUT
I want to make my code clean, so I want to move the "if
condition" in my view page to model page when the state is empty in
the table,
I want to display all my user with users state in my page without
using if condition in the view page.
My code:
DataBase:
My Page:
View:
<?php foreach($Users as $c){ ?>
<th>Firstname</th>
<th>Lastname</th>
<th>Last Activity Time</th>
<th>State</th>
<th>User ID</th>
</tr>
<tr>
<td><?php echo $c->email ?></td>
<td><?php echo $c->type ?></td>
<td><?php echo $c->last_activity ?></td>
<td>
<!-- this code is run good , but i want to change it to contolloer to make the code clean ,
and if i changed to controller hw i can call the state here -->
<?php $current_timestamp = strtotime(date("Y-m-d H:i:s") . '- 10 second');
$current_timestamp = date('Y-m-d H:i:s', $current_timestamp);
if($c->last_activity > $current_timestamp)
{
echo "online";
}
else
{
echo "offline";
} ?>
Model:
public function getAllUsers() //from 1 table
{
$this->db->select('m.user_id, m.email , m.type, u.last_activity ,u.id ,u.state');
$this->db->from('tbl_user m');
$this->db->join('tbl_user_activity u ', 'u.user_id = m.user_id' ,'LEFT');
$this->db->select_max('u.last_activity');
// $this->db->where($where);
$this->db->group_by('m.user_id');// add group_by
$query = $this->db->get();
foreach ($query as $c)
{
$current_timestamp = strtotime(date("Y-m-d H:i:s") . '- 10 second');
$current_timestamp = date('Y-m-d H:i:s', $current_timestamp);
if('$c->last_activity' > $current_timestamp) //try
{ // here must to be function to checl the last user activity and get it
// here must to set the u.state to online
}
else if($query < $current_timestamp) //try
{
}
}
return $query->result();

What if you check and set "state" in your MODEL/CONTROLLER page
MODEL PAGE
<?php
//your code,
$last_activity = $c->last_activity; //make sure it won't return NULL
if($last_activity > $current_timestamp) { //return true if online,
$state = "online";
}else{
$state = "offline";
}
//your code,
?>
just read the state in your VIEW page
VIEW PAGE
<?php
//your code,
$new_state = $c->state; //so $new_state = "online" or $new_state = "offline"
//your code,
?>

Try this.
It will create a new collection of data with a new row called 'state';
The return value is an array so you should probably change your view to loop an array instead of an object.
$query = $this->db->get()->result_result_array();
$new_record = array();
foreach($query as $old_record)
{
$current_timestamp = strtotime(date("Y-m-d H:i:s") . '- 10 second');
$current_timestamp = date('Y-m-d H:i:s', $current_timestamp);
if('$c->last_activity' > $current_timestamp) //try
{
$new_record[]['state'] = 'online';
$new_record[] = $old_record;
}
else if($query < $current_timestamp) //try
{
$new_record[]['state'] = 'offline';
$new_record[] = $old_record;
}
}
return $new_record;

Related

ACF Repeater w/ Flexible Content Inside

I'm working with advance custom fields. I've got a ticket in with them directly but its taking a while. I need to figure this out immediately.
Trying to repeat flexible content for a hero slider where user can add video embed or an image. How do I echo each piece in the loop properly? The content imput in Wordpress is not appearing. The containers are echoing, just no content.
<?php
if (have_rows('add_resorts_hero_image_slide', 'option')) {
while (have_rows('add_resorts_hero_image_slide', 'option')) {
the_row();
$herovideo = the_sub_field('add_resorts_hero_slider_video');
$heroimage = the_sub_field('add_resorts_hero_slider_image');
$heroimgsize = 'hero-image';
$heroimg_array = wp_get_attachment_image_src($heroimage, $heroimgsize);
$heroimg_url = $heroimg_array[0];
if (have_rows('choose_resorts_hero_slider_content')) {
while (have_rows('choose_resorts_hero_slider_content')) {
the_row();
echo '<li class="orbit-slide">';
if( get_row_layout() == 'resorts_slider_video' )
echo $herovideo;
elseif( get_row_layout() == 'resorts_slider_video')
echo '<img src="'.$heroimg_url.'" />';
echo '</li>';
}
}
}
}
Just reposting the pertinent part of your code:
if( get_row_layout() == 'resorts_slider_video' ){
//Display iFrame Video (this assumes that your field is a URL field.)
echo '<iframe src="'.get_sub_field('IFRAME URL FIELD NAME GOES HERE').'"></iframe>';
}elseif( get_row_layout() == 'resorts_slider_video'){
//Display Image (this assumes that your field is an image field, being saved as an Image Object, and you want to output a custom image size)
$myImage = get_sub_field('IMAGE FIELD NAME GOES HERE');
echo '<img src="'.$myImage['sizes']['CUSTOM IMAGE SIZE NAME'].'" alt="'.$myImage['alt'].'" />';
}
Finally figured out exactly what I needed. Hoping this answer helps someone else out!
<!--ORBIT SLIDE-->
<?php
if (have_rows('add_resorts_hero_image_slide', 'option')) {
while (have_rows('add_resorts_hero_image_slide', 'option')) {
the_row();
if (have_rows('choose_resorts_hero_slider_content')) {
while (have_rows('choose_resorts_hero_slider_content')) {
the_row();
$herovideo = get_sub_field('add_resorts_hero_slider_video');
$heroimage = get_sub_field('add_resorts_hero_slider_image');
$heroimgsize = 'hero-image';
$heroimg_array = wp_get_attachment_image_src($heroimage, $heroimgsize);
$heroimg_url = $heroimg_array[0];
if( get_row_layout() == 'resorts_slider_video' ) {
echo '<li class="video orbit-slide">';
echo '<img class="background" src="http://localhost.com/vail/tier2-hero-placeholder.jpg" />';
echo '<div class="container">
<div class="watermark"></div>
<iframe id="heroorbitslider-video"
src="'. $herovideo .'"
width="100%"
frameborder="0"
scrolling="no"
allowFullscreen="true"
allowFullScreen="true"
webkitAllowFullScreen="true"
mozAllowFullScreen="true">
</iframe>
</div>';
echo '</li>';
}
elseif( get_row_layout() == 'resorts_slider_image') {
echo '<li class="orbit-slide">';
echo '<img class="background "src="'. $heroimg_url .'" />';
echo '</li>';
}
}
}
}
}
?>
<!--END ORBIT SLIDE-->

Remember selected checkboxes across paginated pages

I am displaying data in a table and doing some paging and sorting. I have a checkbox for everyrow.
When I move from one page to another, I will like to keep the checkboxes checked if they were checked.
I dont want the checked boxes to uncheck as I navigate from page to page. How do i achieve that?
Here is my jquery.
<script type="text/javascript">
$(document).ready(function () {
$(".header").click(function (evt) {
var sortfield = $(evt.target).data("sortfield");
if ($("#SortField").val() == sortfield)
{
if($("#SortDirection").val()=="ascending")
{
$("#SortDirection").val("descending");
}
else
{
$("#SortDirection").val("ascending");
}
}
else
{
$("#SortField").val(sortfield);
$("#SortDirection").val("ascending");
}
evt.preventDefault();
$("form").submit();
});
$(".pager").click(function (evt) {
var pageindex = $(evt.target).data("pageindex");
$("#CurrentPageIndex").val(pageindex);
evt.preventDefault();
$("form").submit();
});
});
</script>
Here is my html page
<body>
<h1>List of Customers</h1>
#{
PageSortOnlineEx.Models.SortingPagingInfo info = ViewBag.SortingPagingInfo;
}
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#Html.Hidden("SortField", info.SortField)
#Html.Hidden("SortDirection", info.SortDirection)
#Html.Hidden("PageCount", info.PageCount)
#Html.Hidden("PageSize", info.PageSize)
#Html.Hidden("CurrentPageIndex", info.CurrentPageIndex)
<table border="1" cellpadding="10">
<tr>
<th>Select</th>
<th>CustomerID</th>
<th>CompanyName</th>
<th>ContactName</th>
<th>Country</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#Html.CheckBox("select", false)</td>
<td>#item.CustomerID</td>
<td>#item.CompanyName</td>
<td>#item.ContactName</td>
<td>#item.Country</td>
</tr>
}
<tr>
<td colspan="4">
#for (var i = 0; i < info.PageCount; i++)
{
if (i == info.CurrentPageIndex)
{
<span>#(i + 1)</span>
}
else
{
#(i + 1)
}
}
</td>
</tr>
</table>
}
</body>
Here is my controller code
public ActionResult Index()
{
using (NorthwindEntities db = new NorthwindEntities())
{
SortingPagingInfo info = new SortingPagingInfo();
info.SortField = "CustomerID";
info.SortDirection = "ascending";
info.PageSize = 10;
info.PageCount = Convert.ToInt32(Math.Ceiling((double)(db.Customers.Count() / info.PageSize)));
info.CurrentPageIndex = 0;
var query = db.Customers.OrderBy(c => c.CustomerID).Take(info.PageSize);
ViewBag.SortingPagingInfo = info;
List<Customer> model = query.ToList();
return View(model);
}
}
[HttpPost]
public ActionResult Index(SortingPagingInfo info)
{
using (NorthwindEntities db = new NorthwindEntities())
{
IQueryable<Customer> query = null;
switch (info.SortField)
{
case "CustomerID":
query = (info.SortDirection == "ascending" ? db.Customers.OrderBy(c => c.CustomerID) : db.Customers.OrderByDescending(c => c.CustomerID));
break;
case "CompanyName":
query = (info.SortDirection == "ascending" ? db.Customers.OrderBy(c => c.CompanyName) : db.Customers.OrderByDescending(c => c.CompanyName));
break;
case "ContactName":
query = (info.SortDirection == "ascending" ? db.Customers.OrderBy(c => c.ContactName) : db.Customers.OrderByDescending(c => c.ContactName));
break;
case "Country":
query = (info.SortDirection == "ascending" ? db.Customers.OrderBy(c => c.Country) : db.Customers.OrderByDescending(c => c.Country));
break;
}
query = query.Skip(info.CurrentPageIndex * info.PageSize).Take(info.PageSize);
ViewBag.SortingPagingInfo = info;
List<Customer> model = query.ToList();
return View(model);
}
}

Array to string conversion PHP is showing error

Hey guys I am trying to update a checkbox feild in my database and have to capture and bind the Values in using SQL PDO.
I am getting an error however about an array to string conversion,
my check boxes look like this -
<div class="checkboxFour">
<p class="admin_label" id="checklabel2">In Seaon</p>
<input type="checkbox" name="inSeason[]" value="1" id="checkboxFourInput" checked="checked"<?php if( isset( $_GET['inSeason'] ) ){ ?> checked="checked" <?php } ?>/>
<label for="checkboxFourInput"></label>
</div>
<div class="checkboxFour">
<p class= "admin_label"id="checklabel2">Out Season</p>
<input type="checkbox" name="inSeason[]" value="0" id="checkboxFour2Input" <?php if( isset( $_GET['inSeason'] ) ){ ?> checked="checked" <?php } ?> />
<label for="checkboxFour2Input"></label>
</div>
In my PHP I have built the following -
if (isset($_POST['updateProductSubmit'])) {
// open the database connection
include 'includes/connection.php';
$inSeasonValue = "0";
if( array_key_exists( 'inSeason', $_GET ) && $_GET['inSeason'] == '0' ){
$saleItemValue = "0";
echo $saleItemValue['inSeason'];
}
$inSeasonValue = "1";
if( array_key_exists( 'inSeason', $_GET ) && $_GET['inSeason'] == '1' ){
$saleItemValue = "1";
echo $saleItemValue['inSeason'];
}
try {
//create our sql update statement
$sql = "UPDATE Products SET productNbr = :productNbr, productName= :productName, inSeason = '$inSeasonValue', description = :description, photo =
:photo WHERE productNbr=:productNbr;";
// prepare the statement
$statement = $pdo->prepare($sql);
// bind the values
$statement->bindValue(':productNbr', $_POST['productNbr']);
$statement->bindValue(':productName', $_POST['productName']);
$statement->bindValue(':inSeason', $_POST['inSeason']);
$statement->bindValue(':description', $_POST['description']);
$statement->bindValue(':photo', $_POST['photo']);
// execute the statement
$success = $statement->execute();
} // end try
catch (PDOException $e) {
echo 'Error updating item: ' . $e->getMessage();
exit();
} // end catch
// test the result and display appropriate message
if ($success) {
echo '<script type="text/javascript"> alert("Successfully updated Item.")</script>';
}
else {
echo '<script type="text/javascript">alert("Unable to execute the Item update.");</script>';
}
//free connection to the server
$statement->closeCursor();
} // end if statement
?>
The error is pointing out that the bind value $statement->bindValue(':inSeason', $_POST['inSeason']);
I hope you guys can help!!
Thanks so Much in advance!!
:-)
You have named your inSeason checkox with an array construct here
<input type="checkbox" name="inSeason[]" value="0" id="checkboxFour2Input" <?php if( isset( $_GET['inSeason'] ) ){ ?> checked="checked" <?php } ?> />
This will appear as an array when PHP decodes th $_GET data, but here
if( array_key_exists( 'inSeason', $_GET ) && $_GET['inSeason'] == '0' ){
You're testing against a string, hence the array-to-sring error message.
Simply rename your checkBox in your HTML like this:
<input type="checkbox" name="inSeason" value="0" id="checkboxFour2Input" <?php if( isset( $_GET['inSeason'] ) ){ ?> checked="checked" <?php } ?> />
^^^ remove square brackets here.

Likegate issue with js fb api, dialog box getting popup blocked

I use the following code for a likegate but the popup login dialog box is getting blocked. a friend of mine said I can do with fb subscribe event. has anyone done it with that? Unless there is a way to trick the box to open as display:page instead of popup.
Any help appreciated.
FB.getLoginStatus(function(response) {
var page_id = "XXX";
if (response && response.authResponse) {
var user_id = response.authResponse.userID;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
FB.Data.query(fql_query).wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
console.log("LIKE");
$('#container_like').show();
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
});
} else {
FB.login(function(response) {
if (response && response.authResponse) {
var user_id = response.authResponse.userID;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
FB.Data.query(fql_query).wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
console.log("LIKE");
$('#container_like').show();
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
});
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
}, {scope: 'user_likes'});
}
});
};
I figured the PHP way, which is much better and easier... here is the code for all people out there trying :)
$facebook = new Facebook(array(
'appId' => 'XXXXXX',
'secret' => 'XXX',
'cookie' => true
));
$sr = $facebook->getSignedRequest();
?>
<?php if ($sr['page']['liked']): ?>
<-- STUFF IF A FAN -->
<?php else: ?>
<-- STUFF IF NOT A FAN -->
<?php endif; ?>

MODx querying custom db table

See the code below. I'm trying to get some data from a database is modx. The data is there, meaning, when i query the database in phpmyadmin, i get results. I can't figure out why it doesnt work in modx.
$sql = 'SELECT * FROM orders ORDER BY created DESC LIMIT 1';
$stmt = $modx->prepare($sql);
$stmt->execute();
// Put data in array
$order_data = $stmt->fetch(PDO::FETCH_ASSOC);
if ($order_data == '') {
return 'Resultset empty for user '. $user_id.'.<br />'.$sql;
} else {
return 'Data found!';
}
Perhaps try using xPDO:
$sql = 'SELECT * FROM orders ORDER BY created DESC LIMIT 1';
$c = new xPDOCriteria($modx,$sql);
if ($c->stmt && $c->stmt->execute()) {
$order_data = $c->stmt->fetch(PDO::FETCH_ASSOC);
var_dump($order_data);
}
You need to loop through your output, the result will be an array of arrays.
The below example will return the data and present it according to a chunk format
<?php
$sql = "SELECT * FROM `table_name`";
$query = $modx->query($sql);
$rows = array();
if ($query) {
// loop through the result set and inspect one row at a time
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
array_push($rows, $row);
$output .= $modx->getChunk($tpl,$row);
}
}
$output = "<table border=\"1\" cellpadding=\"5\" >
<th>ID</th><th>row1_Head</th><th>row2_Head</th><th>row3_Head</th><th>row4_Head</th><th>row5_Head</th>
$output</table>";
return $output;
This is an example of the chunk:
<tr>
<td>[[+id]]</td> <td>[[+row1]]</td> <td>[[+row2]]</td> <td>[[+row3]]</td> <td>[[+row4]]</td> <td>[[+row5]]</td>
</tr>
Now in a resource call your snippet like
[[!Snippet_name? &tpl=`chunk_name`]]
$sql = 'SELECT * FROM orders ORDER BY created DESC LIMIT 1';
Assume your schema is like
<?xml version="1.0" encoding="UTF-8"?>
<model package="your_package_name" baseClass="xPDOObject" platform="mysql" defaultEngine="MyISAM" version="1.1">
<object class="Orders" table="orders" extends="xPDOSimpleObject">
<field key="order_no" dbtype="varchar" precision="255" phptype="string" null="false" />
<!-- and everything else below -->
</object>
<!-- and everything else below -->
</model>
What you need to do is as simple as this:
$modx->addPackage('your_package_name'); // Add your table schema to MODX object
$orders = $modx->getCollection('Orders'); // class's name, not table's name
$output = '';
if ($orders){
$outputArray = array();
foreach ($orders as $order) {
$orderArray = $order->toArray();
$outputArray[] = $modx->getChunk('your_row_chunk_name', $orderArray);
}
$wrapper = array(
'orders' => #implode("\n", $outputArray);
);
$output = $modx->getChunk('your_wrapper_chunk_name', $wrapper);
}
return $output;