samedi 27 juin 2015

Adding up values in array

I am trying to count elements in an array separated by one or more zeroes (0) Example: [3,2,1,0,5,4,0,0,8,4]. 3+2+1 , 5+4 , 8+4 Output: [6,9,12] I have written the following function:

function countElementsInArray(){
$array = [1,2,4,0,9,8,4,0,7,1,2,6];

$countArr = [];
$count = 0;
$test = 0;

for($i = 0; $i < count($array); $i++){
    if( $array[$i] != 0 ) {
       $count += $array[$i];
    } 
    //else if($array[$i] == 0 || $array[$i - 1] == 0){
    else{
        $count = 0;
        $test += 1;
    }
    $countArr[$test] = $count;
}
return $countArr;

}

This works fine if I have only one "0" in the array. I can't figure out how to add up the values if I have 2 zeroes. Any idea how to solve this problem?

Laravel Polymorphic many to many relationship issue

I have a Many to Many Polymorphic relationship setup between a few models and everything seems to be working just fine with one slight issue...

If I add the same relation $book->genres()->save($scifi) multiple times, it shows up multiple times in my database. Maybe this is intentional, maybe it's not. If I'm overlooking something, I'd like to have it working the "Laravel" way before I go and start making methods to ensure that only one relationship of that kind is in the DB at a time.

Does load_file() in SIMPLE HTML DOM have timeout settings?

I use SIMPLE HTML DOM for parsing. Some pages take a very long time when i try to get contents. I need to set limit for function load_file() (for example 10 sec) -> go to the next page. Please without socket!

Chrome is requesting HTTPS suddenly and I can't log into admin area

I recently moved a wordpress site from one hostgator account to another. It's now an addon domain. For the last couple days everything was working fine.

Then suddenly Chrome started giving me this error when I tried to reach my admin area: enter image description here

Proceeding didn't help either as I don't have an SSL, so it returns a 404. enter image description here

In fact it doesn't matter what URL hijinks I play, any time I access the admin area it tries to use HTTPS.

This is only on Chrome. It appears that Chrome is requesting an HTTPS address. I've tried commenting out all the https code in wp-login.php but no dice.

I've tried uninstalling Chrome, clearing cookies, etc. No good.

I'm at my wit's end.

PHP included HTML relative path of external JS & CSS

I am trying to use PHP to read, then modify and echo an HTML file.

The included HTML file contains external JS, CSS references - all relative paths

for example...

<script src="js/myJavascript.js"></script>

Problem : The location of the PHP modifier file is not the same as the location of the included HTML file, and therefore the external includes are not loaded. I guess...

The solution of using absolute paths to reference external resources in the HTML file is not ideal to say the least...

What can be done to tell PHP that the path context of the included HTML file is the same as the directory from which it is being included and NOT the directory of the modifier file?

Thanks!

SELECT query with apostrophe

In my database, I have a column named storeName with a value called Joe's Kitchen.

When user enters Joe's Kitchen, I would store it in a variable named storeName and do a select query on it like this: "SELECT * FROM shops WHERE storename='".$storeName."'". Problem now is that the value contains apostrophe, how should I go about this ?

I have tried the method below but it is not working

$storeName = mysqli_real_escape_string($db->getConnection(),$_POST["storeName"]);

.NET web service and php client

I am new to php client interaction with .NET web service. I have looked around and aware of posts like the one below but there are not the answer to my question.

How to make a PHP SOAP client and store the result xml in php variables

http://ift.tt/1eOTCI5

Consume a .Net web service using PHP

A PHP SOAP client (to request and get response) is needed for .NET web service (http://localhost:8080/someexample/myservice.wsdl). The input/request would look like this:

<the_input name="secondyear">
  <authen>
    <Teacher>
     <teacherid>MrX</teacherid> 
     <password>t_pass</password> 
    </Teacher>
    <Student>
     <studentid>kids</studentid> 
     <password>s_pass</password> 
    </Student>
   </authen>
 <parameters>
    <parameter name="maths" value="123" /> 
    <parameter name="physics" value="abc" />
    <parameter name="sports" value="def" /> 
 </parameters>
</the_input>

Here is what i got but not working and i am not sure i am on the right track:

<?php 
 require_once("lib/nusoap.php");
 $url="http://ift.tt/1NkBRuL";
 $client = new SoapClient($url);

 $teacherid='MrX';
 $tpassword='t_pass';
 $studentid='kids';
 $spassword='s_pass';
 $ns = "http://example.com/";

 //Body of the Soap Header.
 $headerbody = array ('Teacher' => array('teacherid' => $teacherid,
                                      'password' => $tpassword ),
                      'Student' => array('stendentid' => $studentid,
                                       'password' => $spassword ));
 //Create Soap Header.
 $header = new SOAPHeader($ns, 'Authen', $headerbody);

 //set the Headers of Soap Client.
 $headerparam=$client->__setSoapHeaders($header);

 $name ='secondyear';
 $service_name = array('the_input'=>$name);

 $result =$client->__SoapCall($service_name,$headerparam)
 print_r ($result);
?>

I read somewhere in order to authenticate to a web service, one should put authentication parameter in php header, so what goes to the php body then or is it needed? is the parameters? parameter has the format of name and value, how do i do that in php array? any relevant example available? as mentioned i've done my research and not clear how to solve this problem.

Postgre user without password and PHP

I have a PostgreSQL database with a user and a database owned by that user. A local program written in C uses that user to manipulate that database without a password. I want to use HTML and PHP to create a web interface to access that database.

I've read conflicting things about PostgreSQL and using it without passwords. I also don't want to interfere with the way the current software is accessing and manipulating the database without a password.

Do I simply add a password for that user to use as log-in information for the PHP queries? Is there a better way to securely access that database through PHP?

When to use RDS service in amazon? I have mysql installed in ec2 instance

I have a dynamic website and I need to migrate to AWS. I am new to AWS and linux. I have a doubt while setting the environment. I have installed Mysql,Phpmyadmin separately.

I have the following questions :

  1. How to connect this installed Mysql with this installed Phpmyadmin ? How to access Phpmyadmin through browser in aws.
  2. Why do we need RDS then? Do I really need RDS instance?

Please help me..

Trying to use Path API but failing to deal with access token

I want to use the Path Api, what is the right URL to get access_token ?http://ift.tt/1eRoGH6

if else condition in htaccess for for admin and frontend in open cart?

i have .htaccess in which i want 301 redirect.So when I add 301 redirect code in .htaccess it works fine but i can not login to my backend.But if I remove this code it works fine.I just want it to work in frontend but now because of this code my I cannot login into backend.

Here is the CODE

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://ift.tt/VAk5HC [L,R=301,NC]

now i want if else condition or something which helps me to solve this error which works only for frontend of my open cart site and admin remains as it is without redirection.

Remove duplicates from PHP array but ignoring one parameter

I have an array comprised of PHP objects as such.

$objects[0] => $object->type => 'President'
               $object->name => 'Joe Blogs'
               $object->address => '123 Harry Street'

$objects[1] => $object->type => 'Secretary'
               $object->name => 'Joe Blogs'
               $object->address => '123 Harry Street'

$objects[2] => $object->type => 'Treasurer'
               $object->name => 'Jane Doe'
               $object->address => '456 Upton Street'

I would like to ignore the 'type' parameter and end up with

$objects[0] => $object->type => 'President'
               $object->name => 'Joe Blogs'
               $object->address => '123 Harry Street'

$objects[2] => $object->type => 'Treasurer'
               $object->name => 'Jane Doe'
               $object->address => '456 Upton Street'

I have tried a few difrent things one of which was to unset the parameter "type using a foreach loop and then trying to reset it but I wasn't sure how to tie the two indexes together to reset them. Another was trying to use the union in the select command but that wasn't working 100% correctly either.

I am just not sure how to best manage the type parameter

group_concat only display's one column?

I have a database structure like so

 Car
 - id   
 - carname
 - image
 - category
 - status

Parts
 - partid
 - partname

CarParts
 - carpartid
 - carid(fk)
 - partid(fk)
 - amountid(fk)

Category
 - id
 - categoryname

Amount
 - amountid
 - amountvalue

and here is my query:

SELECT group_concat(parts.partname) as parts FROM car left join  carparts on car.id = carparts.carpartid 
left join  parts on parts.partid = carparts.carpartid
left join amount on amount.amountid = carparts.amountid where status = 1
group by car.id

but this only display parts and nothing else i want

  • carname
  • image
  • category
  • status

PHP code inside Laravel 5 Blade Template

I have to place some PHP code inside Laravel 5 Blade Template. Like below

@foreach ($farmer->tasks as $task)
    @if ($task->pivot->due_at) < date(now))
        $style = 'alert alert-danger';
    @elseif ($task->pivot->due_at) > date(now))
        $style = 'alert alert-success';
    @else
        $style = '';
    @endif
@endforeach

Which is the actual procedure to place PHP code inside Laravel 5 Blade Template ??

How to use $query->set in a custom .php page?

this is my custom.php file.

require_once("wp-load.php");
global $wpdb;

$query->set('posts_per_page', 50 );           
$query->set('orderby', 'meta_value_num');
$query->set('meta_key', '_thumbs_rating_up');
$query->set('date_query', array( 'after' => '1 month ago' ));   
$query->set('order', 'DESC');   

How can a start this query now?

Server side: Fill form on a webpage

Lets say there's a form on a webpage with URL xyz.com . The form has some text input fields, some drop down selections to be made etc. I need to write a server side script to visit this web page and fill and submit the form. Note that the server doesn't have a browser environment.

What should I do to achieve this? Any techniques in PHP (using cURL) or Python or echoing Java script via PHP ? I'd also have the form field IDs with me.

run function that returns several foreach

I'm developing the script, do a search in an array with one or several keywords, which is the following script:

$url= "http://ift.tt/1JqYyQ7".date('d')."&output=json&groupby=country-adspace&period_group_by=day";


function search($array, $key, $value)
{
    $results = array();

    if (is_array($array)) {
        if (isset($array[$key]) && $array[$key] == $value) {
            $results[] = $array;
        }

        foreach ($array as $subarray) {
            $results = array_merge($results, search($subarray, $key, $value));
        }
    }

    return $results;
}


$json = file_get_contents($url);
$arr = json_decode($json, TRUE);



$my_date_arr = search($arr, 'ADSPACE', '41432');

I then returned the key, containing only that number as keyword. and I do another foreach to show only keys containing the characters.

  <?php
foreach ($my_date_arr as $key=>$value) :
  $country = $value['COUNTRY'];
  $clicks = $value['CLICKS'];
  $fecha = $value['DATE'];
  $adspace = $value['ADSPACE'];



?> 
    <td><?= $country; ?></td>
    <td><?= $clicks; ?></td> 
    <td><?=$fecha;?><td>
   <td><?=$adspace;?><td>

  </tr>

  <?php endforeach;?>

it all works perfectly, the problem is I want to make two requests to the same function with a different value for example:

$my_date_arr = search($arr, 'ADSPACE', '41432');
$my_date_arr = search($arr, 'ADSPACE', '41755');

the goal is to look into an array a predetermined value, then return the key that contains the value and thus only make a foreach of what I find in the foreach, but also need is to make several requests in that foreach to I return the entire result in a single request.

Separate multiple meta values with slashes within a $list (wordpress)

I want to list some custom posts (wordpress) and their meta values. Everything works fine so far, but I have to work with empty values too. And I want to use slashes to separate multiple values. So here's what I have so far:

$list = '<div class="clearfix vlist">
         <div class="vlist-content">' ;

while($wpex_query->have_posts()) : $wpex_query->the_post();

global $post;

$list .= '<div class="vlist-item">
          <div class="title">'.get_the_title().'</div>
          <div class="info">'
          .get_post_meta( $post->ID, 'wpex_vita_genre', true ).' / '
          .get_post_meta( $post->ID, 'wpex_vita_director', true ).' / '
          .get_post_meta( $post->ID, 'wpex_vita_role', true ).'</div>
          </div>';
endwhile;

wp_reset_query();

return $list . '</div></div>';

Problem comes within div.info, where I want to display 3 values, separated by slashes (/). Soon as one or two values are empty I get stupid double slashes // because these characters are not conditional. I don't know how to make them appear only when there are values to separate because I can't just put an if statement into my $list. I know I know now you people who know php are just shaking heads or doing facepalms because this for sure is easy pie... could you still tell me how to solve this problem?

Thank you!!

PHP Not Inserting Content in mySQL Database: Text, Images, Anything

So here is my dilemna that I've been reviewing and trying to break through for the last few days. I've created a basic login/register PHP system, which works fine. I've implemented a blog system that displays posts. I've written an add post function which does not post to the database, and it doesn't throw back an error function either.

I don't really understand because my register system works and adds new users, but the 'add blog post' does nothing. I can add from the database and it displays fine, but nothing here.

<?php
    error_reporting(E_ALL & ~E_NOTICE);
    session_start();

    if (isset($_SESSION['id'])) {

        $userId = $_SESSION['id'];
        $username = $_SESSION['username'];
    } else {
        header('Location: login.php');
        die();
    }

    if ($_POST['submit']) { 
        $title = strip_tags($_POST['title']);
        $subtitle = strip_tags($_POST['subtitle']);
        $content = strip_tags($_POST['content']);

        mysqli_query($dbCon, $userREQ3);
        $userREQ3 = " INSERT INTO `logindb`.`blog` 
        (`title`, `subtitle`, `content`) VALUES ('$title','$subtitle','$content')";

    }
?>

<!DOCTYPE html>
 <html>

   <head>

   </head>

   <body>
     Welcome, <?php echo $username; ?>, You are logged in. Your user id is <?php echo $userId; ?>.

    <a href="index.php">Index</a>
    <form action="logout.php">
        <input type="submit" value="Log me out!">
    </form>

    <form method="post" action="admin.php">
        Title: <input type="text" name="title"/><br>
        Subtitle: <input type="text" name="subtitle"/><br>
        <br>
        <br>
        Content: <textarea name="content"></textarea>
        <input type="submit" value="Write Post"/>
    </form>

   </body>
</html>

What software or IDE should I use to design front-end of a website?

I have a knowledge of HTML, CSS and Javascript. It is difficult to design website on Notepad++, and I think Dreamweaver is for beginners. Tell me how professional designers work? How websites like Facebook, Twitter are Designed?

Note: I am not talking about static website. I want to design dynamic website with PHP.

Blogger API : Get number of seen and clicks

I have read Google Developer Documentation but I couldn't find any documentation about get number of click and seen of a blog post. Does anyone know is it possible to get number of seen and click of a blog post through API?

Why isn't my js script loading in WordPress

I am trying to add a bootstrap js script to my WordPress theme the "right" way but i'm not seeing a link to the js file in the head section of the webpage when it loads. Iv'e tried adding it to the header of the WordPress theme the "right" way but no luck. Not i'm trying in the functions.php file and still no luck. Please help!

function buns_bootstrap_run(){


        wp_register_script('bootstrap-js', get_stylesheet_directory() . '/js/bootstrap.min.js', array('jquery'),'3.2.0', false);

        wp_enqueue_script('bootstrap-js');

        }

    add_action('wp_enqueue_script', 'buns_bootstrap_run');

Lumen multiple queues

I am wondering how to setup multiple queues with Lumen?

I have setup the below

\Queue::pushOn('xmlApi','App\Eve\Api\Corp\CorpSheetLimited@fire',['corpID'=>$id['corporationID']]);

now i am attempting to process it with a queue worker below

php artisan queue:work xmlApi --daemon --sleep=3 --tries=3

when i push onto the queue with the below it processes no issues

\Queue::push('App\Eve\Api\Corp\CorpSheetLimited@fire',['corpID'=>$id['corporationID']]);

processing with

php artisan queue:work --daemon --sleep=3 --tries=3

Can you please advise

Image retrieval from mysql database in php not working

I am getting an image from mysql database and trying to show it. I am using the following code. But its not working .What's the mistake i am making?

while ($row=mysql_fetch_array($result,MYSQL_ASSOC)) {
    $photo=$row['photo'];
    $name=$row['firstname'].' '.$row['lastname'];
    $email=$row['email'];
    echo "<tr><td>".'<img src="data:image/jpeg;base64,<?php echo base64_encode( $photo ); ?>" />'.'</td><td>'.$name.'</td><td>'.$email.'</td></tr>';
}

How Get an array by JSon and how i can set this return value to a modal form?

My Ajax code is

$("a#edit").click(function(){
      var id = $(this).closest('tr').attr('id');
        //alert(id);
$.ajax({
        url: 'getdata.php',
        type: "POST",
        dataType:'JSON',
        data: {
            id: id,
        },
        success:function(result){
            alert(result);
        }
      });
    });

My php code is here...

if ($_REQUEST['id'] != "") 
{
     $id=$_REQUEST['id'];
   $sql = "select * from visit_reports WHERE visit_planner_id='$id'";

        $query = sqlsrv_query( $link, $sql);
        while($data = sqlsrv_fetch_array($query,SQLSRV_FETCH_ASSOC))
            {
              print_r($data);
      }  
  }

In firebug the array i get ..

Array
(
[id] => 1.0000
[visit_planner_id] => 230338
[bi_staff_present_name] => BI staff present name
[bi_staff_trial_function] => BI staff trial function
)

Now how i can use this array value into my specific input field of modal form ?

css not working after writing .htaccess

I was trying to get rid of my file extensions using .htaccess, it worked, but right now my CSS and images has stopped working. I have tried different things, but it's still not working. Please! I need help with this. Thanks in advance. All my php files are in the same directory which is the root folder and my css and image folder is in a different folder in my root folder. here is my code

RewriteEngine On
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*/.php$ %{REQUEST_FILENAME}.php [L]
RewriteRule ^(css|img) - [L]

Wordpress - Is using wp_mail function a sufficient way of sending emails

I am using wordpress and wish to create a custom php script instead of using a plugin for the contact form. I want to know if using the wp_mail function is the same as the php mail() function because my host sometimes has issues sending the mail without sending it via the smtp.

I've always used something like php_mailer ect for my contact forms but am new to wordpress.

Fatal Error call to member function count() is non object

I am trying to query a database using pdo, but I cant figure out the problem. I have created an init file for my db details and server details and config file for configuration and index file and DB file.

index.php

<?php
  require_once 'core/init.php';

  $user =  Db::getInstance()->get('users',array('username', '=' , 'raja' ));

  if($user->count()) 
  {
      echo "No user";
  }
  else{
    echo "OK!";
  }


?>

Db.php

<?php
    class Db
    {
        private static $_instance = null;
        private $_pdo,
                $_query,
                $_error=false,
                $_results,
                $_count=0;
        private function __construct()
        {
            try
            {
                $this->_pdo =new PDO("mysql:host=" .Config::get('mysql/host') . ";dbname=" .Config::get('mysql/db'),Config::get('mysql/username'),Config::get('mysql/password'));
            }
            catch(PDOException $e)
            {
                    die($e->getMessage());
            }

        }

        public static function getInstance()
        {
            if (!isset(self::$_instance)) 
            {
                self::$_instance = new Db();
            }
            return self::$_instance;
        }
        public function query($sql,$params=array())
        {
            $this->_error = false;
            if($this->_query = $this->_pdo->prepare($sql))
            {   
                $x=1;
                if (count($params)) 
                {
                    foreach ($params as $param ) 
                    {
                        $this->_query->bindValue($x,$param);
                        $x++;
                    }
                }
                if ($this->_query->execute())
                 {
                        $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
                        $this->_count = $this->_query->rowCount();
                 }  
                 else 
                 {
                    $this->error=true;
                 }
            }
            return $this;               
        }
        public function action($action,$table,$where=array())
        {
            if(count($where) === 3)
            {
                $operators = array('=','<','>','>=','<=');

                $field     = $where[0];
                $operator  = $where[1];
                $value     = $where[2];

                if(in_array($operator,$operators))
                {
                    $sql = "{$action}FROM{$table} WHERE {$field} {$operator} ?";

                    if($this->query($sql,array($value))->error()){
                        return $this;
                    }
                }
            }
            return false;

        }
        public function get($table,$where)
        {
            return $this->action('SELECT *', $table, $where);
        }
        public function delete($table,$where)
        {
            return $this->action('DELETE ', $table,$where);
        }

        public function error()
        {
            return $this->_error;
        }
        public function count()
        {
            return $this->_count;
        }
    }
?>

It reports a fatal error about not finding the count object:

Fatal error: Call to a member function count() on a non-object in C:\xampp\htdocs\Student Management system\index.php on line 6

What is a method to notify you when things "don't" happen?

I have lots of different scripts and quite a few cron jobs that trigger different things throughout the day. Many times it is to download data from an external API or to periodically run a script of some type.

However, I am at a loss in finding a simple method to notify me if these things don't happen. For example, recently, something happened on one of my servers that caused all the cron jobs to stop running. It took a few days before I started getting complaints that things weren't working right. What are some of the methods you use to make sure things happen on a regular basis?

Display the number of before held training

I am new in Laravel and I used Laravel 5 for my project. My specification is count the number of before held training according to category of training so i used join and group by and count function to get the number before held training:

In my controller code is as below:-

<?php

namespace App\Http\Controllers;
use Request;
use App\Training;
use App\Schedule;
use App\User;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\TrainingRequest;
use Carbon\Carbon;


  class TrainingController extends Controller
  {
/**
 * Display a listing of the resource.
 *
 * @return Response
 */

public function __construct(){

$this->middleware('auth',['only'=>'index']);
}
public function index()
{
    //


    $training=Training::all();

        $before_held=Schedule::join('training','training.id','=','schedule.training_id')
                 ->groupBy('training.category')->where('schedule.training_end_date','>=',carbon::now())->get();
   // echo count($before_held);
   //die();


    return view('Training.index',compact('training','before_held'));
}

In View:-

 <td><a href="/training/before_held">{{count($before_held)}}</a></td>

This always show 0 count in the table like this:-

|category|Held Before|
|test    |   0       |
|test    |   0       |

But I need count two if training_end_date greater than or equal to current time.

SO I am thankful if anyone can solve this issue.

Display wordpress sub-category posts on sub-category page

I'm trying to get a WP function to work properly.

I want it to display the posts from the selected sub-category page, for example, when navigating to: http://ift.tt/1BUiBUF, display all custom posts under "apples" category. I want to do this dynamically, so that no matter the number of sub-categories (apples, oranges, pears etc) this works every time the sub-category page is visited.

The following is my current function, but I don't know if the get_query_var('cat') is implemented properly. Currently, when I visit the sub-category page, it displays ALL posts with the parent category "fruits", but I want it to display just the "apples" posts.

<?php

$cat = get_query_var('cat'); // get current category
$yourcat = get_category($cat);

// only display product CPT posts 
query_posts( array( 'post_type' => 'products' ) ); 

if ( have_posts() ) : while ( have_posts() ) : the_post();
?>
  <div class="col-sm-3">
    <div class="thumbnail">
        <div class="more"><a href="<?php the_permalink(); ?>"><span class="fa fa-location-arrow"></span></a></div>
        <?php the_post_thumbnail(); ?>
        <div class="caption">
            <a href="<?php the_permalink(); ?>" class="btn btn-default" role="button"><?php the_title(); ?></a>
        </div>
      </div>
  </div>
<?php endwhile; endif; wp_reset_query(); ?>

ManyOnOne in a twig template

I have the following tables (and entities in / ):

+------------------+                  +--------------------+
|  forum_sections  |                  |  forum_categories  |
+------------------+                  +--------------------+
| id               ├--------|         | id                 |
| title            |        |---------| section            |
| position         |                  | position           |
| created_at       |                  | title              |
+------------------+                  | description        |
                                      +--------------------+

I want to archive the following html page (without the bullets ofcource):

  • this is a title (from forum_sections->title)
    • forum 1 (from forum_categories->title)
    • forum 2 (from forum_categories->title)
  • this is another title (from forum_sections->title)
    • forum 3 (from forum_categories->title)

I did some research on how to do this. So far I tried the following in my twig layout:

{% for section in sections %}
    <h1>title</h1>

    {% for category in categories %}
        bla bla
    {% endfor %}
{% endfor %}

Is this even possible with a 'findAll' query in Doctrine2? I tried some combinations, but they seem to get all the boards ignoring the sections.

My program in php is not working [on hold]

This program i have been debugging:


<?php
$SQLHost="localhost" ;
$SQLDBName="webgeein_database";
$SQLUser="webgeein_root" ;
$SQLPass="gaurav_singh"; 


$conn = new mysqli($SQLHost, $SQLUser, $SQLPass );
if ($conn->connect_error) 
{
$strErr = sprintf ( "Could not connect to server [%s] Error Code [%d]     \nError Message [%s]", $SQLHost, $conn->errno, $conn->error);
echo ( $strErr);
die ();
}

$conn->select_db ($SQLDBName);
$query = "SELECT * FROM student_record WHERE Name='RAMAN'" ;
if($query){echo("success");}else{echo("failure");} 

$result = $conn->query($query, MYSQLI_STORE_RESULT );
if($result){echo("success");}else{echo("failure");} 

$row = $result->fetch_assoc();
if($row){echo("success");}else{echo("failure");} 

$AGE = $row ['Age'] ;
if($T_Status){echo("success");}else{echo("failure");} 

echo($AGE);

?>

but even then the response is failure at running the query function.

and the result shown is

"""""successfailure."""""

I hope someone would solve the problem.

enter code here

MySQL syntax error (INSERT) [duplicate]

This question already has an answer here:

I need help with a simple MySQL insert query. I have the following code:

INSERT INTO reads (location, meter, value) VALUES ('$_GET[location]', '$meter', '$value')

Which, after PHP, translates into:

INSERT INTO reads (`location`, `meter`, `value`) VALUES ('1234','1111','2505')

This query returns the following error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'reads (location, meter, value) VALUES ('1234','1111','2505')' at line 1

I have gone over my syntax many times and just cant figure out what is wrong with my query. Can anyone spot it?

How to store XML field values in database using php

I have an XML in local server. I want to store values in databse using Php. How to do it. Any sample code plz to achieve it.

PHP file_exists returns false with existing files

I'm having a little problem with my PHP-code. I want to create a site which has different directories. Every directories has a file named pass (not .txt or something) with the value of the directories password. So if the pass-file doesn't exist the group will not exist. But even if the group exists it still says the group doesn't exist. Here's my code:

<?php
$name = $_POST['name'];
$group = $_POST['group'];
$pass = $_POST['pass'];
$filename = '/groups/' . $group . '/pass';
if(file_exists($filename)){
    $handle = fopen($filename) or die("can't open file");
    $hoi = fread($handle, filesize($filename));
    fclose($handle);
    if ($pass === $hoi){
        session_start();
        $_SESSION['name'] = $name;
        header('Location: http://www.google.com');
    }
    else{
        echo 'Password is wrong!';
    }
}
else{
    echo 'Group does not exist!';
}
?>

All POST-data is correct btw. Thanks for your help!

Ajax request to php from angular js

I am trying make an ajax request to php from angular js. But I am not getting the data I have sent. Please let me know where I am going wrong.

The following is the ajax call.

<script type="text/javascript">

    angular.module('app', []).controller("MyController", function($scope, $http) {

    var req = {
        method: 'POST',
        url: 'pujastrail/www/rest/get.php',
        headers: {
            'Content-Type': "application/x-www-form-urlencoded; charset=utf-8"
        },
        data: { lang: "fr" }
    }
    $http(req).success(function(data, status, headers, config){alert("done"+data);}).error(function(data, status, headers, config){alert("error"+res);});

        });
</script>

The following is the php code.

<?php
    if (isset($_POST['lang']) && !empty($_POST['lang'])) {
        $lang = $_POST['lang'];//this needs to be sent back to js file
    } else {
        $lang = "eRROR";// but this is being sent back to the js file
    }

    echo (json_encode($lang));
?>

I have tried this using $_REQUEST also but it didnot work.

How to use REST with MVC when there is no Database?

I have two servers, the first works using REST and other Webs pages that are built using MVC.

I usually always run REST commands in the Controller layer, however I am with a doubt, assuming that my project (using MVC) does not use database and I'm using Controllers only to send commands to the webservice to send and receive information.

  • The REST in this case would be equivalent to Model?

    In this case I should call the Rest within the Controllers and not create Models. eg .:

    public function createProductAction() {
        $rest = Rest('ws.example.com', 'PUT /items/', array(
                                            'price' => $price,
                                            'description' => $descricao
                                        ));
    
        if ($response->status === 200) {
            View::show('success.tpl');
        } else {
            View::show('error.tpl', $rest->error);
        }
    }
    
    

or

  • I would have to create Models to make the calls to REST?

    For example:

    class ProductsModel
    {
        public function putItem($preco, $descricao)
        {
            $rest = Rest('ws.example.com', 'PUT /items/', array(
                                                'price' => $price,
                                                'description' => $descricao
                                            ));
    
            //If status=200 new product is added
            return $response->status === 200;
        }
    
        public function deleteItem($id)
        {
            Rest('ws.example.com', 'DELETE /items/{id}', array(
                                                'id' => $id
                                            ));
    
            $response = json_decode($rest->getRespose());
    
            //If status=200 product is deleted
            return $response->status === 200;
        }
    
        public function getItem($id)
        {
            $rest = Rest('ws.example.com', 'GET /items/{id}', array(
                                                'id' => $id
                                            ));
    
            $response = json_decode($rest->getRespose());
            if ($response->status === 200) {
                //If status=200 return data
                return $response->data;
            }
    
            return NULL;
        }
    }
    
    

How should I proceed?

Facebook Graph API. How to get comment from post

Hi i have this to get comment from post it works is there is a years

 $json = file_get_contents("http://ift.tt/1RHTDtg");
    echo $json;

but now i have this error in facebook

{
   "error": {
      "message": "An access token is required to request this resource.",
      "type": "OAuthException",
      "code": 104
   }
}

how i can get all comment from post ?

i have using your code @luschn my request with true APP ID and App Secret

http://ift.tt/1eRiTBa]

i have this

{
   "error": {
      "message": "Invalid OAuth access token signature.",
      "type": "OAuthException",
      "code": 190
   }
}

i use chrome to look this error

-- English is not my native language, sorry for any mistakes.

Add Module to SugarCRM ACL Role List Admin Page when Module doesn't exist?

I am developing a module for SUgarCRM that is not your typical module.

My main module shows up in the SugarCRM Role list of mOdules but my module has several sub-modules which are sections in my main module that have there own custom database table and do not have a module folder or Bean.

Because of this, these sections do not automatically show up on the SugarCRM ACL Role admin page.

I am hoping someone can tell me how to or if it is even possible to add non-real modules as modules in the ACL Role admin page?

I am hoping with code I can manually create some database records and run some code to make it work. Any ideas?

Php include file in different folder that includes another file

I am new in PHP and I've been trying to make a file (index.php) include another file (connect.php) that includes another file (config.php) but they are located in different folders.

This is my directory structure:

 > index.php (in the [root]...)
 > connect.php ([root]/admin/)
 > config.php ([root]/admin/)

This is what I have so far:

index.php

include './admin/connect.php'

connect.php

$directory = getcwd();
chdir(__DIR__);
include "config.php";
chdir($directory);

This is actually working but somehow I'm not loving the idea of changing the working directory.

Is there a better way to achieve my goal?

Login failed in my code after inserting proper login details (i.e username and password), code in php and jquery

I have following code (php and jquery) for Login for Student and Teacher (using same form for both access). In my system the admin can create Student and Teacher. Once created, the details are saved into database. The saved details is suppose to be use for login to their admin panel. But, the problem is , when Student or Teacher wants to login with the login details, provided by the admin (which has already been saved in database table), It display error message : Login Failed, Please check your username and password. (Same details, saved into database table is used for login process). This aching my head. If someone can tell me , if there is some error in my code, will be much appreciated.

login_form.php

<form id="login_form1" class="form-signin" method="post">
<h3 class="form-signin-heading"><i class="icon-lock"></i> Sign in</h3>
<input type="text" class="input-block-level" id="username" name="username" placeholder="Username" required>
<input type="password" class="input-block-level" id="password" name="password" placeholder="Password" required>
<button data-placement="right" title="Click Here to Sign In" id="signin" name="login" class="btn btn-info" type="submit"><i class="icon-signin icon-large"></i> Sign in</button>
<script type="text/javascript">
$(document).ready(function(){
$('#signin').tooltip('show');
$('#signin').tooltip('hide');
});
</script>
</form>
<script>
jQuery(document).ready(function(){
jQuery("#login_form1").submit(function(e){
e.preventDefault();
var formData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "login.php",
data: formData,
success: function(html){
if(html=='true_teacher')
{
$.jGrowl("Loading File Please Wait......", { sticky: true });
$.jGrowl("Welcome to Soch College's E- Learning Management System", { header: 'Access Granted' });
var delay = 1000;
setTimeout(function(){ window.location = 'dasboard_teacher.php'  }, delay);  
}else if (html == 'true'){
$.jGrowl("Welcome to Soch College's E- Learning Management System", { header: 'Access Granted' });
var delay = 1000;
setTimeout(function(){ window.location = 'student_notification.php'  }, delay); 
}else
{
$.jGrowl("Please Check your username and Password", { header: 'Login Failed' });
}
}
});
return false;
});
});
</script>

login.php

<?php include('admin/dbcon.php');
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
//for student login
$query_student = mysql_query("SELECT * FROM student WHERE username='$username' AND password='$password'");
$count_stu = mysql_num_rows($query_student);
$row_stu = mysql_fetch_array($query_student);
//for teacher login
$query_teacher = mysql_query("SELECT * FROM teacher WHERE username='$username' AND password='$password'")or die(mysql_error());
$count_tea = mysql_num_rows($query_teacher);
$row_tea = mysql_fetch_array($query_teacher);
if( $count_stu > 0 ) { 
$_SESSION['id']=$row_student['student_id'];
echo 'true';
}else if( $count_tea > 0 ) { 
$_SESSION['id']=$row_teacher['teacher_id'];
echo 'true_teacher';
}
else{ 
}?>

In Moodle, how to achieve auto continuity between two different activities (Scorm PPT then Quiz) under a topic?

Expectation: A user opens a scorm (Basic001) view all the slides once the activity ends, the process must be automatically redirected to the second activity (Quiz).

I have created a "Category" under which I have created a "Topic" where I have added an activity (Scorm Package created using zenler) and then followed by another activity (Quiz) under the Topic (refer to the image below). I have also set restrictions and activity completion requirements.

The activities(ScormPPT & Quiz) under a topic

I'm using Moodle v2.9

How to achieve this method? If not is there any plugin which helps to achieve this or do this can be achieved by modifying Moodle program?

Symfony2: how can I make a or just

My buttons from the Symfony form component come out as:

<button type="button">Submit</button>

Of course, this doesn't submit the form.

What I'd like is:

<button type="button">Submit</button>
// or
<button>Submit</button>

I'd rather not use an <input type="submit"> so I have more control over the look of the button.

Session_start function not starting properly

I'm trying to use the session_start() function to write a login system using PHP. However, the document i am initializing my session in has the session_start(); on the top of it. I've made sure that nothing is being sent as headers by the document before the session_start(); is processed. However, the error "Cannot send session cache limit - headers already sent.." is still persisting.

<?php session_start(); ?> // The very beginning of my document



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   "http://ift.tt/kkyg93">

<html xmlns="http://ift.tt/lH0Osb">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>WorldOfConquer - WoC</title>
<link rel="SHORTCUT ICON" href="Style/favicon.ico">

<meta name="description" content=" WorldOfConquer - WoC, The best classic 1.0 server.">
<meta name="keywords" content="WorldOfConquer - WoC, The best classic 1.0   server.">

    <meta http-equiv="ROBOTS" content="INDEX,FOLLOW">
    <meta name="ROBOTS" content="INDEX,FOLLOW"> 
    <meta name="REVISIT-AFTER" content="2 days">
    <meta name="Author" content="Laviniu">
    <meta name="LANGUAGE" content="EN">
    <meta name="AUDIENCE" content="ALL">
    <link href="Style/index.css" type="text/css" rel="stylesheet">

How I initialize my session :

$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username;
echo "You have successfuly logged on!";

Gravity Forms - Date Picker - Disallow End Date to be before Start Date

basically I have a large form created on my WordPress site using Gravity Forms. One section of my forms has a bunch of items listed with a 'Start Date' followed by an 'End Date' -- Example:

Item | Start Date | End Date

Item#1 | 05/01/2015 | 05/25/2015

What I am after is making it so I can disallow the 'End Date' from being before the selected 'Start Date'. It would be best if the user was unable to even select the date from the date picker drop down, but if it has to be an error that pops up on submission, that is fine to. I have been researching this for hours and I am just too noob to know exactly what to do. Thanks for any and all help!

PHP : Echo java script code to given url

I wanted to auto-fill a form on a web page. I wrote the javascript code for that, and it is working fine. When I visit the web page manually and run the JS code in the console, it works. But I need this JS code to be run from a server by a PHP code. So I'd like to echo this javascript to the specified URL.

Basically, I want a PHP file on a server (with no browser environment) to run a javascript code on a webpage , using echo . I know how to echo HTML/JS from PHP, but I want it to run on a specific web page. Since there is no browser involved I can't use the JS code window.location.href=url to do this.

Here's the PHP code to echo the JS:

echo "  <html>
    <head>
        <script src="../js/xyz.js"></script>
    </head>
    <body onload="tmp()">
        <script type="text/javascript">
            function tmp(){
                // FIRST VISIT THE URL AND THEN RUN BELOW FUNCTION
                someJSfunction("12345","0019");
            }
        </script>"
    </body>
    </html>
    "
;

Cannot do OOP Callback function for usort

I have read through a few dozen discussion of the use of class members as callback functions but none of the examples address what seems to me to be the obvious OOP design, based upon working with other OOP languages such as C++ and Java.

I have defined a comparison method within the class:

class TestClass {
private $aField; // integer value
function _construct($value)
{
        $this->aField   = $value;
}       // TestClass::_construct

function compare($other)
{
    if ($other instanceof TestClass)
    {           // comparing two instances
    return $this->afield - $other->afield;
    }           // comparing two events
    else
    throw new Exception("parameter is not instance of TestClass");
}       // TestClass::compare
}       // class TestClass

$instances  = array(new TestClass(5),new TestClass(3));
// the following fails because:
// 1. $this is not defined outside a class member
// 2. compare does not take two parameters
usort($instances, array($this, 'compare'));

// the following kluge works around this
function order($this, $that) { return $this->compare($that); }
usort($instances, 'order');

All of the examples I can find on this forum and in the PHP documentation are not complete in that they do not show the context of the call to usort. Now I can get around this by making the comparison function a static function with two parameters and invoke it as a callable by array('TestClass','compare'), but it is not intuitive to define a comparison method as a static function of the class. Based upon over 30 years of personal experience in OOP static functions are in most cases a result of poor class design. In particular static methods defeat polymorphism.

What I am looking for is a sort function like that of Java, which exploits the Comparable interface. I see that there has been some discussion dating back to 2010 about defining a Comparable interface, but that discussion is only in connection with the comparison operators, and makes PHP purists uncomfortable because it overloads operators. However the Java Comparable interface does not overload operators since, with the glaring exception of the String class, Java does not support overloading operators. Implementing the Comparable interface in Java enables you to use the class in SortedMaps and to sort instances within a Collection, but if you wish to compare two objects you must explicitly call the compareTo method. I also see that there is an essentially undocumented compare_objects method which already overrides the default implementation of the comparison operators. In other words despite the purists' objections PHP already permits you to overload the comparison operators for a class. However it is undocumented whether or not the PHP sort function uses compare_objects when it is asked to sort objects.

Limit related records in polymorphic many-to-many realtionship with Laravel

I am using Laravel 5.1 and I need to limit the number of related records I am pulling using a polymorphic many-to-many relationship.

What I would like to do is get a list of categories by parent_id. For each category then I'd like to only pull four posts.

I have have this working with the code below, but it results in a bunch of extra queries. I'd like to just hit the database once if possible. I'd like to use the Laravel/Eloquent framework if at all possible, but am open to whatever works at this point.

@foreach ($categories as $category)
  @if ($category->posts->count() > 0)
    <h2>{{ $category->name }}</h2>
    <a href="/style/{{ $category->slug }}">See more</a>

    {-- This part is the wonky part --}

    @foreach ($category->posts()->take(4)->get() as $post)

      {{ $post->body }}

    @endforeach

  @endif
@endforeach

PostsController

public function index(Category $category)
{
  $categories = $category->with('posts')
      ->whereParentId(2)
      ->get();

  return view('posts.index')->with(compact('categories'));
}

Database

posts
    id - integer
    body - string

categories
    id - integer
    name - string
    parent_id - integer

categorizables
    category_id - integer
    categorizable_id - integer
    categorizable_type - string

Post Model

<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
    public function categories()
    {
        return $this->morphToMany('App\Category', 'categorizable');
    }

Category Model

<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
    public function category()
    {
        return $this->belongsTo('App\Category', 'parent_id');
    }
    public function subcategories()
    {
        return $this->hasMany('App\Category', 'parent_id')->orderBy('order', 'asc');
    }
    public function posts()
    {
        return $this->morphedByMany('App\Post', 'categorizable');
    }

I have seen a number of links to this on the web, but nothing that has actually worked for me.

I have tried this solution without any luck.

$categories = $category->with('posts')
->whereParentId(2)
->posts()
->take(4)
->get();

I have looked into this solution by Jarek at SoftOnTheSofa, but it is for a hasMany relationship and to be honest is a bit beyond my sql skill for me to adapt it for my needs.

Using parseincludes in Laravel5 Fractal

Struggling using parseIncludes in http://ift.tt/1h7EiPY.

I have two tables, Property and Weeks. Each property has many weeks. Using Fractal I can return my property item with a collection of weeks. What I want to do is use parseIncludes, so that the return of weeks is optional.

PropertyTransformer.php

<?php
namespace App\Transformer;

use App\Models\Property;
use League\Fractal\TransformerAbstract;


class PropertyTransformer extends TransformerAbstract
{

    protected $availableIncludes = [
        'week'
    ];

    public function transform(Property $property)
    {
        return [
            'id'                => (int) $property['PropertyID'],
            'PropertyName'      => $property['PropertyName'],
            'ExactBeds'         => (int) $property['ExactBeds'],
            'weeks'             => $property->week
        ];
    }

    /**
     * Include Week
     *
     * @return League\Fractal\ItemResource
     */
    public function includeWeek( Property $property )
    {
        $week = $property->week;

        return $this->item($week, new WeekTransformer);
    }
}

WeekTransformer.php

<?php
namespace App\Transformer;

use App\Models\Week;
use League\Fractal;

class WeekTransformer extends Fractal\TransformerAbstract
{


    public function transform(Week $week)
    {
        return [
            'Week'          => $week['week'],
            'Available'     => $week['available'],
            'Price'         => (int) $week['price'],

        ];
    }

}

My PropertyController.php

<?php namespace App\Http\Controllers\Api\v1;

use App\Http\Requests;
use App\Models\Week;
use Illuminate\Support\Facades\Response;

use App\Models\Property;

use League\Fractal;
use League\Fractal\Manager;
use League\Fractal\Resource\Collection as Collection;
use League\Fractal\Resource\Item as Item;

use App\Transformer\PropertyTransformer;


class PropertyController extends \App\Http\Controllers\Controller {

public function show($id)
{
    $property = Property::with('bedroom')->with('week')->find($id);

    $fractal = new Fractal\Manager();

    if (isset($_GET['include'])) {
        $fractal->parseIncludes($_GET['include']);
    }

    $resource = new Fractal\Resource\Item($property, new PropertyTransformer);
    //$resource = new Fractal\Resource\Collection($properies, new PropertyTransformer);

    return $fractal->createData( $resource )->parseIncludes('weeks')->toJson();

}

I get the following error on the parseIncludes:-

Method 'parseIncludes' not found in class \League\Fractal\Scope

I'm following the guide here on transformers - http://ift.tt/1GEuNV5

I think I am going wrong somewhere here where it says:-

These includes will be available but can never be requested unless the Manager::parseIncludes() method is called:

<?php
use League\Fractal;

$fractal = new Fractal\Manager();

if (isset($_GET['include'])) {
    $fractal->parseIncludes($_GET['include']);
}

If I remove the parseIncludes, I don't get an error, I also get my property data with my collection of weeks, but ?include=week doesn't work to optionally get it.