i'm working on a project where there is posts .. which you can comment to. the comments are in an iframe which is embeded to the post. the iframe has the comment form and the queries to get and insert comments. my problem is that i want to refresh the iframe page whenever the comments table changes. for example i have a conversation with another user trought the comments i don't need to refresh the page to see new comments .. but rather the new comments show up in my comments section. any suggestion or bit of code will be good. thanks.
mercredi 1 juillet 2015
How to insert multiple rows and files into mysql using php array?
How to insert multiple rows and upload files into mysql database using php array?
I want to add a 'Add More' Option in this form by which the same fields got duplicates down to it, and can easily insert multiple rows as well as file uploads to mysql database.
Here is the code :
<?php
// @author - Chetanaya Aggarwal
?>
<?php include('header_dashboard.php'); ?>
<?php include('session.php'); ?>
<?php $get_id = $_GET['id']; ?>
<body id="home">
<?php include('navbar_client.php'); ?>
<div class="container-fluid">
<div class="row-fluid">
<?php include('Device_sidebar.php'); ?>
<div class="span9" id="content">
<div class="row-fluid">
<!-- block -->
<div class="block">
<div class="navbar navbar-inner block-header">
<div class="muted pull-left">Upload Documents</div>
<div class="muted pull-right"><a id="return" data-placement="left" title="Click to Return" href="clients_list.php"><i class="icon-arrow-left icon-large"></i> Back</a></div>
<script type="text/javascript">
$(document).ready(function(){
$('#return').tooltip('show');
$('#return').tooltip('hide');
});
</script>
</div>
<div class="block-content collapse in">
<div class="alert alert-success"><i class="icon-info-sign"></i> Please Fill in required details</div>
<form class="form-horizontal" method="post" enctype="multipart/form-data">
<table style width="100%">
<tr>
<tr>
<td>
<div class="control-group">
<label class="control-label" style="font-size: 16px;" for="inputPassword"><b>Document Type</b></label>
<div class="controls">
<select name="docstype_id" class="chzn-select" required/>
<option></option>
<?php $docs_type=mysql_query("select * from docs_type")or die(mysql_error());
while ($row=mysql_fetch_array($docs_type)){
?>
<option value="<?php echo $row['docstype_id']; ?> Name <?php echo $row['docsname']; ?>"><?php echo $row['docsname']; ?></option>
<?php } ?>
</select>
</div>
</div>
</td>
<td>
<div class="control-group">
<label class="control-label" style="font-size: 16px;" for="inputPassword"><b>Document Copy</b></label>
<div class="controls">
<input name="Photo" class="input-file uniform_on" id="fileInput" type="file" required>
</div>
</div>
</td>
</tr>
<tr>
<td>
<div class="control-group">
<label class="control-label" style="font-size: 16px;" id="la-add-mob" for="inputPassword"><b>Document No.</b></label>
<div class="controls">
<input type="text" class="span8" name="file_no" id="file_no" placeholder="Document No.">
</div>
</div>
</td>
<td>
</td>
</tr>
<tr>
<td>
<div class="control-group">
<div class="controls">
<button name="save" id="save" data-placement="right" title="Click here to Save your new data." class="btn btn-primary"><i class="icon-save"></i> Save</button>
</div>
</div>
</td>
</tr>
<script type="text/javascript">
$(document).ready(function(){
$('#save').tooltip('show');
$('#save').tooltip('hide');
});
</script>
</tr>
</table>
</form>
</div>
</div>
<?php
$uploadDir1 = 'uploads/'; //Image Upload Folder
if (isset($_POST['save'])){
$docstype_id = $_POST['docstype_id'];
$fileno = $_POST['file_no'];
function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; }
$fileName1 = $_FILES['Photo']['name'];
$extension = getExtension($fileName1);
$extension = strtolower($extension);
$tmpName1 = $_FILES['Photo']['tmp_name'];
$fileSize1 = $_FILES['Photo']['size'];
$fileType1 = $_FILES['Photo']['type'];
$image_name= $fileno.'.'.$extension;
$filePath1 = $uploadDir1 . $image_name;
$result1 = move_uploaded_file($tmpName1, $filePath1);
if (!$result1) {
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc())
{
$fileName1 = addslashes($fileName1);
$filePath1 = addslashes($filePath1);
}
mysql_query("insert into upload (clients_id,docstype_id,file_no,file_path) values('$get_id','$docstype_id','$fileno','$filePath1')")or die(mysql_error());
?>
<script>
window.location = "clients_list.php";
$.jGrowl("Documents Uploaded Successfully added", { header: 'Device add' });
</script>
<?php
}
?>
</div>
</div>
<!-- /block -->
</div>
</div>
</div>
<?php include('footer.php'); ?>
</div>
<?php include('script.php'); ?>
</body>
unABLE TO INSERT FORM DATA INTO DATABASE TABLE
Please i have been trying to insert form data into my database with this code
$servername = "localhost";
$user = "Ahmed";
$password = "hammed";
$dbname = "registration";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $user, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// check user_error
$checkuserstmt = $conn->prepare("SELECT * FROM user_registration WHERE username= ? && email= ?");
$checkuserstmt->bindParam(1, $username);
$checkuserstmt->bindParam(2, $email);
$checkuserstmt->execute();
if($checkuserstmt->rowcount()==0){
$stmt = $conn->prepare("INSERT INTO user_registration(fname, lname, username, email, pass, gender)
VALUE (?, ?, ?, ?, ?, ?)");
//bind parameter
$stmt->bindparam(1, $fname);
$stmt->bindparam(2, $lname);
$stmt->bindparam(3, $username);
$stmt->bindparam(4, $email);
$stmt->bindparam(5, $pass);
$stmt->bindparam(6, $gender);
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$username = $_POST['username'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$gender =$_POST['gender'];
// use exec() because no results are returned
$stmt->execute();
if($stmt==false){
echo "<p>There is already a user with that name: </p>";
}
else{
echo "New record created successfully. Last inserted ID is: " ;
$users = $conn->query("SELECT * FROM user_registration");
$row = $users->fetch();
echo $row["username"] . " -- " . $row["email"] . "<br />";
}
}
}
catch(PDOException $e)
{
echo "Unable to create your account: " . $e->getMessage();
}
$conn = null;
// but instead i get error message first type will be undefined index and the exception error is SQLSTATE[23000]: Integrity constraint violation: 1048 Le champ 'fname' ne peut �tre vide (null)
How to get a portion of a string with a regular expression
I have this situation where I can have strings like this:
"Project\\V1\\Rest\\Car\\Controller"
"Project\\V1\\Rest\\Boat\\Controller"
"Project\\Action\\Truck"
"Project\\V1\\Rest\\Helicopter\\Controller"
"Parental\\Boat\\Action"
Just in case the string follow the pattern:
"Project\\V1\\Rest\\THE_DESIRED_WORD\\Controller"
I want to get THE_DESIRED_WORD.
That's why I'm thinking in a regular expression.
Included File Gets Me Undefined Variables
Couldnt find an answer that solves my codes issue.
file.php:
if(isset($_GET['season1'])) {
$season1 = $_GET['season1'];
$url = 'http://ift.tt/ywvpFl'.$season1.'/episodes?season=1';
$imdb_content = file_get_contents($url);
$html = str_get_html($imdb_content);
//Grabbed Content
$resultarray = array();
foreach($html->find('strong a[itemprop="name"]') as $results) {
$resultarray[] = $results;
}
echo $resultarray[0];
echo $resultarray[1];
} else {
header("Location: ../");
}
index.php:
include("http://ift.tt/1IPwyQs".urlencode($imdbid));
(...)
<div class="row">
<div class="tech-spec-element col-xs-20 col-sm-10 col-md-5"> <span title="Episode 1"></span>1 - <?= $resultarray[0]; ?>
<div></div>
</div>
<div class="tech-spec-element col-xs-20 col-sm-10 col-md-5"> <span title="Episode 2"></span>2 - <?= $resultarray[1]; ?>
<div></div>
</div>
<div class="tech-spec-element col-xs-20 col-sm-10 col-md-5"> <span title="Episode 3"></span>3 - <?= $resultarray[2]; ?>
<div></div>
</div>
<div class="tech-spec-element col-xs-20 col-sm-10 col-md-5"> <span title="Episode 4"></span>4 - <?= $resultarray[3]; ?>
<div></div>
</div>
</div>
I know the file.php is being loaded fine as it gives me its output but when I try and use $resultarray[0]; it just doesnt work and say its undefined.
Any ideas on how I would resolve this pleasE?
Downgrade class php 5.6 to 5.5
I founded a class to stack object layers and closures but my server isnt running on php 5.6 yet. And i was wondering how can i convert the ...$parameters because i cant fix it by replacing everything with call_user_func_array() then the buildCoreClosure() method will throw errors for example because a closure isnt an array...
class Stack
{
/**
* Method to call on the decoracted class.
*
* @var string
*/
protected $method;
/**
* Container.
*/
protected $container;
/**
* Middleware layers.
*
* @var array
*/
protected $layers = [];
public function __construct(Container $container = null, $method = null)
{
$this->container = $container ?: new Container;
$this->method = $method ?: 'handle';
}
public function addLayer($class, $inner = true)
{
return $inner ? array_unshift($this->layers, $class) : array_push($this->layers, $class);
}
public function addInnerLayer($class)
{
return $this->addLayer($class);
}
public function addOuterLayer($class)
{
return $this->addLayer($class, false);
}
protected function buildCoreClosure($object)
{
return function(...$arguments) use ($object)
{
$callable = $object instanceof Closure ? $object : [$object, $this->method];
return $callable(...$arguments);
};
}
protected function buildLayerClosure($layer, Closure $next)
{
return function(...$arguments) use ($layer, $next)
{
return $layer->execute(...array_merge($arguments, [$next]));
};
}
public function peel($object, array $parameters = [])
{
$next = $this->buildCoreClosure($object);
foreach($this->layers as $layer)
{
$layer = $this->container->get($layer);
$next = $this->buildLayerClosure($layer, $next);
}
return $next(...$parameters);
}
}
JQuery UI Sortable: Save keys with sort order
I am using this code to save my JQuery UI sort order:
$(function() {
$('#sortable').sortable({
update: function (event, ui) {
var data = $(this).sortable('serialize');
$.ajax({
data: data,
type: 'POST',
url: '/sort.php'
});
}
});
$( "#sortable" ).disableSelection();
});
This produces an array of numbers. Let's say I also want to save keys with the numbers, based on tags in my list items.
So for example a sorted list such as:
<ul id='sortable'>
<li id='item-3' name='special'><image src='special.jpg'></li>
<li id='item-1' name='normal'><image src='normal.jpg'></li>
<li id='item-2' name='extraordinary'><image src='extraordinary.jpg'></li>
</ul>
Would produce this array in PHP:
$item['special'] = 3;
$item['normal'] = 1;
$item['extraordinary'] = 2;
I know how to access the tags with JQuery but not how to serialize these into an array to pass to my PHP script along with the sorted numbers. Help!
Not able to save selected option from selected list to db with Angular and PHP
I have this form in a pop box (Angular Material) and in this form i have 5 input fields and 2 select list. i am able to populate the select list with data from the db and i am also able to save the data but only from the input fields so not from the select box. So i would like to know how to save the selected option from a select list to my db.
I am working with Angular and PHP for the back-end The db situation is the following: 3 tables
- tblTask
- tblLocation
- tblProjectType
Both id from tblLocation and tblProjectType reference back to tblTask (Foreign Key)
HTML code:
<md-dialog aria-label="">
<form ng-controller="AppCtrl">
<md-toolbar>
<div class="md-toolbar-tools">
<md-input-container md-no-float="">
<input class="customInput" placeholder="Name this task..." name="task_name" ng-model="task_name">
</md-input-container>
<span flex></span>
<md-button class="md-icon-button" ng-click="closeDialog()">
<md-icon md-svg-src="images/ic_close_24px.svg" aria-label="Close dialog"></md-icon>
</md-button>
</div>
</md-toolbar>
<md-dialog-content>
<div>
<div layout="row">
<div class="labelPosition">
<md-select-label>Project type</md-select-label>
</div>
<div id="containerSelectListProjectType">
<md-select ng-model="task_project_type" name="project_type" placeholder="Choose a project type" id="containerProjectType">
<md-option ng-model="selected_task_project_type" ng-repeat="projecttype in projectTypeInfo" ng-value="{{projecttype.id_ProjectType}}">{{projecttype.project_type}}</md-option>
</md-select>
</div>
</div>
<br/>
<div layout="row">
<div class="labelPosition">
<md-select-label>Location</md-select-label>
</div>
<div id="containerSelectListLocation">
<md-select ng-model="task_location" name="location" placeholder="Choose your location">
<md-option ng-repeat="location in locationInfo" ng-value="{{location.id_Location}}">{{location.location}}</md-option>
</md-select>
</div>
</div>
<br/>
<div layout="row">
<div class="labelPosition">
<md-select-label>Estimate time</md-select-label>
</div>
<div id="containerEstimateTime">
<md-chips ng-model="ctrl.numberChips2">
<input type="number" ng-model="task_estimate_time" ng-model="ctrl.numberBuffer" placeholder="Enter a number" name="task_estimate_time">
</md-chips>
</div>
</div>
<br/>
<div layout="row">
<div class="labelPositionCP">
<md-select-label>Client/Project</md-select-label>
</div>
<div id="containerClientProject">
<md-input-container md-no-float="">
<input name="project_client_name" placeholder="Project/Client name" ng-model="task_project_client_name">
</md-input-container>
</div>
</div>
<br />
<div layout="row">
<div class="labelPosition">
<md-select-label>Url</md-select-label>
</div>
<div id="containerUrl">
<md-input-container md-no-float="">
<input name="url" placeholder="Url" ng-model="task_url">
</md-input-container>
</div>
</div>
<br />
<div layout="row">
<div class="labelPosition">
<md-select-label>Resource link</md-select-label>
</div>
<div id="containerResourceLink">
<md-input-container md-no-float="">
<input name="resource_link" placeholder="Resource link" ng-model="task_resource_link">
</md-input-container>
</div>
</div>
<br />
<div layout="row">
<div class="labelPosition">
<md-select-label>Note's</md-select-label>
</div>
<div id="containerNotes">
<md-input-container md-no-float="">
<textarea ng-model="task_notes" ng-model="task_notes" placeholder="Note's" columns="1" md-maxlength="150"></textarea>
</md-input-container>
</div>
</div>`enter code here`
</div>
</md-dialog-content>
<div class="md-actions" layout="row">
<md-button class="md-primary">Delete</md-button>
<md-button class="md-primary">Url</md-button>
<md-button class="md-primary">Resource link</md-button>
<md-button class="md-primary">Note's</md-button>
<md-button class="md-primary">Cancel</md-button>
<md-button ng-click="save_task()" class="md-primary">Save</md-button>
</div>
</form>
</md-dialog>
Code of app.js:
app.controller('AppCtrl', function($scope, $mdDialog, $http) {
$scope.taskInfo = [];
$scope.save_task = function(){
$http.post('db.php?action=add_task',
{
'task_name' : $scope.task_name,
'id_ProjectType' : $scope.selected_task_project_type,
'task_project_client_name' : $scope.task_project_client_name,
'task_url' : $scope.task_url,
'task_resource_link' : $scope.task_resource_link,
'task_notes' : $scope.task_notes
}
)
.success(function (data, status, headers, config) {
//$scope.userInfo.push(data);
//$scope.get_task(); //this will fetch latest record from DB
console.log("The task has been added successfully to the DB");
console.log(data);
})
.error(function(data, status, headers, config) {
console.log("Failed to add the task to DB");
});
}
//Populating select list with data from DB for project type
$scope.getProjectTypeFunction = function() {
$http.get('db.php?action=get_ProjectType_Info').success(function(data)
{
$scope.projectTypeInfo = data;
console.log("Retrieved data from server");
//console.log(data);
})
.error(function(data, status, headers, config)
{
console.log("Error in retrieving data from server");
});
}
$scope.getProjectTypeFunction(); //-- call the function that calls $http
//Populating select list with data from DB for location
$scope.getLocationFunction = function() {
$http.get('db.php?action=get_Location_Info').success(function(data)
{
$scope.locationInfo = data;
console.log("Retrieved data from server");
//console.log(data);
})
.error(function(data, status, headers, config)
{
console.log("Error in retrieving data from server");
});
}
$scope.getLocationFunction(); //-- call the function that calls $http
});
My PHP code:
<?php
include('config.php');
switch($_GET['action']) {
case 'get_ProjectType_Info' :
get_ProjectType_Info();
break;
case 'add_task' :
add_task();
break;
case 'get_Location_Info' :
get_Location_Info();
break;
}
/** Function to data from tblProjectType **/
function get_ProjectType_Info(){
$qry = mysql_query('SELECT * from tblProjectType');
$data = array();
while($rows = mysql_fetch_array($qry))
{
$data[] = array(
"id_ProjectType" => $rows['id_ProjectType'],
"project_type" => $rows['project_type']
);
}
print_r(json_encode($data));
//return json_encode($data);
}
/** Function to data from tblLocation **/
function get_Location_Info(){
$qry = mysql_query('SELECT * from tblLocation');
$data = array();
while($rows = mysql_fetch_array($qry))
{
$data[] = array(
"id_Location" => $rows['id_Location'],
"location" => $rows['location']
);
}
print_r(json_encode($data));
//return json_encode($data);
}
/** Function to add a task to db **/
function add_task() {
$data = json_decode(file_get_contents("php://input"));
$task_name = $data->task_name;
$task_project_type = $data->id_ProjectType;
$task_location = $data->id_Location;
$task_estimate_time = $data->task_estimate_time;
$task_project_client_name = $data->task_project_client_name;
$task_url = $data->task_url;
$task_resource_link = $data->task_resource_link;
$task_notes = $data->task_notes;
print_r($data);
$qry = 'INSERT INTO tblTask(task_name, id_ProjectType, task_project_client_name, task_url, task_resource_link, task_notes)
VALUES ("' . $task_name . '","' . $task_project_type . '","' . $task_project_client_name . '","' . $task_url . '","' . $task_resource_link . '","' . $task_notes .'")';
echo ($qry);
$qry_res = mysql_query($qry);
if ($qry_res) {
$arr = array('msg' => "Task added successfully!!!", 'error' => '');
$jsn = json_encode($arr);
// print_r($jsn);
}
else {
$arr = array('msg' => "", 'error' => 'Error in inserting record');
$jsn = json_encode($arr);
// print_r($jsn);
}
}
?>
The minute i add the reference of the project type in my php and app.js file then i won't save any more to the db. But when i leave it out i am able to save all data from the 5 input fields.
Class 'App\Libs\Emotes' not found (Laravel & Blade)
I'm currently having an Issue with Laravel (5), Its been a long time since I haven't touched laravel since the early versions of 4, and as soon as Laravel 5 was released I boarded the train and thought I would have a go with it, specifically with a Emote phraser.
Basically the over-all issue I'm having is Class "App\Libs\Emote is not found" although I think I've registered the alias correctly for us, but someone could prove me wrong.
<!DOCTYPE html>
<html>
<head>
<title>Laravel</title>
<link href="//fonts.googleapis.com/css?family=Lato:100" rel="stylesheet" type="text/css">
<style>
html, body {
height: 100%;
}
body {
margin: 0;
padding: 0;
width: 100%;
display: table;
font-weight: 100;
font-family: 'Lato';
}
.container {
text-align: center;
display: table-cell;
vertical-align: middle;
}
.content {
text-align: center;
display: inline-block;
}
.title {
font-size: 96px;
}
</style>
</head>
<body>
<div class="container">
{{
Emote::PhraseEmote()
}}
<div class="content">
<div class="title">(flag:gb) (flag:us)</div>
</div>
</div>
</body>
</html>
Class;
<?php
namespace Libs\Emotes;
class Emotes {
public static function PhraseEmote($value) {
$config = Config::get('emotes');
$smileys = $config['render_phrase'];
foreach($emotes as $key => $val) {
//$value = str_replace($key, '<img src="' . $config['path'] . $smileys[$key][0] . '" width="' . $smileys[$key][1] . '" height="' . $smileys[$key][2] . '" alt="' . $smileys[$key][3] . '" style="border:0;" />', $value);
$value = str_replace($key, $emotes[$key][0], $value);
}
return $value;
}
}
?>
Config;
<?php
return array(
'render_phrase' => array(
'(flag:gb)' => array('<i class="gb flag" data-content="United Kingdom" data-variation="tiny"></i>'),
'(flag:us)' => array('<i class="us flag" data-content="United States" data-variation="tiny"></i>'),
//'(flag:CN_Code)' => array('<i class="CN_CODE flag" data-content="United States" data-variation="tiny"></i>'),
)
);
PHP Compare date to current date does not work
This is a wordpress site but the dates are custom and they are not post dates. I'm trying to compare an expire date to current date. It works on some dates but when expire date is on 01/01/2017 or 01/01/2016 it returns an Invalid status. Even when date is on the year 2017 it still returns invalid status. Somehow it is not consistent and I am not sure where to check and what statement might be missing. This is the sample code. Expired date is already stored in $dates[1] and the value has a format of MM/DD/YY. I used the wordpress current_time code to call the current date. Please help. Thanks!
<?php
$current_datetime = current_time( 'mysql' );
if ($dates[1] < date('m/d/Y', strtotime($current_datetime)) ){
echo '<td class="-status"><span>Invalid</span></td>'."\n";
}
else
if ($dates[1] >= date('m/d/Y', strtotime($current_datetime)) ){
echo '<td class="-status"><span>Valid</span></td>'."\n";
}
?>
Angularjs Form input text is always undefined
Here is my form
<form>
<input class="text_box1" type="text" name="email" ng-model="forget.email" >
<button style="width:auto" class="sign_up" ng-click="doForget(forget)">Get a Password</button>
</form>
Inside my app.js I have
.when('/forget', {
title: 'forget',
templateUrl: 'resources/views/forget.php',
controller: 'authCtrl'
})
And inside the authCtrl controller i tried to do the console of the input value.
$scope.doForget = function (customer) {
console.log($scope.email);
};
But i am getting the console as undefined always.
How can i get this value ?
Browser back button is not working in IE
Hello, I have generated follow button script from below website.But it is showing issue in IE on clicking back buton of browser.Same IE issue exist in below url.Any helps
Replace letters on the whole page, but not within the tags
I've been searching for this for days.. but no result.
I want to replace latin letters with cyrillic ones using php. But I want to exclude some words and letters within the specific tag <notranslate>
So if I have:
<p><b>Ovo je neki tekst</b> i ovo sigurno <notranslate>nece preci u cirilicu</translate>, hvala !</p>
I want it to become:
<p><b>Ово је неки текст</b> и ово сигурно <notranslate>nece preci u cirilicu</translate>, хвала !</p>
How to do this, using regex ?
Php code compatibility version 5.2 to 5.4
I'm currently using a PHP Version 5.2.5. I want to upgrade my php to PHP version 5.4.35 and my apache 2.0.5(no ssl) to apache 2.2.25 (open ssl). Does my code compatible with the current and the latest version or should i rewrite my code to be compatible? Help.. pls Thank you..
CKEditor bullets and numbers formatting
I have CKEditor in mode inline, and one of the problems I'm having is not getting the bullets and numbers (lists) not attached to color and/or font size.
- Is there a way to get around this ?
Predefined editable areas CMS
I'm trying to develop a backend type cms where the user logged in to the admin area is able to edit simple things within their website. For example, allow the user to change the hours the store is open without having to go through the html code. My thoughts were php, mysql? But i am unsure how i would tagged certain areas only to be editable; I don't want the entire page to be edible, just set defined areas.
Any help/advice would be appreciated!
SilverStripe: How do I make HTTP Request to another website?
I am trying to make a HTTP request to another website inside a controller method. I searched for solutions but I can't find any working examples.
Here is my code:
$r = new HttpRequest('http://ift.tt/1Kts5XU', HttpRequest::METH_GET);
$r->addQueryData(array('SessionID' => $arrGetParams['SessionID']));
try {
$r->send();
} catch (HttpException $ex) {}
I get the following error:
Fatal error: Class 'HttpRequest' not found in C:\wamp\www\abb\mysite\code\form\ALoginForm.php on line 215
How can I get this HTTP request working?
I am using SilverStripe on WAMP on a Windows 7 machine.
Symfony2 - Highcharts rendering a blank div
I have just installed the Highcharts Bundle on Symfony 2.7, but I am already facing an issue while trying to reproduce the "Usage Example" from the documentation (cf http://ift.tt/1IPuHeC)
Here is my code :
Controller
public function homepageAction()
{
$user = $this->getUser();
$securityContext = $this->get('security.context');
$authorization = $securityContext->isGranted('ROLE_REGISTERED_USER');
if ($authorization) {
// Charts Test
$ob = new Highchart();
$ob->chart->renderTo('piechart');
$ob->title->text('Browser market shares at a specific website in 2010');
$ob->plotOptions->pie(array(
'allowPointSelect' => true,
'cursor' => 'pointer',
'dataLabels' => array('enabled' => false),
'showInLegend' => true
));
$data = array(
array('Firefox', 45.0),
array('IE', 26.8),
array('Chrome', 12.8),
array('Safari', 8.5),
array('Opera', 6.2),
array('Others', 0.7),
);
$ob->series(array(array('type' => 'pie', 'name' => 'Browser share', 'data' => $data)));
return $this->render('MVPBundle:User:homepage.html.twig', array(
'user' => $user,
'chart' => $ob,
));
} else {
$url = $this->generateUrl('user_displayCompanyCreationForm');
return $this->redirect($url);
}
}
View
<script src='{{ asset('bundles/mvp/js/jquery-2.1.4.js') }}' type="text/javascript"></script>
<script src='{{ asset('bundles/mvp/js/highcharts.js') }}' type="text/javascript"></script>
<script src='{{ asset('bundles/mvp/js/exporting.js') }}' type="text/javascript"></script>
<script type="text/javascript">
{{ chart(chart) }}
</script>
<div id="linechart" style="min-width: 400px; height: 400px; margin: 0 auto"> </div>
After some research, I understood that it could be linked with the import of the JS files, so I made sure the paths to the files were okay, and that Jquery was imported before Highcharts JS files, so I really don't see where the problem comes from... :(
I would appreciate any help ! :)
Cheers,
How to disable cache in open cart CMS
I used to set $expire = 0; in all cache.php files. Delete all from cache folder. Put $this->cache->delete(); in some random files. Use Ctrl+F5 in my brouser. But cache still alive.
The php json_encode($object) output object namespace
I try to use json_encode() an object but the result has namespace prefix before every direct member variable. The class like this:
namespace common\model;
class MyObj {
private $f1 = 0;
private $f2 = 2;
.....
}
The output like this:
{"\u0000common\\model\\MyObj\u0000f1":0,"\u0000common\\model\\MyObj\u0000f2":2,
how to make the json output without the namespace prefix? my PHP version is 5.6.10.
Using wordpress functions to add featured image to block
Hi I'm a bit new with adding custom functions in my code but I'm building a blog and in the every post page has a button where it says previous or next article. I wanted to use that pre existing function but display a block with the featured image for the each previous/next post.
I'm using Radcliffe theme and the arrows are in the bottom of the page:
This is the part of the code I wanna add the "block"
Thank you
<div class="post-nav">
<?php
$next_post = get_next_post();
if (!empty( $next_post )): ?>
<p class="post-nav-next">
<a title="<?php _e('Next post:', 'radcliffe'); echo ' ' . get_the_title($next_post); ?>" href="<?php echo get_permalink( $next_post->ID ); ?>"><?php echo get_the_title($next_post); ?> </a>
</p>
<?php endif; ?>
<?php
$prev_post = get_previous_post();
if (!empty( $prev_post )): ?>
<p class="post-nav-prev">
<a title="<?php _e('Previous post:', 'radcliffe'); echo ' ' . get_the_title($prev_post); ?>" href="<?php echo get_permalink( $prev_post->ID ); ?>"><?php echo get_the_title($prev_post); ?> </a>
</p>
<?php endif; ?>
PHP: Parse CSS file, find quoted font-family value, copy rules/selectors without that quoted font, add class to all selectors with that font name
Here's a simple example showing what I would like to do with CSS.
Example Input:
html {
font-family: "PT Sans", Helvetica, Arial, sans-serif;
color: #222222;
}
Desired Output:
html {
font-family: Helvetica, Arial, sans-serif;
color: #222222;
}
.pt-sans html {
font-family: "PT Sans", Helvetica, Arial, sans-serif;
color: #222222;
}
I've been using http://ift.tt/1mGBIIC but the examples are not detailed enough for me to figure this out.
This is what I have so far:
<?php
$css_string = '
html {
font-family: "PT Sans", Helvetica, Arial, sans-serif;
color: #222222;
}';
// Create parser.
$oSettings = Sabberworm\CSS\Settings::create()->withMultibyteSupport(false);
$oCssParser = new Sabberworm\CSS\Parser($subject, $oSettings);
$oCssDocument = $oCssParser->parse();
// Get font-family rules.
foreach($oCssDocument->getAllRuleSets() as $key0 => $oRuleSet) {
$rules = $oRuleSet->getRules('font-family');
if (!empty($rules)) {
foreach ($rules as $key1 => $values) {
var_dump(array($key0, $key1));
var_dump($values->getValue());
}
}
}
Which outputs this
array (size=2)
0 => int 0
1 => int 0
object(Sabberworm\CSS\Value\RuleValueList)[91]
protected 'aComponents' =>
array (size=4)
0 =>
object(Sabberworm\CSS\Value\String)[85]
private 'sString' => string 'PT Sans' (length=7)
1 => string 'Helvetica' (length=9)
2 => string 'Arial' (length=5)
3 => string 'sans-serif' (length=10)
protected 'sSeparator' => string ',' (length=1)
The reason why I want to do this is for async font loading http://ift.tt/1LVYHbC Where I would run some js code like this.
<script src="//cdn.rawgit.com/bramstein/fontfaceobserver/master/fontfaceobserver.js"></script>
<script>
var observer = new FontFaceObserver("PT Sans", {});
observer.check(null, 5000).then(function () {
w.document.documentElement.className += " pt-sans";
});
</script>
Laravel get rows with specific day and month
I have the following query in laravel:
$eventos = EventsData::join('tbl_users', 'tbl_users.id_user', '=', 'tbl_events.id_user')
->where('tbl_users.birth_date', '>=', date("m-d")) //my error
->where('tbl_events.year', '>=', date("Y"))
->get();
I have a users table (tbl_users), with the date of the birthdays of each user. And an events table (tbl_events), which records the anniversary of each user. Thus creating a table that will get the next birthdays.
My birth_date is type "yyyy-mm-dd". The table events is the year. I want to get the next event on the current day and year.
ie I think the anniversary date must be greater than the current month and day, and the event with the top year to the current year
Perform a Stripe transaction without JS to retrieve token
I am trying to perform a stripe transaction without the use of Javascript. Possibly cURL but I cannot figure out the header using the v2 api.
<form action="" method="POST" id="payment-form">
<span class="payment-errors"></span>
<div class="form-row">
<label>
<span>Card Number</span>
<input type="text" size="20" data-stripe="number"/>
</label>
</div>
<div class="form-row">
<label>
<span>CVC</span>
<input type="text" size="4" data-stripe="cvc"/>
</label>
</div>
<div class="form-row">
<label>
<span>Expiration (MM/YYYY)</span>
<input type="text" size="2" data-stripe="exp-month"/>
</label>
<span> / </span>
<input type="text" size="4" data-stripe="exp-year"/>
</div>
<button type="submit">Submit Payment</button>
</form>
<?php
require '../stripe-php/init.php';
//this next line is very wrong
$post = 'client_secret=['sk_07C5ukIdqx'].'&grant_type=authorization_code&code='.$_GET['code'];
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $system['stipe']['token_url']);
curl_setopt($ch,CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
$decode = json_decode($result);
\Stripe\Stripe::setApiKey("my_secret");
\Stripe\Charge::create(array(
"amount" => 500,
"currency" => "usd",
"source" => $decode[2], // I am totally guessing the value will be in element #2
"description" => "Charge for test@example.com"
));
?>
most of my issue is getting the token. All of the stripe docs are only using stripe.js and I am not using javascript.
How do I get the stripe token into a PHP variable without the use of Javascript so I can use it for a basic transaction?
My pagination isn't displaying with my code
Why my pagination doesnt show when the condition match with my function func_testSearchByName.php but when the condition match with my function func_testPopulateLeads.php, the pagination shows...
can somebody help me to figure it out?
here's my code for func_testPopulateLeads.php http://ift.tt/1Nxl5JF
here's my code for func_testSearchByName.php http://ift.tt/1C0pDa5
here's my pagination http://ift.tt/1Nxl5JI
here's my page where func_testPopulateLeads.php and func_testSearchByName.php included as it is inside If Else statement.. http://ift.tt/1Nxl5JK
pls help me
Mass Update on Laravel 5 Collection
I am working on a project where I will need to get at least 1 lac data from SQL table (the data is a 6 digit code indexed on the table), export them into a CSV file and run an update query to update their status.
The export time takes only seconds but because of the update queries it's taking a long time. I am looking for an efficient way to do this task.
Here's my code:
$filename = 'sample.csv';
$handle = fopen($filename, 'w+');
$collection = Code::select('code')->where('status', 0)->take($request->quantity)->get();
foreach ($collection->chunk(500) as $codes) {
foreach ($codes as $code) {
fputcsv($handle, [
$code->code,
]);
// this update query making the whole process taking long time
Code::where('code', $code->code)->update(['status' => 1]);
}
}
fclose($handle);
I am looking for a better way to update those data. Any suggestions?
php query for every record with the same value
I want to detect all records with the same value ( in mysql table ). For each detected record the code should run a while loop where all the records in the same row will be stored into values.
so if i have a table like this in mysql:
| fruit | drink | food |
| apple | cola | chips |
| cherry | fanta | chips |
| banana | sprite | potato |
| strawberry | milk | chips |
and i type in "chips" in my query the code shoult print this:
| apple | cola | chips |
| cherry | fanta | chips |
| strawberry | milk | chips |
I also want to store all the records in an array or an variable. What is the fastest and easiest way to do this?
Thank you
cakephp is not associated with model
I am in trouble in cakephp.
Model: agent.php
class Agent extends AppModel{
var $name = 'Agent';
var $belongsTo = array(
'Arrival'=>array(
'className'=>'AirTime',
'foreignKey'=>'arrival_id'
),
'Departure'=>array(
'className'=>'AirTime',
'foreignKey'=>'departure_id'
));
}
Model: airtime.php
class AirTime extends AppModel{
var $name = 'AirTime';
}
Controller: agentController.php
$condition = array(
'limit'=>20,
'contain'=>array(
'Arrival'=>array(
'fields'=>array('airline_id','flight_num'),
'Airline'=>array('fields'=>'code')
),
'Departure'=>array(
'fields'=>array('airline_id','flight_num'),
'Airline'=>array('fields'=>'code')
)
)
);
$this->Agent = ClassRegistry::init('Agent');
$this->paginate=$condition;
$data = $this->paginate('Agent');
When you run the source of, Warning error is output.
Error:
Warning (512): Model "Agent" is not associated with model "Arrival" [CORE/cake/libs/model/behaviors/containable.php, line 343]
Warning (512): Model "Agent" is not associated with model "Departure" [CORE/cake/libs/model/behaviors/containable.php, line 343]
I do not know how to solve this problem.
How do I use Parent page to get attributes for wp_nav_menu buttons?
I have a WordPress page that I am working on that I have had to change to aid in optimising the SEO of the page. as part of this optimisation, I changed the Page Titles, which has caused an issue with menu's in the header as they originally used the Page Titles as Menu Items.
I made a custom menu and used the wp_nav_menu to have it populate in the header which works well, however, the original wp_list_pages menu had a function where if you hovered over the button, the button colour would change to the background colour of the linked parent page.
The header file code is:
<div id="slideshow" <?php if (is_page_template("page-state.php") OR is_page_template("page-state-2col.php")) { echo "class=\"subnav\"";} ?>>
<div class="image">
<?php
// Get featured image
get_the_image( array( 'link_to_post' => 0, 'the_post_thumbnail' => 'true', 'size' => 'full', 'default_image' => ''.get_bloginfo('template_url').'/images/img-masthead.jpg' ) );
// Get image caption
$args = array( 'post_type' => 'attachment', 'orderby' => 'menu_order', 'order' => 'ASC', 'post_mime_type' => 'image' ,'post_status' => null, 'numberposts' => null, 'post_parent' => $post->ID );
/*
$attachments = get_posts($args);
if ($attachments) {
foreach ( $attachments as $attachment ) {
//$alt = get_post_meta($attachment->ID, '_wp_attachment_image_alt', true);
$caption = $attachment->post_excerpt;
$description = $attachment->post_content;
echo "<p class=\"caption\">" .$caption. "</p>";
//echo "<p class=\"caption\">" .$description. "</p>";
}
}
*/
// Get featured image caption
echo the_post_thumbnail_caption();
?>
</div>
<ul id="state-nav">
<!--?php wp_list_pages('sort_column=menu_order&title_li=&depth=1&child_of=19'); ?-->
<?php wp_nav_menu(array( 'sort_column' => 'menu_order', 'menu' => 'state_menu', 'container_class' => 'state-nav', 'container_id' => 'header', 'theme_location' => 'header', 'child_of' => 19) ); ?>
</ul>
<?php
// Check if page is using the state template
if (is_page_template("page-state.php") OR is_page_template("page-state-2col.php")) { ?>
<ul id="state-subnav">
<?php
$id = $post->ID;
$pid = $post->post_parent;
?>
<?php if($pid != 19) { ?>
<li class="page_item"> <a href="<?php echo get_permalink( $pid ); ?>">Overview</a>
<? } else { ?>
<li class="current_page_item"> <a href="<?php echo get_permalink( $id ); ?>">Overview</a>
<?php } ?>
</li>
<?php
if($pid == 19)
wp_list_pages('sort_column=menu_order&title_li=&depth=1&child_of='.$id.'');
else
wp_list_pages('sort_column=menu_order&title_li=&depth=1&child_of='.$pid.''); ?>
</ul>
<?php
}
?>
</div>
The original CSS is:
#slideshow { position: relative; width: 981px; height: 279px; overflow: hidden; margin:0 0 20px 2px;}
#slideshow.subnav { height: 317px; width: 950px; }
#slideshow .image { position: relative; width: 982px; overflow: hidden; }
#slideshow .image .caption { position: absolute; top: 55px; left: 23px; padding: 10px 25px; margin: 0; background: url(images/bg-slideshow_caption.png); color: #fff; font: 38px/40px Rockwell, Verdana, "Times New Roman", Times, serif; max-width: 470px }
#slideshow #state-nav { position: absolute; right: 0; top: 0; margin: 0; }
#slideshow #state-nav li { border-bottom: 2px solid #36434d; padding: 0; text-align: center; width: 200px; height: 33px; line-height: 33px; }
#slideshow #state-nav li.last { border-bottom: none; }
#slideshow #state-nav li a { display: block; font-size: 14px; color: #fff; text-decoration: none; text-transform: uppercase; background: #586169 url(images/bg-state_nav.png) top center repeat-y; }
#slideshow #state-subnav { position: absolute; bottom: 1px; left: 0; background: #4dc1ff; overflow: hidden; width: 981px; }
#slideshow #state-subnav li { list-style: none; float: left; display: inline; }
#slideshow #state-subnav li a { display: block; font-size: 14px; color: #000; text-decoration: none; padding: 10px 20px; }
#slideshow #state-subnav li a:hover,
#slideshow #state-subnav li.current_page_item a { color: #fff; }
#slideshow #state-nav li a:hover,
#slideshow #state-nav li.current_page_item a,
#slideshow #state-nav li.current_page_parent a { background: #4dc1ff; color: #000; }
/*NSW*/
body.page-id-20 #content h2,
body.parent-pageid-20 #content h2 {color: #4dc1ff; }
/*VIC*/
#slideshow #state-nav li.page-item-31 a:hover,
#slideshow #state-nav li.page-item-31.current_page_item a,
#slideshow #state-nav li.page-item-31.current_page_parent a,
body.page-id-31 #slideshow #state-subnav,
body.parent-pageid-31 #slideshow #state-subnav
{ background: #87d853; color: #000; }
body.page-id-31 #content h2, body.parent-pageid-31 #content h2 {color: #87d853; }
/*QLD*/
#slideshow #state-nav li.page-item-33 a:hover,
#slideshow #state-nav li.page-item-33.current_page_item a,
#slideshow #state-nav li.page-item-33.current_page_parent a,
body.page-id-33 #slideshow #state-subnav,
body.parent-pageid-33 #slideshow #state-subnav{ background: #cd3337; color: #000; }
body.page-id-33 #content h2,
body.parent-pageid-33 #content h2 {color: #cd3337; }
/*SA*/
#slideshow #state-nav li.page-item-35 a:hover,
#slideshow #state-nav li.page-item-35.current_page_item a,
#slideshow #state-nav li.page-item-35.current_page_parent a,
body.page-id-35 #slideshow #state-subnav,
body.parent-pageid-35 #slideshow #state-subnav{ background: #f9b53a; color: #000; }
body.page-id-35 #content h2,
body.parent-pageid-35 #content h2 {color: #f9b53a; }
/*WA*/
#slideshow #state-nav li.page-item-37 a:hover,
#slideshow #state-nav li.page-item-37.current_page_item a,
#slideshow #state-nav li.page-item-37.current_page_parent a,
body.page-id-37 #slideshow #state-subnav,
body.parent-pageid-37 #slideshow #state-subnav{ background: #68b1ae; color: #000; }
body.page-id-37 #content h2,
body.parent-pageid-37 #content h2 {color: #68b1ae; }
/*NT*/
#slideshow #state-nav li.page-item-39 a:hover,
#slideshow #state-nav li.page-item-39.current_page_item a,
#slideshow #state-nav li.page-item-39.current_page_parent a,
body.page-id-39 #slideshow #state-subnav,
body.parent-pageid-39 #slideshow #state-subnav{ background: #cdb189; color: #000; }
body.page-id-39 #content h2,
body.parent-pageid-39 #content h2 {color: #cdb189; }
/*TAS*/
#slideshow #state-nav li.page-item-41 a:hover,
#slideshow #state-nav li.page-item-41.current_page_item a,
#slideshow #state-nav li.page-item-41.current_page_parent a,
body.page-id-41 #slideshow #state-subnav,
body.parent-pageid-41 #slideshow #state-subnav{ background: #2fb56c; color: #000; }
body.page-id-41 #content h2,
body.parent-pageid-41 #content h2 {color: #2fb56c; }
/*ACT*/
#slideshow #state-nav li.page-item-43 a:hover,
#slideshow #state-nav li.page-item-43.current_page_item a,
#slideshow #state-nav li.page-item-43.current_page_parent a,
body.page-id-43 #slideshow #state-subnav,
body.parent-pageid-43 #slideshow #state-subnav{ background: #986fae; color: #000; }
body.page-id-43 #content h2,
body.parent-pageid-43 #content h2 {color: #986fae; }
I have tried to edit the CSS to include the class from the new menu, but I cannot figure out how to make it replicate the original functionality.
Any help would be appreciated.
Cheers
Lloyd
Multiple browser connections getting the same DB object
Running two concurrent scripts that I want to access the database sequentially so that each's autoincrement primary keys are sequential. i.e. running them both (instance A and instance B) at the time will lead to
1-A, 2-A, 3-A, 1-B, 2-B, 3-B
However, currently I get
1-A, 1-B, 2-A, 2-B ,3-A ,3-B
After transactions and locking tables didn't work as I would have expected I did some deeper looking and it appears that both scripts (even when run in different browsers) are getting the same connection. So this would not allow one to block the other. Is there anything I can do to force them to get different connections (changing to mysqli or PDO is not an option as this is an existing system)
Chrome:
object(DB_mysql)#10 (26) {
["phptype"]=>
string(5) "mysql"
...
Firefox
object(DB_mysql)#10 (26) {
["phptype"]=>
string(5) "mysql"
...
Laravel 5: Unable to pass data to controller via redirect
I am trying to pass a query builder to view and I want to print it. Query builder does not return null, but I am unable to pass it or print it.
Controller
public function search() {
$option1 = Request::get( 'option1' );
$option2 = Request::get( 'option2' );
$condition = Request::get( 'condition' );
$date_option = Request::get( 'dateOption' );
$option1_value = Request::get( 'option1_value' );
$option2_value = Request::get( 'option2_value' );
$fromDate = Request::get( 'fromDate' );
$toDate = Request::get( 'toDate' );
if ( $condition == 'no' ) {
$vehicles = Vehicle::with( 'brand', 'section', 'representive', 'buyer', 'seller', 'buyingPaymentType', 'sellingPaymentType' )->where( $option1, $option1_value )->get();
//return $vehicle;
}
if ( $condition == 'or' ) {
$vehicles = Vehicle::with( 'brand', 'section', 'representive', 'buyer', 'seller', 'buyingPaymentType', 'sellingPaymentType' )->where( $option1, $option1_value )->orWhere( $option2, $option2_value )->get();
}
if ( $condition == 'and' ) {
$vehicles = Vehicle::with( 'brand', 'section', 'representive', 'buyer', 'seller', 'buyingPaymentType', 'sellingPaymentType' )->where( $option1, $option1_value )->where( $option2, $option2_value )->get();
}
return redirect()->back()->with( 'vehicles', $vehicles );
//return $vehicles;
}
View
@if(isset($vehicles))
@foreach($vehicles as $vehicle)
<td>{{ $vehicle->id }}</td>
@endforeach
@endif
What am I doing wrong? Any help would be appreciated.
PHP Files showing 404 in a Wordpress site
In a wordress site, I have to add a completely different app. In a domain as:
mydomain.com/live
I created a folder live in the document root.
When index.php or index.html are not there, it shows directory contents.
When index.html is there, it loads index.html by default.
When index.php is there, it shows 404.
Below is my .htaccess file. I am not good with the Apache Configuration. What's causing this?
AddHandler application/x-httpd-php52 .php .php5 .php4 .php3
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
(NATIVE JAVASCRIPT) - The function with ajax request does not provide a response
I'm currently working in a module where in the user will going to register and the following methods that I'm going to mention will check if the email of the registrant is already in use.
Why is it the function with a ajax request does not return any value to other function with ajax request? By the way, I'm not using any javascript framework such as jquery, just a plain and native javascript ;)
By the way, here is the code ^_^
function checkEmailExistense(email){
var url = "library/functions.php?action=emailchecker&emailadd=" + email;
http.onreadystatechange = function(){
if (http.status == 200 && (http.readyState === 4)){
var res = http.responseText;
if (res == "Invalid") {
return 0;
}
}
}
http.open("GET", url , true);
http.send();
}
On another javascript function wherein I have an ajax request for registration, i have an if statement to check if the returning value of the function above is 0;
var emailaddress = document.getElementById("emailadd").value;
if (checkEmailExistense(emailaddress) == 0){
errorcount+=1;
errorstatement+="Email already exist";
}
I don't have a problem with my php query, but here is my code ;)
$action = $_GET['action'];
switch ($action){
case 'emailchecker':
checkTheEmailAdd();
break;
}
function checkTheEmailAdd(){
$email = $_GET['emailadd'];
$connection = new connection();
$realconnection = $connection->connect();
$getCount = mysqli_query($realconnection, "SELECT user_email FROM tbl_user WHERE user_email = '".$email."'");
if(mysqli_num_rows($getCount) > 0){
echo "Invalid";
}
}
Looking forward for some answers. Thank you!
Blogger API: Get number of views and clicks
I have read the Google Developer Documentation but I couldn't find any documentation about how to get the number of clicks and views of a blog post.
Does anyone know if is it possible to get number of views and clicks of a blog post through the Blogger API?
Creating Remember Me with multiple computers
I'm trying to implement a 'remember me' feature on my website, but all the tutorials I've seen are either WAY out of date or mention saving a tokenid to a cookie, checking it against the database and then destroying it every time you login (meaning logging in from 2 different computers would be impossible). Are there any good recent tutorials that deal with this issue especially since the new php 5.5 password_hash fixes a lot of the old problems people had?
Database Query into Associative Array using PHP
I am trying to grab data from my database and place in a format so I can call field1 and return field2.
In my mind I think this:
while($row = mysqli_fetch_assoc($result)) {
$aa = $row["field1"];
$bb = $row["field2"];
}
$cc = array(“$aa”=>”$bb”);
Will compute this:
$cc = array(
"Row1a"=>"Stuff in field2 row1b",
"Row2a"=>"Stuff in field2 Row2b",
"Row3a"=>"Stuff in field2 Row3b",
"Row4a"=>"Stuff in field2 Row4b",
);
After this I will be able to:
echo $cc('Row1a');
To display:
Stuff in field2 row1b
Submit an input box OR a select box (not both)
I want to have the option for my users to submit a form that they have the option to either use either the select box or the input text box, but not both. Here is my form code:
<!-- Text input-->
<div id="incident-type" class="control-group">
<label class="control-label" for="textinput">Incident Type (Use this box or the common incident box)</label>
<div class="controls">
<input id="textinput" name="incident_type" type="text" class=" form-control">
</div>
</div>
<!-- Select Box -->
<div id="incident-control-box" class="control-group">
<label class="control-label" for="textinput">Common Incidents (Use this box or the incident type box)</label>
<div class="controls">
<select onclick="hideInputBox()" id="textinput incident-type1" name="incident_type" type="text" class=" form-control" >
<option value="blank"></option>
<option value="AFA Commercial">AFA Commercial</option>
<option value="AFA Residential">AFA Residential</option>
<option value="MVA W/Injuries">MVA W/Injuries</option>
<option value="Gas Leak Outside">Gas Leak Outside</option>
<option value="Gas Leak Inside">Gas Leak Inside</option>
<option value="Investigation">Investigation</option>
<option value="Possible Structure Fire">Possible Structure Fire</option>
</select>
</div>
</div>
Then here is my code from my PHP where it gets the input boxes of the form:
$incident_type = $row['incident_type'];
The problem I run into is that I want either one of them to submit depending on what the user chooses to fill out. Currently only the select input works, not the text box input also.
get rid of string in mysql dump
I created a script to dump my database, the script is working good but there is something I dont like about it.
The ( ' ), How do I dump my tables without having to remove this in every column that it gets fetched?
This part of my script looks like:
$query = $db->query("SELECT * FROM {$table}");
$numrows = mysqli_num_rows($query);
if($numrows != 0) {
$insert .= "INSERT INTO {$table} ($fields) VALUES \n";
while($row = $query->fetch_array())
{
$insert .= "(";
$comma = '';
foreach($field_list as $field)
{
$row[$field] = preg_replace("#\'#", "", $row[$field]);
$insert .= $comma."'".$db->real_escape_string($row[$field])."'";
$comma = ', ';
}
$insert .= "),\n";
}
$insert = substr($insert, 0, -2);
$insert .= ";\n";
I get rid of the string using this code
$row[$field] = preg_replace("#\'#", "", $row[$field]);
and it works, but is there a way to dump the table without having to remove that and the dump to still be able to be imported ?
Thanks.
Symfony dom crawler failed with NUL character
When I filter some html that contain NUL(http://ift.tt/1Hwijn8) character Symfony dom crawler failed to filter and when I remove NUL characters everything is OK. This is a sample code:
$crawler->filter('div[itemscope] > div[align=justify]');
yii changing removing and renameing column names
I currently have a return that sends back a list of items in an auction. What I am trying to do is clean up the array before I export it to a excel spread sheet. I can use yii or php to clean up the select before exporting, I just need to know how to do it. I know how to do it with a mysql statement but that is frowned upon in the yii world.
This is my current code:
$auction = Btmauctions::model()->findByPk($id);
$listings = $auction->btmListings;
$filename = 'last_lot_export.csv';
$csv = new ECSVExport($listings);
$csv->toCSV($filename); // returns string by default
Yii::app()->getRequest()->sendFile( $auction->name.'_lots.csv' , file_get_contents( $filename ) );
This exports a csv that looks like this:
ID auction_ID lot description manufacturer model more_info condition
21 10 12 FANUC CIRCUIT BOARD Fanuc A20B-9000-0180/09C 3
20 10 1 FANUC CIRCUIT BOARD Fanuc A20B-0008-0242/023A 4
22 10 18 FANUC CIRCUT BOARD Fanuc A20B-1003-0010/12B * A LITTLE DIRTY 3
23 10 19 FANUC CIRCUIT BOARD Fanuc A20B-1003-0020/03A *VERY DIRTY!!! *PLASTIC BROKEN ON RISERS!! COSMETIC ONLY!! 3
What I need to do is clean up the cvs automatically before exporting it so it looks like this:
lot INFO manufacturer model more info condition
12 FANUC CIRCUIT BOARD Fanuc A20B-9000-0180/09C 3
1 FANUC CIRCUIT BOARD Fanuc A20B-0008-0242/023A 4
18 FANUC CIRCUT BOARD Fanuc A20B-1003-0010/12B * A LITTLE DIRTY 3
19 FANUC CIRCUIT BOARD Fanuc A20B-1003-0020/03A *VERY DIRTY!!!
Iterate through specific rows sql php
I have a table that looks like this
+-----------+--------+----------------+---------------------+-------------------+ | commentid | blogid | comment_author | comment_date | blog_comment | +-----------+--------+----------------+---------------------+-------------------+ | 2 | 5 | random guy | 2015-07-01 16:48:35 | | 3 | 5 | James | 2015-07-01 18:54:03 | +-----------+--------+----------------+---------------------+-------------------+
inside there are 2 rows with the blogid=5
when run this code
$checkcomments = "SELECT * from blog_comments where blogid=5";
if ($result=$db->query($checkcomments)) {
while ($data=$result->fetch_object()) {
echo $data->comment_author;
It shows me only 1 name "Random" guy
How do I iterate through all author_names that are part of blogid=5?
Having trouble with load data local infile writing to database
I am new to php and mysqli, and am attempting to put together a stats site for a game that I play. In a nut shell this code 1) looks up by user (via URL) the last X sorties (1 here but can change to any number), 2) Curl's that result, 3) places it into /tmp/sorties.csv, then 4) loads data local infle /tmp/sortie.csv to my database.
It does connect to the database (member table) and look up by member/player name (echos back in "updating for"), as well as the game information (shows 1 sortie per player who has data in the game database) --I've commented out the header so as to see what is echod back.
my site is hosted buy a 3rd party, but is using sql 5.5.32, php 5.3.13, and is a Linux/Debian platform. Any (and all) assistance is greatly appreciated, I actually wrote the vast majority of this by using some of the questions and answers provided here. I do have an only MySQL version of this code that is having the same error (started not working 2 days ago) and am hoping that updating to mysqli will correct the issue. The database fields do match both in number and data-type.
For those curios, the eventual output is at http://ift.tt/1R652Io - after being sorted by date of last login (it's not yet the best looking/functioning site, but it's getting better -- slowly)
//header("Location: /hcman/delsorties.php"); //After sorties put into database - clears any that are not valid
include 'Data/openi.php';
//Collect player name info
$query = "SELECT name FROM Members";
$result=$link->query($query);
// Array
$rows = array();
while($row = $result->fetch_array())
{
$rows[] =$row['name'];
}
// collect sortie data
foreach ($rows as $player)
{
$url = "http://ift.tt/1NxciYd".$player."&startsortie=0&sortiecount=1";
$path = '/tmp/sortie.csv' ;
// echo Player name -- works
echo "<br /><br />Updating for ".$player."<br />" ;
//Curl to tmp file (aka $path)
$ch = curl_init($url);
if($ch === false)
{
die('Failed to create curl handle');
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result=curl_exec($ch);
if(!curl_exec($ch))
{
die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}
curl_close($ch);
file_put_contents($path,$result );
//show sortie (post Curl) data on screen -- Works
echo $result ;
// Input to the database -- Not working
$sqli = "LOAD DATA LOCAL INFILE '/tmp/sortie.csv'
INTO TABLE Sorties
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\''
LINES TERMINATED BY '\n'
" ;
$done=$link->query($sqli);
if (!$done) echo mysqli_error($sqli);
/*if (mysql_affected_rows() >= 1) {
$message = "The user was successfully updated!";
}
else
{
$message = "</br>The user update failed:</br> ";
$message .= mysql_error();
}
echo $message;
*/
}
$result->close();
$link->close();
return $rows;
Ajax .post not returning data like array for JavaScript
I need a JavaScript variable like:
var test_js = {
"first_test": "a_simple_test",
"second_test": "other_simple_test",
"last_test": "last_simple_test"
};
But the array is returned using ajax, i'm trying:
test.php
echo "
'first_test': 'a_simple_test',
'second_test': 'other_simple_test',
'last_test': 'last_simple_test'
";
JavaScript
$.post("test.php").done(function(test_data) {
var test_js = {
test_data
};
});
But when i'll minify the JavaScript (jscompress.com)
The following error is returned:
Unexpected token punc «}», expected punc «:»
How to do to fix it and return the array correctly?
Calculate time hours between "X" dates
I am trying to build Job management tool. I have database with employers who have their card id for Open In and Out.
I want to calculate how many hours they spend outside, and how many they have effective.
My Data:
Log Time: 2015-07-02 08:57:00
Type: Normal Open
Log Time: 2015-07-02 09:21:00
Type: Normal Open
Log Time: 2015-07-02 10:37:00
Type: Normal Open
Log Time: 2015-07-02 10:53:00
Type: Normal Open
Log Time: 2015-07-02 14:29:00
Type: Open (Forward)
Log Time: 2015-07-02 15:20:14
Type: Open (Out)
Log Time: 2015-07-02 15:20:22
Type: Open (Out)
Log Time: 2015-07-02 15:25:22
Type: Open (Forward)
Log Time: 2015-07-02 15:48:22
Type: Ilegal
Log Time: 2015-07-02 16:02:39
Type: Open (Forward)
We have here total: You worked this day: 7 hours, and 5 minutes ( already build with PHP )
Now, there are two OUT's in this case. I want to calculate how much time they spend outside. Is this possible and how i can do it?
Working on PHP5. Remember, this employers can have more outs/ins. So i want to fetch on total time spend outside.
Thanks!
How to Use SSO with vitger crm and owncloud:
I am implementing a SSO in Vtiger crm and Owncloud (with SimpleSAMLphp)
But I ‘am blocked in this step: In saml20-sp-remote.php:
$metadata['http://ift.tt/1NxchDv'] = array(
'AssertionConsumerService' => 'http://ift.tt/1R6556S
http://ift.tt/1NxchDx',
'NameIDFormat' => 'urn:oasis:names:tc:SAML:2.0:nameid-format:email',
'simplesaml.nameidattribute' => 'test',
'simplesaml.attributes' => FALSE,
'ForceAuthn' => FALSE,
'SingleLogoutService' => 'http://ift.tt/1R6556S
http://ift.tt/1R6556U',
);
How can I configure?
Mysqli Getting Multiple Values from Multiple Tables
I'm struggling to figure this out, and it's probably pretty simple but I just can't get it to work. Using PHP/MYSQLI I'm trying to get data from two tables, while the first table will have the basis to get everything, the second table may or may not have data that matches to the first table's data, so I would need the second table to return empty values. For example...
First Table 'Cust':
CustomerID Name School
------------------------------------------
1623 Bob Smith BON
1785 Betty Davis FOOT
1854 John Miller BECK
1547 Kate Lake BON
Second Table 'Ybk':
CustomerID Frame Type
------------------------------------------
1623 001 CC
1854 012 CC
What I would like to get from these two tables is a bit variable between two things...
1) If I want to select the School from the first table (For example WHERE Cust.School='BON') I would like to get this result back:
CustomerID Name School Frame Type
---------------------------------------------------------
1623 Bob Smith BON 001 CC
1547 Kate Lake BON
2) Or, if I select everything, I get this result back:
CustomerID Name School Frame Type
---------------------------------------------------------
1623 Bob Smith BON 001 CC
1785 Betty Davis FOOT
1854 John Miller BECK 012 CC
1547 Kate Lake BON
Right now, when I try some different versions of the SELECT statement I only get back results that are in both tables instead all of the Cust fields returning with the Ybk ones if they exist as well. Help! Thank you!
Displaying List from mysql data using jquery mobile
Im trying to get my squery mobile app to show certain data of mysql in a listview mode. It seems to be something wrong as nothing happens when I try it.
Here is my html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Watto</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="../css/app.css" rel="stylesheet" />
<link href="../css/themes/2/watto.min.css" rel="stylesheet" />
<link href="../css/themes/2/jquery.mobile.icons.min.css" rel="stylesheet" />
<link href="../lib/jqm/jquery.mobile.structure-1.4.5.min.css" rel="stylesheet" />
<script src="../js/listaplanesnuevos.js"></script>
<script src="../lib/jquery/jquery-2.1.4.min.js"></script>
<script src="../lib/jqm/jquery.mobile-1.4.5.js"></script>
<script src="../services/getplanes.php"></script>
<link rel="apple-touch-icon" href="../img/apple-touch-icon.png" />
<link rel="apple-touch-icon-precomposed" href="../img/apple-touch-icon.png"/>
</head>
<body>
<!----------PLANES NUEVOS ------------>
<div data-role="page" id="planesnuevos">
<div data-role="header" data-position="fixed">
<h1>Planes Nuevos</h1>
</div> <!----HEADER---->
<div role="main" class="ui-content">
<ul id="listaplanesnuevos" data-role="listview" data-filter="true"></ul>
</div> <!------ CONTENT ----->
<div data-role="footer">
<div data-role="navbar">
<ul>
<li><a href="#planesnuevos" data-icon="home" class="ui-btn-active"></a></li>
<li><a href="#search" data-icon="search"></a></li>
<li><a href="#chooser" data-icon="eye" data-iconpos="right"></a></li>
<li><a href="#location" data-icon="location"></a></li>
<li><a href="../settings" data-icon="gear"></a></li>
</div>
</div>
</body>
</html>
Here is my JavaScript:
var serviceURL = "http://localhost/directory/app/watto/services";
var planes;
$('#planesnuevos').bind('pageinit', function(event) {
getListaPlanes();
});
function getListaPlanes() {
$.getJSON(serviceURL + 'getplanes.php', function(data) {
$('#listaplanesnuevos li').remove();
resplanes = data.items;
$.each(resplanes, function(index, plan) {
$('#listaplanesnuevos').append('<li><a href="detallesplan.html?id=' + plan.folio + '">' +
'img src="pics/' + plan.foto + '"/>' +
'<h4>' + plan.nombre + '</h4>' +
'<p>' + plan.descripcion + '</p></a></li>');
});
$('#listaplanesnuevos').listview('refresh');
});
}
and here is the PHP file
<?PHP
include 'config.php';
$sql = "SELECT `folio`, `nombre`, `descripcion`, `foto` FROM `Planes` GROUP BY `folio` ORDER BY `folio`";
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$planes = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
echo '{"items":'. json_encode($planes) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":' . $e->getMessage() . '}}';
}
?>
I don't know what is wrong, please help as im new to this.
Thanks!
How do I make this code refresh every minute?
How do I make this code refresh every minute?
<script type="text/javascript">
$j(document).ready(function () {
$j('#left-box').load('pages/box.php');
});
</script>
I want it to refresh every 1 minute I've tried other stuff cant do it
ajax queries still waiting after window close
I have webpage that has an ajax call that gets data from a php script.
ajaxRequest = new XMLHttpRequest();
ajaxRequest.open("GET", "submit.php?id=" + id, true);
ajaxRequest.send(null);
Inside the submit.php I wait for a binary to finish and create an outfile.
while(1){
if(is_file($OUTFILEPATH)){
break;
}else{
sleep(60);
}
}
The problem is that if the user closes the browser window, the ajax call and corresponding httpd are not aborted.
And if the user refreshes the webpage multiple times, I end up having hundreds of httpd processes all waiting for the the same outfile to be created.
Apache Server Status
115 requests currently being processed, 5 idle workers
WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW
WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW_W____........
................................................................
................................................................
Scoreboard Key:
"_" Waiting for Connection, "S" Starting up, "R" Reading Request,
"W" Sending Reply, "K" Keepalive (read), "D" DNS Lookup,
php and deleteing variable on from 2 array
Array1
(
[0] => 14
[1] => 9
[2] => 10
[3] => 11
)
Array2
(
[0] => 8
[1] => 9
[2] => 10
[3] => 11
[4] => 12
[5] => 13
[6] => 14
[7] => 15
[8] => 16
[9] => 17
[10] => 18
[11] => 19
[12] => 20
[13] => 21
[14] => 22
[15] => 23
[16] => 24
some function to delete the array1 values on array 2 and create a array3 whit the results ?
thanks !