Affichage des articles dont le libellé est Active questions tagged php - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged php - Stack Overflow. Afficher tous les articles

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.