samedi 25 avril 2015

pear BBCodeParser2 couldn't parse WysiBB links


i used pear BBCodeParser2 with Wysibb editor,it works good for most bbcodes like bold,italic,images....etc

the problem only in links,it can't parse urls in the topic,and when i look at db table, i found the url bbcode unchanged.... i checked all links and files included,and the problem still the same:

php:

       $config = parse_ini_file('HTML/BBCodeParser2.ini',true);
        $options = $config['HTML_BBCodeParser2'];
        $parser = new HTML_BBCodeParser2($options);
        $parser->setText($this->db->real_escape_string($_POST['t_body'])); 
        $parser->parse(); 
        $t_body= $parser->getParsed();

img from db: enter image description here


Is it possible use a custom 'select' template for bunlded products in Magento?


I'm creating a specific bundled product, which needs a few custom changes to the select and checkbox templates.

Supposedly I could just add a custom update layout in the product, but nothing I do seems to be able to target a new select.phtml template.

<reference name="product.info.options.wrapper">
 <!-- THIS WORKS -->
 <block type="bundle/catalog_product_view_type_bundle" name="product.info.bundle.options" as="type_bundle_options" template="bundle/catalog/product/view/type/bundle/*custom*.phtml">
  <action method="addRenderer">
    <type>select</type>
    <block>bundle/catalog_product_view_type_bundle_option_select</block>  
    <!-- THIS DOESN'T WORK -->
    <template>*custom_folder*/bundle/catalog/product/view/type/bundle/option/*custom*-select.phtml</template>
  </action>
 </block>
 <action method="insert"><block>product.info.bundle.options</block></action>
</reference>

Looking at the catalog.xml, it looks like the checkboxes, and selects, etc ... point to a template, but not in bundle.xml.

And, I can of course overwrite the default templates in theme/template/bundle/catalog/...etc../option/select.phtml ... but I really need a specific template for one product ... not all of them.

I'm hoping somebody has some insight into this? Maybe I'm going about this the wrong way?

Thanks!


php mysql fetch two table


i have two table from mysql.

1, photo (url_link)

2, video(url_link)

i wanna fetch only 1 table (video url) if both table aren't empty.. Is there anyways? am using code below:

<--photo -->
    <?php       
$query_img = mysql_query("SELECT `url` FROM `photos_news` WHERE title='{$thumn_content['titles']}' LIMIT 0,1");
while($img = mysql_fetch_array($query_img)){ ?>
<img src="<?php echo $img['url'];?>" class="img-responsive img-rounded"/>
<?php }?>


<!-- vdo -->
<?php
$query_vdo = mysql_query("SELECT `url` FROM `video_news` WHERE title='{$thumn_content['titles']}' LIMIT 0,1");
while($vdo = mysql_fetch_array($query_vdo)){ ?>
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src="<?php echo $vdo['url']?>?modestbranding=1&showinfo=0&fs=0"></iframe>
</div>

<?php }?>

thank you sir,


Send data sensitive data to javascript


I have this code:

<input type="button" value="Delete Group" class="followbt" name="delete" onclick="deleteGroupDialog(' . $group_row['ngroup'] . ');">

The field 'ngroup' is the group number that i want to delete, and i am passing it to a javascript function that opens an jquery dialog window in order to ask if the user is certain of what is doing, the problem is that anyone can go on the browser and edit that number and go delete any group (that belongs to him).

I have already made a search about this but i didn't find anything, is there a way to pass the argument more securely?

PS: When i show the dialog window i don't want to reload the page a make a server request.


Compare data from two tables and check the same data


Hello I have two tables in my database.

The first one is table disease which look like the above...

enter image description here

And the second is table patient which look like this ...

enter image description here

And I have an edit page where I want to give the user the ability to update his/her diseases. An example is the below..

enter image description here

What I want to do is to check the disease column from the table patient with the column name from the table disease and check that if a data from the table patient is the same with the data from the table disease then check from the checkboxes the same disease.

I tried to find a way to do it by I couldnt Here is my code...

<?php
$sql = "SELECT name FROM disease UNION SELECT disease FROM patient WHERE username='$username'";
$query_resource = mysql_query($sql);

  while( $name = mysql_fetch_assoc($query_resource) ):
?>
    <span><?php echo $name['name']; ?></span>
    <input type="checkbox" name="disease[]" value="<?php echo $name['name']; ?>" /><br />


<?php endwhile; ?>

The way I store the diseases in my database is this...

$disease = implode(",",$_POST["disease"]);

Because a user might have many diseases


need help how do i get response from php just like this?


It's my wishes { "worldpopulation": [ { "rank":1,"country":"China", "population":"1,354,040,000", "flag":"http://ift.tt/1k4xoyg" },

     {
     "rank":2,"country":"India",
     "population":"1,210,193,422",
     "flag":"http://ift.tt/1kKjA0k"
     }, 

     {
     "rank":3,"country":"United States",
     "population":"315,761,000",
     "flag":"http://www.androidbegin.com/tutorial/flag/unitedstates.png"
     }, 

     {
     "rank":4,"country":"Indonesia",
     "population":"237,641,326",
     "flag":"http://ift.tt/1gnVIs0"
     }, 

     {
     "rank":5,"country":"Brazil",
     "population":"193,946,886",
     "flag":"http://ift.tt/1kKjxlh"
     }, 

     {
     "rank":6,"country":"Pakistan",
     "population":"182,912,000",
     "flag":"http://ift.tt/1kKjxlj"
     }, 

     {
     "rank":7,"country":"Nigeria",
     "population":"170,901,000",
     "flag":"http://ift.tt/1gnVIIk"
     }, 

     {
     "rank":8,"country":"Bangladesh",
     "population":"152,518,015",
     "flag":"http://ift.tt/1kKjA0v"
     }, 

     {
     "rank":9,"country":"Russia",
     "population":"143,369,806",
     "flag":"http://ift.tt/1o2k91J"
     }, 

     {
     "rank":10,"country":"Japan",
     "population":"127,360,000",
     "flag":"http://ift.tt/1kKjxBB"
     } 
] 

} http://ift.tt/LA6KRN


Yii2 Getting user input from a form


I am making a Search query for a user to find a property within a price range. I do not know how Yii2 gets the user input. Here is my code for the form:

  <?php $form = ActiveForm::begin([
    'action' => ['index'],
    'method' => 'get',
]); ?>

<?= $form->field($model, 'address') ?>

<?= $form->field($model, 'minprice')->dropDownList(['£100' => '£100','£200' => '£200','£300' => '£300']) ?>

 <?= $form->field($model, 'maxprice')->dropDownList(['£100' => '£100','£200' => '£200','£300' => '£300']) ?>

<div class="form-group">
    <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
    <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>

<?php ActiveForm::end(); ?>    

And here is my model:

class PropertiesSearch extends Properties
{

 public $minprice;
 public $maxprice;

public function search($params)
{
    $query = Properties::find();

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

    $this->load($params);

    if (!$this->validate()) {
        return $dataProvider;
    }

    $query->andFilterWhere([
        'id' => $this->id,
        'NoofBedrooms' => $this->NoofBedrooms,
        'type_id' => $this->type_id,
    ]);

    $query->andFilterWhere(['like', 'address', $this->address])
        ->andFilterWhere(['like', 'city', $this->city])
        ->andFilterWhere(['like', 'Postcode', $this->Postcode])
        ->andFilterWhere(['>=', 'price', $this->minprice])
        ->andFilterWhere(['<=', 'price', $this->maxprice])
        ->andFilterWhere(['=', 'option', $this->option])
        ->andFilterWhere(['like', 'description', $this->description]);
   return $dataProvider;
}
}

I added the public $minprice and $maxprice as I was receiving this error:

Getting unknown property: app\models\PropertiesSearch::minprice

However, the query doesn't work, in my URL it shows the user input but the query isn't following through. I would have thought that ($model, 'minprice') gives the field a name and that $this-minprice gets that value. It works when I make public $minprice = '$100' and $maxprice = '$300', so they must be overwriting the users input, but if I remove them I get the previous error again, what am I doing wrong?


Php code to import excel file to database


I want to import Excel data to my database using PHPExcel. Below is my code.

When I upload the excel file and submit the form, I can echo out the table but no data is being stored in the database, Can anyone please help me with this.

<?php

# Database Connection
$dbc = mysqli_connect('localhost', 'root', 'ron143', 'tcc') OR die('Error: '.mysqli_connect_error());

/** Include path **/
#set_include_path(get_include_path() . PATH_SEPARATOR . 'PHPExcel/Classes/');

/** PHPExcel_IOFactory */
include 'PHPExcel/Classes/PHPExcel.php';

/** PHPExcel_IOFactory */
include 'PHPExcel/Classes/PHPExcel/IOFactory.php';

# Upload the file to server
$file = $_FILES["file"]["name"];
$target_dir = "../../temp/";
$target_file = $target_dir . basename($file);
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
$xls_url = "$target_dir$file";

$inputFileName = $xls_url;
$inputFileType = $_POST['file_type'];
$sheetname = '0'; /** input the worksheet number to read. 0 for first and 1 for second worksheet */

/**  Create a new Reader of the type defined in $inputFileType  **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);

/**  Advise the Reader that we only want to load cell data and not its formating or any formula set on it **/
$objReader->setReadDataOnly(true);

/**  Load $inputFileName to a PHPExcel Object  **/
$objPHPExcel = $objReader->load($inputFileName);

//  Get worksheet dimensions
$objWorksheet = $objPHPExcel->getSheet($sheetname);
$highestRow = $objWorksheet->getHighestRow(); // e.g. 10
$highestColumn = $objWorksheet->getHighestColumn(); // e.g 'F'

$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); // e.g. 5

echo '<table>' . "\n";
for ($row = 2; $row <= $highestRow; ++$row) {
    echo '<tr>' . "\n";

for ($col = 0; $col <= $highestColumnIndex; ++$col) {

    echo '<td>' . $objWorksheet->getCellByColumnAndRow($col, $row)->getValue() . '</td>' . "\n";

  }
  echo '</tr>' . "\n";
}
  echo '</tr>' . "\n";

#$q = "INSERT INTO products (product_name, product_code, category1, category1_id, category2, category2_id, stylename, grams, thickness, width, length, color_ground, color_border, material, backing, reed, weave, ply, pile, care, precaution, use, tag, image, link) VALUES(`".$val[0]."`, `".$val[1]."`, `".$val[2]."`, `".$val[3]."`, `".$val[4]."`, `".$val[5]."`, `".$val[6]."`, `".$val[7]."`, `".$val[8]."`, `".$val[9]."`, `".$val[10]."`, `".$val[11]."`, `".$val[12]."`, `".$val[13]."`, `".$val[14]."`, `".$val[15]."`, `".$val[16]."`, `".$val[17]."`, `".$val[18]."`, `".$val[19]."`, `".$val[20]."`, `".$val[21]."`, `".$val[22]."`, `".$val[23]."`, `".$val[24]."`)";
#$r = mysqli_query($dbc, $q);

if($q!='') $q.=',';
$q.='(\''.mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colproduct_name, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colproduct_code, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colcategory1, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colcategory1_id, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colcategory2, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colcategory2_id, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colstylename, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colgrams, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colthickness, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colwidth, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($collength, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colcolor_ground, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colcolor_border, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colmaterial, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colbacking, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colreed, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colweave, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colply, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colpile, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colcare, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colprecaution, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($coluse, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($coltag, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($colimage, $row)->getValue()).'\',\''.
        mysqli_real_escape_string($dbc, $objWorksheet->getCellByColumnAndRow($collink, $row)->getValue()).'\')';

if($q!='') {
    $q='INSERT INTO products (product_name, product_code, category1, category1_id, category2, category2_id, stylename, grams, thickness, width, length, color_ground, color_border, material, backing, reed, weave, ply, pile, care, precaution, use, tag, image, link) VALUES '.$q;
    $r=mysqli_query($dbc, $q);
    }


?>


PHP - How to get images from Instagram for more then 1 tag


Guys i'm working on PHP script which is getting all images for a specific tag in Instagram.

Here is my code:

<?PHP
 function callInstagram($url)
    {
    $ch = curl_init();
    curl_setopt_array($ch, array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => 2
    ));

    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
    }

    $tag = "sweden";
    $client_id = "1e0f576fbdb44e299924a93cace24507";
    $Next_URL = $_GET["nexturl"];
    if($Next_URL == ""){
    $url = 'http://ift.tt/SUv5zZ'.$tag.'/media/recent?client_id='.$client_id.'&count=24';
    } else {
    $url =  $Next_URL;
    }
    $inst_stream = callInstagram($url);
    $results = json_decode($inst_stream, true);
    $maxid = $results['pagination']['next_max_id'];
    $nexturl = $results['pagination']['next_url'];
    //Now parse through the $results array to display your results... 
    ?>
    <div class="holder" style="display:block;margin-left:70px;">
    <?PHP
    foreach($results['data'] as $item){
        $image_link = $item['images']['thumbnail']['url'];
        $big_image = $item['images']['standard_resolution']['url'];
    echo "Image: $image_link";
    }

This script is getting information about only one tag - sweden.

How i can make this code get all the information about more then one tag, for example let's say for another two tags - england and germany ?

Thanks in advance!


header redirect with include file


I've looked around on here and couldn't locate any solution for my little problem.

I currently have this following IF statment

if($page==1) {
    $sql = "UPDATE page SET page='1' WHERE id=1";
          INCLUDE 'month.php';
          header("Refresh: 10; url=http://XXXXX.co.uk/?p=2");           
    }

Which currently updates a database according to what page it is on and then includes the current month calendar file and I hoped I could redirect it to page number 2 which is very much similar but loads another calendar and the SQL adds +2 to the database.

In essence it's just a loop I've made and it just reads a SQL database to see what page it needs to load next< I know there's better ways to create a loop (just to scroll through 3 PHP pages) but I'm not that great at PHP..

So i'm just wondering really, could anybody help me to have that include statement along with the header refresh?

Like said the purpose is so that the pages rolls a loop, I've managed to get it all to work with an iframe (instead of the header) but it takes a few seconds longer for the frame window to load.


How can i use PHP break condition with yii2?


How can i use PHP break condition with yii2? Please help me.

echo implode(PHP_EOL, str_split($string, $break));


Merge Dependency Injection Parameters by key


I am new to Symfony. I need to create likely 2 or 3 separate bundles. Each bundle extends DependencyInjection providing an array typed parameter with key:navigations but with different values.

nav.xml on bundle page:

<parameters>
    <parameter key="navigations" type="collection">
        <parameter key="page" type="collection">
            <parameter key="label">Page</parameter>
            <parameter key="url">%admin%/page</parameter>
        </parameter>
    </parameter>
</parameters>

nav.xml on bundle blog:

<parameters>
    <parameter key="navigations" type="collection">
        <parameter key="blog" type="collection">
            <parameter key="label">Blog</parameter>
            <parameter key="url">page</parameter>
        </parameter>
    </parameter>
</parameters>

when I do:

$nav = $this->container->getParameter('navigations');
dump($nav);

I only get last defined parameters. How should I merge them ?


Posting to a Facebook page is showing on the "POSTS TO PAGE" panel


I got the code below from another website which seems to be working fine. The only problem is that posts appear on the "POSTS TO PAGE" section of the Facebook page instead of appearing on the page timeline directly.

Any idea why?

Also, the code works when I use the access token, not the app access token. When using app access token, I get an error message saying: "(#200) The user hasn't authorized the application to perform this action"

<?php
// require Facebook PHP SDK
// see: http://ift.tt/1fCaYUH
require_once("/YOUR_PATH_TO/facebook_php_sdk/facebook.php");

// initialize Facebook class using your own Facebook App credentials
// see: http://ift.tt/1n65vdg
$config = array();
$config['appId'] = 'YOUR_APP_ID';
$config['secret'] = 'YOUR_APP_SECRET';
$config['fileUpload'] = false; // optional

$fb = new Facebook($config);

// define your POST parameters (replace with your own values)
$params = array(
  "access_token" => "YOUR_ACCESS_TOKEN", // see: http://ift.tt/L1kwN8
  "message" => "Here is a blog post about auto posting on Facebook using PHP #php #facebook",
  "link" => "http://ift.tt/1hBHVQg",
  "picture" => "http://ift.tt/1hBHVQj",
  "name" => "How to Auto Post on Facebook with PHP",
  "caption" => "www.pontikis.net",
  "description" => "Automatically post on Facebook with PHP using Facebook PHP SDK. How to create a Facebook app. Obtain and extend Facebook access tokens. Cron automation."
);

// post to Facebook
// see: http://ift.tt/1p38EHk
try {
  $ret = $fb->api('/YOUR_FACEBOOK_ID/feed', 'POST', $params);
  echo 'Successfully posted to Facebook';
} catch(Exception $e) {
  echo $e->getMessage();
}
?>


Post and Get value by jquery ajax


How can I add my values owdid and visited id after clicking below link by ajax?

<a href="index.php" onclick="insertvisit(<?php echo $interestid;?>)">member1</a>

Below is my insertvisit function. I have defined owdid and interestid

function insertvisit(visitedid) {
  $.ajax({
       type: "POST",
       url: 'insertvisit.php',
       data:{'field1' : owdid, 'field2' : visitedid},
       success:function(html) {
       }
  });
}

and below is insertvisit.php

global $pdo;
$ownid = $_GET['field1'];
$interestid =$_GET['field2'];

$query = $pdo->prepare("UPDATE tablem SET field1= ? WHERE field2= ?");
$query -> bindValue(1, $ownid);
$query -> bindValue(2, $interestid);
$query -> execute();

Please help thanks.


How to get a table class which is being displayed through ajax


I have a main page which has a div with the id of displayTable. In that a table GETs loaded through AJAX from another php page.

The table is laid out like this:

<div class="table-responsive">
      <table class="table table-bordered table table-condensed">
        <thead>
          <tr>
            <td>Name</td>
            <td>Blah Blah</td>
            <td>Blah Blah</td>
            <td>Blah Blah</td>
            <td>Total</td>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>Dilbert</td>
            <td>Rob</td>
            <td>Blah</td>
            <td>Blah</td>
            <td>Blah Blah Blah</td>
          </tr>
        </tbody>
      </table>
    </div>

I am attempting at using this jquery code to make the first tr fixed. So, in the example above, Dilbert and Name would be fixed and the rest is scrollable. However, I cannot seem to get to the table and it doesn't seem to affect it or do anything.

    var $table = $('#displayTable .table');
    var $fixedColumn = $table.clone().insertBefore($table).addClass('my-sticky-col');

    $fixedColumn.find('th:not(:first-child),td:not(:first-child)').remove();

    $fixedColumn.find('tr').each(function (i, elem) {
    $(this).height($table.find('tr:eq(' + i + ')').height());
    });


Relative path to sub-directory in PHP and Apache's htaccess file


I am working on my own PHP Framework. I am currently developing it on localhost and everything related to project is in subfolder called RuddyPhpFramework, so the path look like this:

localhost/RuddyPhpFramework/

In that folder, I do have index.php, the init point of whole Framework. I am currently working on my own router, but I have a two problems. First, in Apache's htaccess file a have this:

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) RuddyPhpFramework/index.php [L]

So whenever someone acces a page like this:

localhost/RuddyPhpFramework/something/smtelse/

The index.php will init the application and echo a path for me, which is:

[path] => /RuddyPhpFramework/something/smtelse/

But that is not excatly what I want. What I want is to get a relative path to subfolder (I don't know if I am explaining this correctly), for example:

[path] => /something/smtelse/

And another problem is that I want to setup the htacces so the last line would look something like this:

RewriteRule (.*) index.php [L]

So it will go for the index.php in the folder where is the htaccess file (/RuddyPhpFramework/index.php) and not /index.php, without specifying the foler, because if someone else will be using the framework, he might have it in a folder with different name.


Codeigniter Form Validation Callback Function


I'm trying to create a form validation callback function but I'm having a little trouble getting my head around it.

What I am trying to do is create a contact form where with a join the mailing list option. If the option to join the mailing list is checked I want the name and email of the person to be added to the mailing list database. This part works perfectly however I also want the function to check the database to ensure that the email address being added is unique and this is the bit that I just can't get my head around.

Controller:

public function contact()
{
    $this->load->helper('form');
    $this->load->library('form_validation');

    $this->form_validation->set_rules('name', 'your name', 'required', array('required'=>"<p class='required'>Please provide %s</p><br>"));
    $this->form_validation->set_rules('email', 'your email address', 'required', array('required'=>"<p class='required'>Please provide %s</p><br>"));

    if($this->form_validation->run() == FALSE)
    {
        $this->load->view('templates/headder');
        $this->load->view('contact');
        $this->load->view('templates/footer');
    }
    else
    {
        $this->load->library('email');

        $name = $this->input->post('name');
        $email = $this->input->post('email');
        $phone = $this->input->post('phone');
        $message = $this->input->post('message');
        $list = $this->input->post('mailing_list');

        $email_message = "Name: $name<br>Email: $email<br>Phone: $phone<br>Message:<br>$message";

        $this->email->initialize();
        $this->email->from($email, $name);
        $this->email->to('myaddress@mydomain.co.uk');
        $this->email->subject('New Query');
        $this->email->message($email_message);
        $this->email->send();

        if($this->email->send()){
        $this->load->view('send_error');
        }
        else
        {
            if($list == 'no')
            {
            $this->load->view('sent');
            }
            else
            {
                $this->form_validation->set_rules('email', 'Email', 'is_unique[mail_list, email]');


                if($this->form_validation->run() == FALSE)
                {

                $this->load->model('mailing_listm');
                $this->mailing_listm->add_name();
                $this->load->view('sent'); 
                }
                else
                {
                $this->load->view('contact');
                }

            }
        }
    }
}

Error Message:

A Database Error Occurred

Error Number: 1064

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 ' email 'myaddress@mydomain.co.uk' LIMIT 1' at line 3

SELECT * FROM `mail_list`, `email` WHERE mail_list, email 'myaddress@mydomain.co.uk' LIMIT 1

Filename: libraries/Form_validation.php

Line Number: 1134

Hopefully someone will be able to let me know what daft thing I've done this time.

Also, This function is turning into a bit of a monster, it's the most complicated thing I've every tried to write. Is there any way that I can split it out so that it is made up of several smaller functions instead of one gargantuan one?

Thanks,

EDIT I have updated my code in line with the comment below about using is_unique however now I am receiving an error message.


Using Laravel Eloquents HasManyThrough relation with multiple relations through polymorphism


I got a rather simple application where a user can report other users comments and recipes. I use a polymorphic relation to store the reports. This all works fine, however I am now trying to get the offenses that a user has made.

Getting his own reports is not a problem, this can be done simply using user->reports() but I would very much like to get the reports in which other people has reported said user. I can get this to work using either the hasManyThrough relation or queries BUT only on one model at a time.

ex.

public function offenses() {
    return $this->hasManyThrough('Recipe', 'Reports');
}

Or

->with('user.recipe.reports')

The problem is that my reportable object is not just recipes, it could be comments, images etc. So instead of having to use multiple functions, the logical way would be to somehow parse the relationship of hasManyThrough multiple parameters.

Theoretically looking like this:

public function offenses() {
    return $this->hasManyThrough(['Recipe', 'RecipeComments'], 'Reports');
}

Is this in any way possible? With some undocumented syntax? If not is there any clever work-arounds/hacks?

Possible solution?

Would an acceptable solution be to add another column on my report table and simply add offender_id like this?

ID | User_id | Offender_id | Reportable_type | Reportable_id

This would mean I could simply make a relation on my user model that connects offenses through that column. But would this be considered redundant? Since I already have the offender through the reportable model?


Models

Polymorphic Model

class Report extends Model {
    public function reportable() {
        return $this->morphTo();
    }

    public function User() {
        return $this->belongsTo('App\User');
    }
}

Recipe Model

class Recipe extends Model {
    public function user() {
        return $this->belongsTo('App\User');
    }

    public function reports() {
        return $this->morphMany('App\Report', 'reportable');
    }
}

Comment Model

class RecipeComment extends Model {   
    public function user() {
        return $this->belongsTo('App\User');
    }

    public function reports() {
        return $this->morphMany('App\Report', 'reportable');
    }
}


I have the same error message when i put any error in the file


when I submit this form i have the same error message all the time . even if i put right or wrong password or don't put password or i write the name of the data base wrong . all of this wrongs i have the same error message : Please enter a username and password . so what is the problem . and i am sure about my fields on data base .

    <?

    session_start();
    $username = $_POST['username'];
    $password = $_POST['password'];


    if ($username && $password)
    {

        $connect = mysql_connect("localhsost","root","adminffpass") or die("Couldent connet to database ");
        mysql_select_db("login") or die("No data base found ");

        $query = mysql_query("SELECT * FROM users WHERE username='$username'");

        $numrows = mysql_num_rows($query);

        if ($numrows !=0)
        {

            while ($row= mysql_fetch_array($query)) 
            {

                $dbusername = $row['username'];
                $dbpassword = $row['password'];

            }

            if ($username == $dbusername && $password==$dbpassword)
            {
                echo "Login successul .<a href='memeberarea.php'>Click to enter member area</a>";
                $_SESSION['username'] = $dbusername;
            }
            else
                echo "incorrect  password  ";

        }
        else
           die ("That user name dosent exist");

   }
   else
     die ("Please enter a username and password");


    ?>


convert csv file to csv UTF8 by php


I got .csv file from client but when I read it with PHP, it show some text can't read. I try to upload and open with google sheet and then export .csv again with google. it work perfect when I read it with php.

Are there any way to convert .csv to .csv UTF8 without using google ? because client will send .csv to server everyday automatic. and then my php script will read and import .csv data into database. please help

Thanks


IFRAME Outlook Calendar (Office365)


I'm building a script which jumps around to index.php?p=1 - 3 which loads the calendars in what I hoped would be an iframe however Ive just found out that they are blocked.

Is there any alternative?


404 Error on ZF2 skeleton application on all tutorials


I am trying to learn Zend Framework 2. I have followed both the tutorial found in the ZF2 user guide at http://ift.tt/1zNXHOx and the book Learn ZF2: Learning by example. I've also tried a few other tutorials. I feel like I have wasted so much time and money trying to learn Zend Framework, and can't even get started because I can't even get the welcome screen to load. I have tried so many different things and can not even get the Framework to work. I can get the files to download with Git and Composer (just like in the tutorials). I go to pull up the welcome page and I get the same thing on every tutorial. The header and footer load, but the page is just a 404 error. I wish I could load a picture, but I'm new to Stack Overflow and don't have enough reputation points to do so. You can see an image of what I am getting here: http://ift.tt/1Gt0CTe I am using the PHP server, included with PHP5, and have made no changes at all to any of the Zend Framework file.


Why is my ZF2 Segment child route being ignored?


I have the following routing config in my project:

'router' => array(
    'routes' => array(
        'home' => array(
            'type' => 'Zend\Mvc\Router\Http\Literal',
            'options' => array(
                'route' => '/',
                'defaults' => array(
                    '__NAMESPACE__' => 'MyApp\Controller',
                    'controller' => 'Default',
                    'action' => 'default',
                ),
            ),
            'may_terminate' => true,
            'child_routes' => array(
                'api' => array(
                    'type' => 'Zend\Mvc\Router\Http\Segment',
                    'options' => array(
                        'route' => 'api/:action[/:id]',
                        'defaults' => array(
                            '__NAMESPACE__' => 'MyApp\Controller',
                            'controller' => 'Api',
                            'action' => 'index',
                        ),
                    ),
                    'may_terminate' => true,
                ),
                'default' => array(
                    'type' => 'Zend\Mvc\Router\Http\Segment',
                    'options' => array(
                        'route' => '[:id]',
                        'defaults' => array(
                            '__NAMESPACE__' => 'MyApp\Controller',
                            'controller' => 'Default',
                            'action' => 'default',
                        ),
                    ),
                    'may_terminate' => true,
                ),
            ),
        ),
    ),
),

When I make a call to http://localhost/api/foo/bar I get the response from the DefaultController. I have stripped my application until this is the only route (removed home/default, and made it an only route for the application) but it is ignored.

The desired outcome is that calls to /api... go to the Api controller, but all other calls go to the Default Controller.

There are no errors being thrown as far as I can see (looking at apache2 logs)

Any suggestions as to what might be wrong?


Getting Instagram subscription JSON data from post in PHP


This whole process of subscriptions for the Instagram API seems to be less than straight forward.

I have some code set up to receive the post data sent when Instagram hits me with a notification of a post from one of my subscriptions. However when I try to view the data the raw JSON it posts I can't get at it. If I print_r or var_dump I just get the number 1.

See my code for accessing the data:

    // Catches realtime updates from Instagram
if ($_SERVER['REQUEST_METHOD']==='POST') {
     // Retrieves the POST data from Instagram
    $update = file_get_contents('php://input');
    $data = json_decode($update);

    var_dump($data); //Outputs 1
    print_r($data[0]); //Outputs 1

}   

How can I get at the JSON as an array?

This is what the JSON should look like:

[
    {
        "subscription_id": "1",
        "object": "user",
        "object_id": "1234",
        "changed_aspect": "media",
        "time": 1297286541
    },
    {
        "subscription_id": "2",
        "object": "tag",
        "object_id": "nofilter",
        "changed_aspect": "media",
        "time": 1297286541
    },
    ...
]

Thanks for any help.


Create 3rd level foreach and loop the arrays and save it to data?


I am using opencart 1.5.6.4 . I've create a module.

<?php $module_row = 1; ?>
<?php foreach ($modules as $module) { ?>

<?php $element = 1; ?>
<?php if(isset($module['tabs'])) { foreach($module['tabs'] as $tab) { ?>

<?php $elements = 1; ?>
<?php if(isset($tab['styles'])) { foreach($tab['styles'] as $style) {  ?>

<?php $elements++; } }  ?>

<?php $element++; }  } ?>

<?php $module_row++; } ?>

But 3rd level not working and saved.

<?php $elements = 1; ?>
    <?php if(isset($tab['styles'])) { foreach($tab['styles'] as $style) {  ?>

When i changed it to

<?php $elements = 1; ?>
        <?php foreach($tab as $style) { if ($style > 0) {  ?>

Not working properly.

What is the correct solution?


PHP & regex to extract two separate parts of a string as ONE recombined variable


I have a PHP string consisting of HTML code as follows:

$string =
'<ul>
<li>
<a href="/nalcrom">Nalcrom</a>
        (Sodium Cromoglicate)
</li>
<li>
<a href="/alimemazine">Alimemazine</a>
</li>
<li>
<a href="/xolair">Xolair</a>
        (Omalizumab)
</li>
</ul>';

using

preg_match_all($regex,$string,$matches, PREG_PATTERN_ORDER);

for ($i = 0; $i < count($matches[0]); ++$i)
{ echo $i . "    " . $matches[0][$i]. "<br>"; }

if I use

$regex = "^(?<=>).*?(?=(\Q</a>\E))^";

I get

1 Nalcrom

2 Alimemazine

3 Xolair

whereas if I use

$regex = "^\(.*?\)^";

I get

1 (Sodium Cromoglicate)

2 (Omalizumab)

Trying

$regex = "^(?<=>).*?(?=(\Q</a>\E))(\(.*?\))^";

and variations upon it I get nothing but blank, whereas what I need is:

1 Nalcrom (Sodium Cromoglicate)

2 Alimemazine

3 Xolair (Omalizumab)

Any ideas on how I can do this? thnx


Users in my social network can't register and login


I made a simple social network system, with register and login function, but whem the user register and try to login, he give this message:

Fatal error: Call to a member function rowcount() on a non-object in home/login.php on line 7

There is some problem in my login.php code?:

<?php
include('dbcon.php');
$username = $_POST['username'];
$password = $_POST['password'];

$query = $conn->query("select * from database where username = '$username' and password = '$password'");
$count = $query->rowcount();
$row = $query->fetch();
if ($count > 0){
session_start();
$_SESSION['id'] = $row['member_id'];
 header('location:home.php'); 
}else{
 header('location:index.php'); 
}
?>

SQL for showing row data in columns


Here is my sql (in mysql table)

select * from(SELECT sample_register.usin,    
                     DATE_FORMAT(sample_register.doc,'%d-%m-%Y') as doc1,    
                     sample_register.location,    
                     sample_register.description,    
                     sample_register.type,    
                     sample_allocation.gamma,    
                     gamma_results.act,    
                     gamma_results.act_sd,    
                     gamma_results.mdl,    
                     gamma_results.bdl,    
                     DATE_FORMAT(count_dt,'%d-%m-%Y') as count_dt    
               FROM sample_register    
               LEFT JOIN sample_allocation    
               ON sample_register.usin=sample_allocation.usin    
               LEFT JOIN gamma_results    
               ON gamma_results.usin = sample_register.usin    
               AND gamma_results.istp='Cs137'    
               WHERE mid(sample_register.usin,3,1)='F'    
               AND sample_register.doc BETWEEN '2015-01-01'    
                                       AND '2015-03-31'    
                                       AND sample_register.category='ter'    
                                       AND sample_allocation.gamma='Y'    
               ORDER BY mid(sample_register.usin,3,1),    
                        sample_register.doc,    
                        sample_register.usin) AS a    
               LEFT JOIN (SELECT sample_register.usin,    
                                 gamma_results.act,    
                                 gamma_results.act_sd,    
                                 gamma_results.mdl,    
                                 gamma_results.bdl    
                          FROM sample_register    
                          LEFT JOIN gamma_results    
                          ON gamma_results.usin = sample_register.usin    
                          AND gamma_results.istp='k40'    
                          WHERE mid(sample_register.usin,3,1)='F'    
                          AND sample_register.doc    
                          BETWEEN '2015-01-01'    
                          AND '2015-03-31'    
                          AND (sample_register.category='ter')    
                          ORDER BY mid(sample_register.usin,3,1),    
                                   sample_register.doc,    
                                   sample_register.usin) AS b    
               ON a.usin=b.usin

There are 4 records in the gamma_results table. two records each for 10/04/2015 and 18/04/2015.

USIN        istp     act     count_dt
-----------------------------------------
15FML002    Cs137   0.00769  10/04/15
15FML002    K40     0        10/04/15
15FML002    Cs137   0.00608  18/04/15
15FML002    K40     12.117   18/04/15

Query output data in the following form (some fields I deleted for convenience)

15FML002            0.00769 Y   10/04/15    00
15FML002            0.00769 Y   10/04/15    12.117
15FML002            0.00608 Y   18/04/15    00
15FML002            0.00608 Y   18/04/15    12.117

But I want to get output in two records. That is like this

15FML002            0.00769 Y   10/04/15    00
15FML002            0.00608 Y   18/04/15    12.117

How can I reframe (join or union) the query to get output like this?


Can't figure out with character encoding in PHP


I have put together little utility for reading youtube video tags. http://ift.tt/1Kg80CS

<?php
header("Content-Type: application/json");
error_reporting(E_ERROR | E_PARSE);
$_POST['fn']='http://ift.tt/1Kg80CU';
if(isset($_POST['fn']) && $_POST['fn'] != ''){
    $url = htmlentities($_POST['fn']);
    $page_content = file_get_contents('http://ift.tt/1Kg80CU');


    $dom_obj = new DOMDocument();
    if($dom_obj->loadHTML($page_content)){

        $dom_obj->loadHTML($page_content);
        $meta_val = '';

        foreach($dom_obj->getElementsByTagName('meta') as $meta) {

            if($meta->getAttribute('property')=='og:video:tag'){ 

                $meta_val = $meta_val.','.$meta->getAttribute('content');
            }
        }
        echo substr($meta_val,1);
    }
    else{
        echo "Invalid Url!";
    }
}
else{
    echo "Empty Url!";
}
?>

It works for ASCI characters but UTF characters show unreadable. I can't find the problem.


Querying from Remote databases using an ORM ( ie. Eloquent )


I have recently come across a situation where querying from two tables that has about 16k records each.

Executing raw SQL results in the response time to a few seconds and if I opt to stick to the ORM queries , the same results in a nginx request timeout since the query takes more than 1 min to process.

Has anyone faced a similar scenario , I am aware that heavy queries can be made using a Doctrine.


Featured Images in WP not showing


Added the line of code in my function.php file

add_theme_support('post-thumbnails' );

After going saving, and looking at my screen options, Featured images still wasn't showing. I even wen't as far back to check if my Custom Fields was correct and I had it unmarked to show


Display count of unique values in MySQL db table using PHP


So I have a table named pins that has 3 columns that need to be taken into consideration. These columns are plan and order_id.

I need to get a count for all of the pins that have an order_id=0 and plan=9.

This is what I have so far:

$qT="SELECT plan, COUNT(*) as cnt FROM pins WHERE order_id=0 and plan=9";
$res=mysql_query($qT);<br/>
mysql_free_result($res);

while($row = mysql_fetch_array($res)) {<br/>
echo $row['plan'];<br/>
}

Any help in displaying the results would be a great help.


Laravel 5 override summernote Image upload


I want to override image upload in summernote with laravel 5 method ajax, but I cant get it to work.

Here's my php method

public function ajaxImage()
{
    $file = Input::file('image');
    $destinationPath = public_path();
    $filename = $file->getClientOriginalName();
    if(Input::file('image')->move($destinationPath, $filename)) {
        echo $destinationPath.$filename;
    }
}

and here's my jquery code:

$(document).ready(function(){
            $('#description').summernote({
                height: 300,

                onImageUpload: function(files, editor, welEditable) {
                    sendFile(files[0], editor, welEditable);
                }
            });
            function sendFile(file, editor, welEditable) {
                var  data = new FormData();
                data.append("file", file);
                var url = '/articles/ajaximage';
                $.ajax({
                    data: data,
                    type: "POST",
                    url: url,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function(url) {
                        alert('Success');
                        editor.insertImage(welEditable, url);
                    }
                });
            }
        });

and i get an error in the console of:

POST http://ift.tt/1HCJ622 500 (Internal Server Error)


Adjust price if addons are set


Hi i have woocommerce addons plugin in my wordpress shop, for users to choose a weight and calculate the price upon the weight, i have this code that adds the main price to the price of KG, For example the cake costs 100$ per kg

in Cart it shows 700$ for 6 KG's. but it must show 600. So it adds the main price after the calculation.

here is the code

public function add_cart_item( $cart_item ) {
    // Adjust price if addons are set
    if ( ! empty( $cart_item['addons'] ) && apply_filters( 'woocommerce_product_addons_adjust_price', true, $cart_item ) ) {



        foreach ( $cart_item['addons'] as $addon ) {
            if ( $addon['price']  ) {

            }
        }

        $cart_item['data']->adjust_price($addon['price'] );
    }

    return $cart_item;
}


htaccess rewrite with php pages


OK, first of let me just say I understand that this is a question that has been asked before. I just can't narrow it down to keywords and find what I'm looking for. So sorry in advance if this is a duplicate. htaccess rewrite is like black magic to me... I can't really get it to work.

To the question at hand: I'm writing a simple barebone php/html site. I haven't done this in about 10 years (I usually use some CMS (wordpress, joomla etc.)). I'm trying to get a handle on some of the things that "come for free" with these CMSs. Like pretty URLs. I have a simple index.php with some includes to build the pages. Then I have my includes folder with my dynamic content.

So two case examples of the actual URLs

index.php?page=index (my main page) index.php?page=anotherpage (another page)

But what if I want to go to index.php?page=a-sub-page-to-another-page

This is my PHP (index.php in web root folder)

if(isset($_GET["page"])){
        $page = $_GET["page"];
        $filename = "/includes/" . $page . ".php";
        if(file_exists($filename)){
            include("/includes/head.php");
            include("/includes/navbar.php");
            include $filename;
            include("/includes/footer.php");
        }else{
            include("/includes/404.php");
        }
    }else{
        include("/includes/head.php");
        include("/includes/navbar.php");
        include("/includes/index.php");
        include("/includes/footer.php");
    }

This is my .htaccess

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9_-]+)$ index.php?page=$1

This works as long as I don't have any sub pages. But If I try to go to [root]/somepage/somsubpage then it doesn't work anymore. Can someone please help me out here? I'm looking to replicate the effect I get with standard CMSs like wordpress, where all URLs are SEO friendly.


Can't remove whitespaces in string


My script reads txt file and then writes values into database table. There is a field with price, and in txt file price with 4 digit values have whitespace after first digit (2 500 ex.). I put this function (str_replace works well and replaced ',' but when I use it for removing whitespace it does not do it, and finally I put preg_replace but it also skips whitespace):

$model->price = preg_replace('/\s+/','',str_replace(',', '.', $row_data[3]));

datatype of price field in my table is varchar, when I used int or decimal it skips digits after space (2 070 becomes 2, 12 015 => 12). I have to remove this space in integration stage, because when I do operations with price field php skips digits after space and I have errors in my further manipulations.

What is the problem guys?


How to get messages from MySQL database and print them in groups determined by Sender?


Say I have a table in MySQL database: id, msgto, msgfrom, message, date.

id = just message of it.
msgto = user ID who the message belongs to.
msgfrom = From whom the message is.
message = Message itself.
date = date of message.

So I want to make message system and display it as threads, so SELECT * FROM messages WHERE msgto=[current users ID]

Then I want to have messages grouped to sections/arrays like based on msgfrom variable.

So say there are 15 messages with msgfrom=5 and msgto=[current user] So basically there are 15 messages from user with ID of 5, how can I basically have them grouped and printed out in ID descending order (newest first)?

End result should be like:

message 4 from user1
message 3 from user1
message 2 from user1
message 1 from user1

[new group]
message 3 from user2
message 2 from user2
message 1 from user2

Printed in PHP by the way.


What web and mobile application technique are used in Foodpanda?


I want to know, How can I develop a website and mobile application (for Android , IOS and WP) like Foodpanda?

What is the technique used for both website and app?


Symfony2 / Doctrine2 : How to override DebugStack class used in doctrine DataCollector?


In order to better manage how I was making my database calls using Doctrine, I investigated how I could add the php debug_backtrace to the symfony doctrine db collector.

I managed to identify the modifications I had to make but I did not yet found a good way to override the DebugStack class (apart from overriding the vendor class).

the class is located here :

vendor/doctrine/dbal/lib/Doctrine/DBAL/Logging/DebugStack.php

For those who are interested, here is the result :

enter image description here

To do this, you need to :

Override the vendor/doctrine/doctrine-bundle/Resources/views/Collector/db.html.twig file

Copy this file to app\resources\DoctrineBundle\views\Collector\db.html.twig

You'll see my modifications below the two ====MODIFIED=== comments :

{% extends app.request.isXmlHttpRequest ? 'WebProfilerBundle:Profiler:ajax_layout.html.twig' : 'WebProfilerBundle:Profiler:layout.html.twig' %}

{% block toolbar %}
    {% set icon %}
        <img width="20" height="28" alt="Database" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAcCAYAAABh2p9gAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQRJREFUeNpi/P//PwM1ARMDlcGogZQDlpMnT7pxc3NbA9nhQKxOpL5rQLwJiPeBsI6Ozl+YBOOOHTv+AOllQNwtLS39F2owKYZ/gRq8G4i3ggxEToggWzvc3d2Pk+1lNL4fFAs6ODi8JzdS7mMRVyDVoAMHDsANdAPiOCC+jCQvQKqBQB/BDbwBxK5AHA3E/kB8nKJkA8TMQBwLxaBIKQbi70AvTADSBiSadwFXpCikpKQU8PDwkGTaly9fHFigkaKIJid4584dkiMFFI6jkTJII0WVmpHCAixZQEXWYhDeuXMnyLsVlEQKI45qFBQZ8eRECi4DBaAlDqle/8A48ip6gAADANdQY88Uc0oGAAAAAElFTkSuQmCC" />
        <span class="sf-toolbar-status{% if 50 < collector.querycount %} sf-toolbar-status-yellow{% endif %}">{{ collector.querycount }}</span>
        {% if collector.querycount > 0 %}
            <span class="sf-toolbar-info-piece-additional-detail">in {{ '%0.2f'|format(collector.time * 1000) }} ms</span>
        {% endif %}
        {% if collector.invalidEntityCount > 0 %}
            <span class="sf-toolbar-info-piece-additional sf-toolbar-status sf-toolbar-status-red">{{ collector.invalidEntityCount }}</span>
        {% endif %}
        {% if collector.cacheEnabled %}
            <span class="sf-toolbar-info-piece-additional sf-toolbar-status sf-toolbar-status-green" title="Second level cache enabled">2l cache</span>
        {% endif %}
    {% endset %}
    {% set text %}
        <div class="sf-toolbar-info-piece">
            <b>DB Queries</b>
            <span>{{ collector.querycount }}</span>
        </div>
        <div class="sf-toolbar-info-piece">
            <b>Query time</b>
            <span>{{ '%0.2f'|format(collector.time * 1000) }} ms</span>
        </div>
        <div class="sf-toolbar-info-piece">
            <b>Invalid entities</b>
            <span class="sf-toolbar-status sf-toolbar-status-{{ collector.invalidEntityCount > 0 ? 'red' : 'green' }}">{{ collector.invalidEntityCount }}</span>
        </div>
        {% if collector.cacheEnabled %}
            <div class="sf-toolbar-info-piece">
                <b>Cache hits</b>
                <span class="sf-toolbar-status sf-toolbar-status-green">{{ collector.cacheHitsCount }}</span>
            </div>
            <div class="sf-toolbar-info-piece">
                <b>Cache misses</b>
                <span class="sf-toolbar-status sf-toolbar-status-{{ collector.cacheMissesCount > 0 ? 'yellow' : 'green' }}">{{ collector.cacheMissesCount }}</span>
            </div>
            <div class="sf-toolbar-info-piece">
                <b>Cache puts</b>
                <span class="sf-toolbar-status sf-toolbar-status-{{ collector.cachePutsCount > 0 ? 'yellow' : 'green' }}">{{ collector.cachePutsCount }}</span>
            </div>
        {% endif %}
    {% endset %}
    {% include 'WebProfilerBundle:Profiler:toolbar_item.html.twig' with { 'link': profiler_url } %}
{% endblock %}

{% block menu %}
<span class="label">
    <span class="icon"><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAcCAYAAAB/E6/TAAABLUlEQVR42u3TP0vDQBiA8UK/gDiLzi0IhU4OEunk5OQUAhGSOBUCzqWfIKSzX8DRySF0URCcMjWLIJjFD9Cpk/D6HITecEPUuzhIAz8CIdyTP/f2iqI4qaqqDx8l5Ic2uIeP/bquezCokOAFF+oCN3t4gPzSEjc4NEPaCldQbzjELTYW0RJzHDchwwem+ons6ZBpLSJ7nueJC22h0V+FzmwWV0ee59vQNV67CGVZJmEYbkNjfpY6X6I0Qo4/3RMmTdDDspuQVsJvgkP3IdMbIkIjLPBoadG2646iKJI0Ta2wxm6OdnP0/Tk6DYJgHcfxpw21RtscDTDDnaVZ26474GkkSRIrrPEv5sgMTfHe+cA2O6wPH6vOBpYQNALneHb96XTEDI6dzpEZ0VzO0Rf3pP5LMLI4tAAAAABJRU5ErkJggg==" alt="" /></span>
    <strong>Doctrine</strong>
    <span class="count">
        <span>{{ collector.querycount }}</span>
        <span>{{ '%0.0f'|format(collector.time * 1000) }} ms</span>
    </span>
</span>
{% endblock %}

{% block panel %}
    {% if 'explain' == page %}
        {{ render(controller('DoctrineBundle:Profiler:explain', {
            'token': token,
            'panel': 'db',
            'connectionName': app.request.query.get('connection'),
            'query': app.request.query.get('query')
        })) }}
    {% else %}
        {{ block('queries') }}
    {% endif %}
{% endblock %}

{% block queries %}
    <h2>Queries</h2>

    {# =========================================       MODIFIED        ===============================#}
    <script src="{{ asset('vendor/jquery/jquery-2.1.1.min.js') }}"></script>
    <style rel="stylesheet">
        .hidden {display: none;}
    </style>
    <script>
        $(function(){
            $('.trace').on('click', function(e){
                e.preventDefault();
                $(this).next().toggleClass('hidden');
            });
        });
    </script>

    {% for connection, queries in collector.queries %}
        <h3>Connection <em>{{ connection }}</em></h3>
        {% if queries is empty %}
            <p>
                <em>No queries.</em>
            </p>
        {% else %}
            <p>
                <button type="button" class="sf-button" onclick="expandAllQueries(this);" data-action="expand">
                    <span class="border-l">
                        <span class="border-r">
                            <span class="btn-bg">Expand all queries</span>
                        </span>
                    </span>
                </button>
            </p>
            <table class="alt" id="queriesPlaceholder-{{ loop.index }}">
                <thead>
                    <tr>
                        <th onclick="javascript:sortTable(this, 0, 'queries-{{ loop.index }}')" data-sort-direction="-1" style="cursor: pointer;">#<span>&#9650;</span></th>
                        <th onclick="javascript:sortTable(this, 1, 'queries-{{ loop.index }}')" style="cursor: pointer;">Time<span></span></th>
                        <th style="width: 100%;">Info</th>
                    </tr>
                </thead>
                <tbody id="queries-{{ loop.index }}">
                {% for i, query in queries %}
                    <tr id="queryNo-{{ i }}-{{ loop.parent.loop.index }}" class="{{ cycle(['odd', 'even'], i) }}">
                        <td>{{ loop.index }}</td>
                        <td>{{ '%0.2f'|format(query.executionMS * 1000) }}&nbsp;ms</td>
                        <td>
                            <div class="query-section" data-state="collapsed" onclick="return expandQuery(this);" title="Expand query" data-target-id="code-{{ i }}-{{ loop.parent.loop.index }}" style="cursor: pointer;">
                                <img alt="+" src="data:image/gif;base64,R0lGODlhEgASAMQTANft99/v+Ga44bHb8ITG52S44dXs9+z1+uPx+YvK6WC24G+944/M6W28443L6dnu+Ge54v/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABMALAAAAAASABIAQAVS4DQBTiOd6LkwgJgeUSzHSDoNaZ4PU6FLgYBA5/vFID/DbylRGiNIZu74I0h1hNsVxbNuUV4d9SsZM2EzWe1qThVzwWFOAFCQFa1RQq6DJB4iIQA7" style="display: inline;" />
                                <img alt="-" src="data:image/gif;base64,R0lGODlhEgASAMQSANft94TG57Hb8GS44ez1+mC24IvK6ePx+Wa44dXs92+942e54o3L6W2844/M6dnu+P/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABIALAAAAAASABIAQAVCoCQBTBOd6Kk4gJhGBCTPxysJb44K0qD/ER/wlxjmisZkMqBEBW5NHrMZmVKvv9hMVsO+hE0EoNAstEYGxG9heIhCADs=" style="display: none;" />
                                <span style="display: none">Shrink query</span>
                                <span id="smallcode-{{ i }}-{{ loop.parent.loop.index }}">
                                    {{ query.sql|doctrine_minify_query|raw }}
                                </span>
                            </div>
                            <code id="code-{{ i }}-{{ loop.parent.loop.index }}">
                                {{ query.sql|doctrine_pretty_query(i, loop.parent.loop.index)|raw }}
                            </code>
                            <span id="original-query-{{ i }}-{{ loop.parent.loop.index }}" style="display: none;">
                                {{ query.sql|doctrine_replace_query_parameters(query.params)|raw }}
                            </span>
                            <small>
                                <strong>Parameters</strong>: {{ query.params|yaml_encode }} <br />
                                [<span id="expandParams-{{ i }}-{{ loop.parent.loop.index }}" onclick="javascript:toggleRunnableQuery(this);" target-data-id="original-query-{{ i }}-{{ loop.parent.loop.index }}" style="cursor: pointer;">Display runnable query</span>]<br/>
                            </small>

                            {% if query.explainable %}
                                [<a href="{{ path('_profiler', {'panel': 'db', 'token': token, 'page': 'explain', 'connection': connection, 'query': i}) }}" onclick="return explain(this);" style="text-decoration: none;" title="Explains the query" data-target-id="explain-{{ i }}-{{ loop.parent.loop.index }}" >
                                    <img alt="+" src="data:image/gif;base64,R0lGODlhEgASAMQTANft99/v+Ga44bHb8ITG52S44dXs9+z1+uPx+YvK6WC24G+944/M6W28443L6dnu+Ge54v/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABMALAAAAAASABIAQAVS4DQBTiOd6LkwgJgeUSzHSDoNaZ4PU6FLgYBA5/vFID/DbylRGiNIZu74I0h1hNsVxbNuUV4d9SsZM2EzWe1qThVzwWFOAFCQFa1RQq6DJB4iIQA7" style="display: inline; width: 12px; height: 12px;" />
                                    <img alt="-" src="data:image/gif;base64,R0lGODlhEgASAMQSANft94TG57Hb8GS44ez1+mC24IvK6ePx+Wa44dXs92+942e54o3L6W2844/M6dnu+P/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABIALAAAAAASABIAQAVCoCQBTBOd6Kk4gJhGBCTPxysJb44K0qD/ER/wlxjmisZkMqBEBW5NHrMZmVKvv9hMVsO+hE0EoNAstEYGxG9heIhCADs=" style="display: none; width: 12px; height: 12px;" />
                                    <span style="vertical-align:top">Explain query</span>
                                </a>]
                            {% else %}
                                This query cannot be explained
                            {% endif %}

                            {% if query.explainable %}
                                <div id="explain-{{ i }}-{{ loop.parent.loop.index }}" class="loading"></div>
                            {% endif %}

                            {# =========================================       MODIFIED        ===============================#}
                            {% if query.trace is defined %}
                                <div>
                                    [<a href="#/" style="text-decoration: none;" title="Show the trace" class="trace">
                                        <img alt="+" src="data:image/gif;base64,R0lGODlhEgASAMQTANft99/v+Ga44bHb8ITG52S44dXs9+z1+uPx+YvK6WC24G+944/M6W28443L6dnu+Ge54v/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABMALAAAAAASABIAQAVS4DQBTiOd6LkwgJgeUSzHSDoNaZ4PU6FLgYBA5/vFID/DbylRGiNIZu74I0h1hNsVxbNuUV4d9SsZM2EzWe1qThVzwWFOAFCQFa1RQq6DJB4iIQA7" style="display: inline; width: 12px; height: 12px;" />
                                        <span style="vertical-align:top">Show the trace</span>
                                    </a>]
                                    <div class="hidden">{{ dump(query.trace) }}</div>
                                </div>
                            {% endif %}
                        </td>
                    </tr>
                {% endfor %}
                </tbody>
            </table>
        {% endif %}
    {% endfor %}

    <h2>Database Connections</h2>

    {% if collector.connections %}
        {% include 'WebProfilerBundle:Profiler:table.html.twig' with {data: collector.connections} only %}
    {% else %}
        <p>
            <em>No connections.</em>
        </p>
    {% endif %}

    <h2>Entity Managers</h2>

    {% if collector.managers %}
        {% include 'WebProfilerBundle:Profiler:table.html.twig' with {data: collector.managers} only %}
    {% else %}
        <p>
            <em>No entity managers.</em>
        </p>
    {% endif %}

    <h2>Second Level Cache</h2>

    {% if collector.cacheCounts %}
        {% include 'WebProfilerBundle:Profiler:table.html.twig' with {data: collector.cacheCounts} only %}

        {% if collector.cacheRegions.hits %}
            <h3>Number of cache hits</h3>
            {% include 'WebProfilerBundle:Profiler:table.html.twig' with {data: collector.cacheRegions.hits} only %}
        {% endif %}

        {% if collector.cacheRegions.misses %}
            <h3>Number of cache misses</h3>
            {% include 'WebProfilerBundle:Profiler:table.html.twig' with {data: collector.cacheRegions.misses} only %}
        {% endif %}

        {% if collector.cacheRegions.puts %}
            <h3>Number of cache puts</h3>
            {% include 'WebProfilerBundle:Profiler:table.html.twig' with {data: collector.cacheRegions.puts} only %}
        {% endif %}
    {% else %}
        <p>
            <em>No cache.</em>
        </p>
    {% endif %}

    <h2>Mapping</h2>

    {% for manager, classes in collector.entities %}
        <h3>Manager <em>{{ manager }}</em></h3>
        {% if classes is empty %}
            <p><em>No loaded entities.</em></p>
        {% else %}
            <table>
                <thead>
                <tr>
                    <th scope="col">Class</th>
                    <th scope="col">Mapping errors</th>
                </tr>
                </thead>
                <tbody>
                {% for class in classes %}
                    <tr>
                        <td>{{ class }}</td>
                        <td>
                            {% if collector.mappingErrors[manager][class] is defined %}
                                <ul>
                                    {% for error in collector.mappingErrors[manager][class] %}
                                        <li>{{ error }}</li>
                                    {% endfor %}
                                </ul>
                            {% else %}
                                Valid
                            {% endif %}
                        </td>
                    </tr>
                {% endfor %}
                </tbody>
            </table>
        {% endif %}
    {% endfor %}

    <script type="text/javascript">//<![CDATA[
        function explain(link) {
            "use strict";

            var imgs = link.children,
                target = link.getAttribute('data-target-id');

            Sfjs.toggle(target, imgs[0], imgs[1])
                .load(
                    target,
                    link.href,
                    null,
                    function(xhr, el) {
                        el.innerHTML = 'An error occurred while loading the details';
                        Sfjs.removeClass(el, 'loading');
                    }
                );

            return false;
        }

        function expandAllQueries(button) {
            var queries = document.getElementsByClassName('query-section'),
                i = queries.length,
                action = button.getAttribute('data-action');

            if (action == 'expand') {
                button.getElementsByClassName('btn-bg')[0].innerHTML = 'Collapse all queries';

                while (i--) {
                    if (queries[i].getAttribute('data-state') == 'collapsed') {
                        expandQuery(queries[i]);
                    }
                }
            } else {
                button.getElementsByClassName('btn-bg')[0].innerHTML = 'Expand all queries';

                while (i--) {
                    if (queries[i].getAttribute('data-state') == 'expanded') {
                        expandQuery(queries[i]);
                    }
                }
            }

            button.setAttribute('data-action', action == 'expand' ? 'collapse' : 'expand');
        }

        function expandQuery(link) {
            var sections = link.children,
                target = link.getAttribute('data-target-id'),
                targetId = target.replace('code', ''),
                queriesParameters = document.getElementById('original-query' + targetId);

            if (queriesParameters.style.display != 'none') {
                queriesParameters.style.display = 'none';
                document.getElementById('small' + target).style.display = 'inline';
                document.getElementById('expandParams' + targetId).innerHTML = 'Display runnable query';
            }

            if (document.getElementById('small' + target).style.display != 'none') {
                document.getElementById('small' + target).style.display = 'none';
                document.getElementById(target).style.display = 'inline';

                sections[0].style.display = 'none';
                sections[1].style.display = 'inline';
                sections[2].style.display = 'inline';

                link.setAttribute('data-state', 'expanded');
            } else {
                document.getElementById('small' + target).style.display = 'inline';
                document.getElementById(target).style.display = 'none';

                sections[0].style.display = 'inline';
                sections[1].style.display = 'none';
                sections[2].style.display = 'none';

                link.setAttribute('data-state', 'collapsed');
            }

            return false;
        }

        function toggleRunnableQuery(target) {
            var targetId = target.getAttribute('target-data-id').replace('original-query', ''),
                targetElement = document.getElementById(target.getAttribute('target-data-id')),
                elem;

            if (targetElement.style.display != 'block') {
                targetElement.style.display = 'block';
                target.innerHTML = 'Hide runnable query';

                document.getElementById('smallcode' + targetId).style.display = 'none';
                document.getElementById('code' + targetId).style.display = 'none';

                elem = document.getElementById('code' + targetId).parentElement.children[0];

                elem.children[0].style.display = 'inline';
                elem.children[1].style.display = 'none';
                elem.children[2].style.display = 'none';

            } else {
                targetElement.style.display = 'none';
                target.innerHTML = 'Display runnable query';

                document.getElementById('smallcode' + targetId).style.display = 'inline';
            }
        }

        function sortTable(header, column, targetId) {
            "use strict";

            var direction = parseInt(header.getAttribute('data-sort-direction')) || 1,
                items = [],
                target = document.getElementById(targetId),
                rows = target.children,
                headers = header.parentElement.children,
                i;

            for (i = 0; i < rows.length; ++i) {
                items.push(rows[i]);
            }

            for (i = 0; i < headers.length; ++i) {
                headers[i].removeAttribute('data-sort-direction');
                if (headers[i].children.length > 0) {
                    headers[i].children[0].innerHTML = '';
                }
            }

            header.setAttribute('data-sort-direction', (-1*direction).toString());
            header.children[0].innerHTML = direction > 0 ? '&#9650;' : '&#9660;';

            items.sort(function(a, b) {
                return direction*(parseFloat(a.children[column].innerHTML) - parseFloat(b.children[column].innerHTML));
            });

            for (i = 0; i < items.length; ++i) {
                Sfjs.removeClass(items[i], i % 2 ? 'even' : 'odd');
                Sfjs.addClass(items[i], i % 2 ? 'odd' : 'even');
                target.appendChild(items[i]);
            }
        }

    //]]></script>

    <style>
        h3 {
            margin-bottom: 0px;
        }

        code {
            display: none;
        }

        code pre {
            padding: 5px;
        }
    </style>
{% endblock %}

Next edit the vendor/doctrine/dbal/lib/Doctrine/DBAL/Logging/DebugStack.php file

and change the startQuery method as follows :

/**
 * {@inheritdoc}
 */
public function startQuery($sql, array $params = null, array $types = null)
{
    if ($this->enabled) {
        $this->start = microtime(true);
        $this->queries[++$this->currentQuery] = array('sql' => $sql, 'params' => $params, 'types' => $types, 'executionMS' => 0, 'trace' => debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS));
    }
}

I've not yet found how to make a more efficient change, so every proposition here would be very nice ! Thanks !


wamp is not starting completely


I have latest version of wamp i.e WAMPSERVER (64 BITS & PHP 5.5) 2.5 installed. Its not starting completely, not turning to green and so mysql is not starting even though the port is used by apache itself.

I have also installed Visual Studio 2012 VC 11 vcredist_x64/86.exe for my Windows 8.1 64bit OS.

Very weird, all the paths are configured in paths and also extensions enabled. Please help!!

enter image description here


All fields in database updated at once using PHP


I have a form that comes from a link in a table that should just update one record in my database. When I changed some details in the table and pressed my submit button it changed all of my fields in the database and not just the one I wanted to change. Below is my form code and also the table that is being edited.

Edit user code

<?php

 // since this form is used multiple times in this file, I have made it a function that is easily reusable
 function renderForm($userID, $username, $password, $telephone, $address1, $town, $postcode, $forename, $surname, $email, $error)
 {
 ?>
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://ift.tt/nYkKzf">
 <html>
 <head>
 <title>Edit User</title>
 </head>
 <body>
 <?php 
 // if there are any errors, display them
 if ($error != '')
 {
 echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
 }
 ?> 
 
 <form action="" method="post">
 <input type="hidden" name="userID" value="<?php echo $userID; ?>"/>
 <div>
 <p><strong>ID:</strong> <?php echo $userID; ?></p>
 <strong>Username: </strong> <input type="text" name="username" value="<?php echo $username; ?>"/><br/>
 <strong>Password: </strong> <input type="text" name="password" value="<?php echo $password; ?>"/><br/>
 <strong>Telephone: </strong> <input type="text" name="telephone" value="<?php echo $telephone; ?>"/><br/>
 <strong>Address: </strong> <input type="text" name="address1" value="<?php echo $address1; ?>"/><br/>
 <strong>Town: </strong> <input type="text" name="town" value="<?php echo $town; ?>"/><br/>
 <strong>Postcode: </strong> <input type="text" name="postcode" value="<?php echo $postcode; ?>"/><br/>
 <strong>Forename: </strong> <input type="text" name="forename" value="<?php echo $forename; ?>"/><br/>
 <strong>Surname: </strong> <input type="text" name="surname" value="<?php echo $surname; ?>"/><br/>
 <strong>Email: </strong> <input type="text" name="email" value="<?php echo $email; ?>"/><br/>

 <input type="submit" name="submit" value="Edit details">
 </div>
 </form> 
 </body>
 </html> 
 <?php
 }



 // connect to the database
 include "config.php";
 
 // check if the form has been submitted. If it has, process the form and save it to the database
 if (isset($_POST['submit']))
 { 
 // confirm that the 'id' value is a valid integer before getting the form data
 if (is_numeric($_POST['userID']))
 {
 // get form data, making sure it is valid
 $userID = $_POST['userID'];
 $username = $_POST['username'];
 $password = $_POST['password'];
 $telephone = $_POST['telephone'];
 $address1 = $_POST['address1'];
 $town = $_POST['town'];
 $postcode = $_POST['postcode'];
 $forename = $_POST['forename'];
 $surname = $_POST['surname'];
 $email = $_POST['email'];
 
 // check that firstname/lastname fields are both filled in
 if ($username == '' || $password == '' || $telephone == '' || $address1 == '' || $town == '' || $postcode == '' || $forename == '' || $surname == '' || $email == '' )
 {
 // generate error message
 $error = 'ERROR: Please fill in all required fields!';
 
 //error, display form
 renderForm($userID, $username, $password, $telephone, $address1, $town, $postcode, $forename, $surname, $email, $error);
 }
 else
 {
 // save the data to the database
        $query = $db->prepare("UPDATE user SET username='$username', password='$password', telephone='$telephone', address1='$address1', town='$town', postcode='$postcode', forename='$forename', surname='$surname', email='$email' ");
        $query->execute();
 
 // once saved, redirect back to the view page
 header("Location: view_user.php"); 
 }
 }
 else
 {
 // if the 'id' isn't valid, display an error
 echo 'Error!';
 }
 }
 else
 // if the form hasn't been submitted, get the data from the db and display the form
 {
 
 // get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
 if (isset($_GET['userID']) && is_numeric($_GET['userID']) && $_GET['userID'] > 0)
 {
 // query db
 $userID = $_GET['userID'];
 $query = $db->prepare("SELECT * FROM user WHERE userID=$userID");
 $query->execute();
 $dbRow = $query->fetch(PDO::FETCH_ASSOC);
 
 // check that the 'id' matches up with a row in the databse
 if($dbRow)
 {
 
 // get data from db
 $username = $dbRow['username'];
 $password = $dbRow['password'];
 $telephone = $dbRow['telephone'];
 $address1 = $dbRow['address1'];
 $town = $dbRow['town'];
 $postcode = $dbRow['postcode'];
 $forename = $dbRow['forename'];
 $surname = $dbRow['surname'];
 $email = $dbRow['email'];
 
 
 // show form
 renderForm($userID, $username, $password, $telephone, $address1, $town, $postcode, $forename, $surname, $email, '');
 }
 else
 // if no match, display result
 {
 echo "No results!";
 }
 }
 else
 // if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
 {
 echo 'Error!';
 }
 }
?>

View user info code

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">

    <title>Ballymena Sports</title>

    <!-- Bootstrap core CSS -->
    <link href="bootstrap.min.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="home2.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="http://ift.tt/1xwklwE"></script>
      <script src="http://ift.tt/1qIredN"></script>
    <![endif]-->
  </head>

  <body>

    <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
      <div class="container">
        <div class="navbar-header">
                                <a class="navbar-brand" href="home2_template.html">Ballymena Sports</a>
                </div>
                
                <ul class="nav navbar-nav navbar-right">
                    <li><a href="admin_login.php">Administrator</a></li>
            <li><a href="logout.php">Log out</a></li>
                </ul>
                
          </div>
    </nav>
        


    <!-- Main part of homepage -->
    <div class="jumbotron">
                <div class="container">
                  <h2>Users</h2>
                  <p>This table shows all registered users of Ballymena Sports:</p>            
                        
                        <div class="table-responsive"> 
                        <tbody>
                                <?php 
                                        include "config.php"; 
                                        
                                        $query = $db->prepare("SELECT * FROM user ORDER BY userID asc");
                                        $query->execute();
                
                
                                        echo "<table id='user' class='table table-bordered'>
                                                  <tr>
                                                  <th>User ID</th>
                                                  <th>Username</th>
                                                  <th>Forename</th>
                                                  <th>Surname</th>
                                                  <th>Email</th>
                                                  <th>Address</th>
                                                  <th>Town</th>
                                                  <th>Postcode</th>
                                                  <th>Edit User</th> 
                                                  <th>Delete User</th>
                                                  </tr>";
                                                
                                        while ($dbRow = $query->fetch(PDO::FETCH_ASSOC)) {
                                                $userID = $dbRow['userID'];
                                                $username = $dbRow['username'];
                                                $forename = $dbRow['forename'];
                                                $surname = $dbRow['surname'];
                                                $email = $dbRow['email'];
                                                $address1 = $dbRow['address1'];
                                                $town = $dbRow['town'];
                                                $postcode = $dbRow['postcode'];
                                                // code to display information
                                                
                                
                           { echo "<tr>
                                                <td>$userID</td>
                                                <td>$username</td>
                                                <td>$forename</td>
                                                <td>$surname</td>
                                                <td>$email</td>
                                                <td>$address1</td>
                                                <td>$town</td>
                                                <td>$postcode</td>
                                                <td><a href='edit_user.php?userID=".$userID."'>Edit</a></td>
                                                <td><a href='delete_user.php?userID=".$userID."'>Delete</a></td>
                                          </tr>";}
                                } //while
                                ?> 

                        </tbody>
                        </div>
                  </table>
                </div>
    </div>
<?php 


        if(!$_SESSION['admin_username']){
                header('location:admin_login.php'); 
                
                $name = $_SESSION['admin_username'];
        }
        
?> 

      <hr>



    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="http://ift.tt/1qRgvOJ"></script>
    <script src="../../dist/js/bootstrap.min.js"></script>
    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <script src="../../assets/js/ie10-viewport-bug-workaround.js"></script> 
        <!-- Header and footer later to be used as include statements -->
  </body>
</html>

sending information from a newly created record to a different mysql table


I'm making a form that submits a story into a mysql table called 'work'. I want to later take the id of the newly created record and put the information into a different table. But when I submit the story, it says $workid is undefined. I can't see the problem though because I believe I've defined it?

<?php
            if (!empty($_POST) && !empty($_POST['title']) && !empty($_POST['story']) && !empty($_POST['genre']) && !empty($_POST['rating'])) { 
                $title = strip_tags($_POST['title']);
                $story = strip_tags($_POST['story']);
                $title = mysqli_real_escape_string($db, $title);
                $story = mysqli_real_escape_string($db, $story);
                $genre = $_POST['genre'];
                $rating = $_POST['rating'];

                $query = "SELECT COUNT(*) AS count FROM works WHERE Title = '".$title."'";
                 $result = $db->query($query);
                 $data = $result->fetch_assoc();

                 if ($data['count'] > 0) {
                     echo "<p>Story already exists!</p>";
                     } else {
                         $query = "INSERT INTO works (author_id, login_id, Title, Story, Genre, Rating) VALUES ('".$userid."','".$authorid."','".$title."','".$story."','".$genre."','".$rating."')";

                        $query="SELECT `id` FROM `works` WHERE `Title` = '".$title."'";
                        if ($result = $db->query($query)) {
                        while ($row= $result->fetch_assoc()) 
                        $workid = $row["id"];} //workid is written here but still considered undefined


                        $query = "INSERT INTO `author_work` (`author_id`) VALUES ('".$authorid."')";
                        $result = $db->query($query);

                        $query = "INSERT INTO `author_work` (`work_id`) VALUES ('".$workid."')";
                        $result = $db->query($query);

                        $query = "INSERT INTO `login_work` (`work_id`) VALUES ('".$workid."')";
                        $result = $db->query($query);


                        $query = "INSERT INTO `login_work` (`login_id`) VALUES ('".$userid."')";
                        $result = $db->query($query);                           


            if ($result) {
              echo "<p>Story submitted!</p>";
            } else {
                echo "SQL Error: " . $db->error;
            }
            }
            }
        ?>


REST client model in CakePHP 3


I'm developing a Cake application that pulls data from the database as well as from a third-party REST API. I'd like to implement the REST API properly using models for the various REST collections I'm trying to access (inheriting from a single behaviour), but I can't get my model working without a corresponding database table. My original plan was to create class Software extends Cake\ORM\Entity and class SoftwaresTable extends Cake\ORM\Table, then use the before* hooks to override the various calls and reroute them to the API rather than the database.

However, I've added die() to beforeMarshal, beforeRules, beforeFind, beforeSave, and beforeDelete, and calling $this->Softwares->all() from the controller still fails with the message

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'inventory.softwares' doesn't exist

Is my approach wrong? Something simple that I'm missing?


dynamically created input button is being skipped by tabbing ... how to set tabindex


I have dynamically created a table with elements followed by a search and reset button. In general tabbing works through input fields and select fields in the table. Tabbing skips over checkbox which is not bothering me. However, after the table comes two buttons, search and reset. Adding these buttons dynamically will get skipped over when tabbing.

$('#' + div_id).append('<input type="button" class = "button" value="Search" onclick="'+this.table_name+'.submitSearch()">');
$('#' + div_id).append('<input type="button" class = "button" value="Reset" onclick="'+ this.table_name +'.resetSearch()">');

I have tried adding the following code:

$(":input:not(:hidden)").each(function (i) 
    {
        console.log(this.id);
        $(this).attr('tabindex', i + 1); 
    }); 

Which is not helping. Php generated html code works as expected. Thanks for your help!!!


Multi-Store in OpenCart - Config


I have 'website1.com' running OpenCart 2.0.1.1 and I want to set up a multi store with 'website2.com' - so that the client can manage both websites via one single admin area instance. To my understanding, I'm supposed to point 'website2.com' to use the same httpdocs location as 'website1.com'. Instead, I've set up 'website2.com' as an alias of 'website1.com' which is fine, the website loads up but what is confusing me is the config.php:

<?php
// HTTP
define('HTTP_SERVER', 'http://ift.tt/1HD4Auf');

// HTTPS
define('HTTPS_SERVER', 'http://ift.tt/1PAgFDf');

// DIR
define('DIR_APPLICATION', '/var/www/vhosts/website1.com/httpdocs/catalog/');
define('DIR_SYSTEM', '/var/www/vhosts/website1.com/httpdocs/system/');
define('DIR_LANGUAGE', '/var/www/vhosts/website1.com/httpdocs/catalog/language/');
define('DIR_TEMPLATE', '/var/www/vhosts/website1.com/httpdocs/catalog/view/theme/');
define('DIR_CONFIG', '/var/www/vhosts/website1.com/httpdocs/system/config/');
define('DIR_IMAGE', '/var/www/vhosts/website1.com/httpdocs/image/');
define('DIR_CACHE', '/var/www/vhosts/website1.com/httpdocs/system/cache/');
define('DIR_DOWNLOAD', '/var/www/vhosts/website1.com/httpdocs/system/download/');
define('DIR_UPLOAD', '/var/www/vhosts/website1.com/httpdocs/system/upload/');
define('DIR_MODIFICATION', '/var/www/vhosts/website1.com/httpdocs/system/modification/');
define('DIR_LOGS', '/var/www/vhosts/website1.com/httpdocs/system/logs/');

Would there be any security issues if I were to change every instance of 'website1.com' to $_SERVER['HTTP_HOST']? - this way, the correct directories would be loaded into the config file.

Apparently the correct way to set up multi-store is to set the domain up as a VirtualHost - but I can't understand how this would work since the define statements are still always going to point to the first website.

Appreciate any help!

Thanks,

Liam


search attempt syntax error


I could not figure out if I am doing this right. I am trying to output results from my search, however I am unsure if this is done properly. Plus I'm getting this error.

Parse error: syntax error, unexpected '''' (T_CONSTANT_ENCAPSED_STRING) in /usr/local/www/project/OlegarioJW/largecoursework/tobakuhome.php on line 152

In addition, I am intending to put it inside a div as well as two of my results into <a> tag as these will have links and they are all inside a variable. Is this how it is done?

Below is my code:

<html>
<header></header>

<body>

<?php
    $serverName = "example.com";
    $dbName = "abc";
    $user = "abc";
    $pass = "abc";

    $connection = mysqli_connect($serverName, $user, $pass, $dbName);
    if (!$connection){
        die("Connection failure" . mysqli_connect_error());
    }

?>

<form id ="search" action="tobakuhome.php" method="post">
        <input type="text" name="search" placeholder="Search Game titles here"/>
        <input type="submit" value="Go" />
</form>

<?php print("$output"); ?>

<?php

$output = '';
if (isset($_POST['search'])){
    $searching = $_POST['search'];
    $searching = preg_replace("#[^0-9a-z]#i","", $searching);
} 

    $query = "SELECT * FROM Software WHERE name LIKE '%searching%' OR description LIKE '%$searching%' OR exclusivity LIKE '%$searching%' OR format LIKE '%$searching%'";
    $result = mysqli_query($connection, $query) or die("no results found");
    $count = mysqli_num_rows($query);
    if($count ==0){
        $output = 'Sorry, No results was found.';

    }else{
        while($row = mysqli_fetch_array($query)){
            $Tname = $row['Name'];
            $Tdes = $row['description'];
            $Timg = $row['image'];
            $Texcl = $row['exclusivity'];
            $Tform = $row['format'];
            $Tprice = $row['price'];
            $id = $row['id'];


            $output .= '<div id="data">''<ul id="itemgal">'
            '<li id = "softitem">'
            '<a id= "row" href = "displaysoftware.php?id=" .$id." '.$Tname.' />' '</a>'
            '<a id= "row" href = "displaysoftware.php?id=" .$id." '.$Timg.' />'    '</a>'
            '<br />'
            '<h3>'.$Tform . '</h3>''</td>'
            '<br />'
            '<h4>'.$Texcl . '</h4>''</td>'
            '<h5>' '£' . $Tprice.'</h5>'
            '</li>'
            '</ul>'
            '</div>';
        }
    }

?>
</body>
</html>


My login script does not connect the admin panel


I watch a tutorial on Youtube to create a login script, the login works, but the login does not connect to the admin panel. What am I doing wrong?

Thank you very much!

<?php

require_once "../blog/connect.php";
require_once "../blog/functie.php";



?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <title>Dashboard I Admin Panel</title>

    <link rel="stylesheet" href="css/layout.css" type="text/css" media="screen" />
    <!--[if lt IE 9]>
    <link rel="stylesheet" href="css/ie.css" type="text/css" media="screen" />
    <script src="http://ift.tt/yaI000"></script>
    <![endif]-->
    <script src="js/jquery-1.5.2.min.js" type="text/javascript"></script>
    <script src="js/hideshow.js" type="text/javascript"></script>
    <script src="js/jquery.tablesorter.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="js/jquery.equalHeight.js"></script>
    <script type="text/javascript">
    $(document).ready(function() 
        { 
          $(".tablesorter").tablesorter(); 
     } 
    );
    $(document).ready(function() {

    //When page loads...
    $(".tab_content").hide(); //Hide all content
    $("ul.tabs li:first").addClass("active").show(); //Activate first tab
    $(".tab_content:first").show(); //Show first tab content

    //On Click Event
    $("ul.tabs li").click(function() {

        $("ul.tabs li").removeClass("active"); //Remove any "active" class
        $(this).addClass("active"); //Add "active" class to selected tab
        $(".tab_content").hide(); //Hide all tab content

        var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
        $(activeTab).fadeIn(); //Fade in the active ID content
        return false;
    });

});
    </script>
    <script type="text/javascript">
    $(function(){
        $('.column').equalHeight();
    });
</script>
</head>
<body>

    <?php

    if ($_SESSION["login"]){
        require_once "inc/default.php";
    }else {

}
    if ($_POST) {

        $kadi = p("kadi");
        $sfire = p("sfire");


        if (!$kadi || !$sfire) {
            echo "Kullanici adi ve sifre bos birakilamaz..";

        }else {

            $query = query("SELECT * FROM uyeler WHERE uye_kadi = '$kadi' && uye_sfire = '$sfire' && uye_rutbe = 1");
            if (mysql_affected_rows()){

                $row = row($query);
                $session = array(
                    "login" => true,
                    "uye_id" => $row["uye_id"],
                    "uye_rutbe" => $row["uye_rutbe"],
                    "uye_kadi" => $row["uye_kadi"]);

                session_olustur($session);

                go(URL."/admin");

            }


            else {
                echo "<font color='red'>Boyle bir kullanici adi bulunmuyor</font>";
            }
        }
    }
?>


<div id="giris_yap">
<form action="" method="post">
    <table cellpadding="0" cellspacing="0">
            <tr>
                <td>Gebruikersnaam:</td>
                <td><input type="text" name="kadi" /></td>
            </tr>
    <tr>
        <td>Wachtwoord:</td>
        <td><input type="password" name="sfire" /></td>
    </tr>

    <tr>
        <td></td>
        <td><button type="submit">Giris yap</button></td>
    </tr>
    </table>
</form>
</div>
</body>
</html>