Why it doesn't return?? PHP - php

I can't understand and I seek for help=(
Here is my code:
$add_article = $this->M_articles->Add($_POST['title'], $_POST['content']);
echo "sd;flksdf;lksdfl;";
$add_article2 = true;
if ($add_article)
{
echo 'Article Added!';
header("Location:index.php");
die();
}
else
die('Error adding article');
this is function "Add" from M_Articles:
public function Add($title, $content)
{
/*
$title = trim($title);
$content = trim($content);
if ($title == '')
return false;
//запрос
$object = array();
$object['title'] = $title;
$object['content'] = $content;
$this->msql->Insert('articles', $object);
*/
return true;
}
The thing is...even if I comment everything from function "Add" and leave only "return true"... it wouldn't redirect me to index.php. Moreover, it doesn't even echo anything (even those "sd;fkfdsf.." string). The script just dies for some reason. I can't get where is the problem, can some1 explain to newbie what's the problem and how it should be fixed? If you need additional info, i'll provide it.
update: Maybe it's important...but if I delete those comment "/* */" things, it'd correctly add article to a DataBase. But then the script dies=/
update:
ok, now it says: "Notice: Undefined variable: result in Z:\home\myblog\www\c\M_MSQL.php on line 86"
here's my code for M_MSQL on line 86:
public function Insert($table, $object)
{
$columns = array();
$values = array();
foreach ($object as $key => $value)
{
$key = mysql_real_escape_string($key . '');
$columns[] = $key;
if ($value === null)
{
$values[] = "'$value'";
}
else
{
$value = mysql_real_escape_string($value . '');
$values[] = "'$value'";
}
}
$columns_s = implode(',', $columns);
$values_s = implode(',', $values);
$query = "INSERT INTO $table ($columns_s) VALUES ($values_s)";
$result = mysql_query($query);
if (!$result)
die(mysql_error());
return mysql_insert_id();
}

Reason is you are outputing things, so you have a notice : "Headers already sent".
If you remove the "echo" stuff, you'll be alright :
if ($add_article)
{
header('Location: /index.php?article_added=1');
}

Related

Calling Stored Procedure inside foreach PHP Codeigniter

I'm having an error when calling stored procedure inside foreach
It says "Commands out of sync you can't run this command now" .
I already looking for solution, but the result is not like i'm expecting.
This is my code
$query = "CALL PROCEDURE_HEAD()";
$sql = $this->db->query($query)->result_array();
foreach($sql as $key) {
$name = $key['name'];
$array['name'] = $name;
$array['data'] = $key['data'];
$query2 = "CALL PROCEDURE_CHILD('$name')";
$sql2 = $this->db->query($query2)->result_array();
foreach($sql2 as $value) {
$array['child'] = array(
'child_name' => $value['child_name'],
'child_data' => $value['child_data']
);
}
}
i have tried run codeigniter : Commands out of sync; you can't run this command now, and because i'm using Procedure after Procedure,it doesn't run.
Any kind of help is really appreciated
Use Model with associate this
In Controller
$head = $this->Model_name->call_head();
foreach($head as $item) {
$name = $item['name'];
$array['name'] = $name;
$array['data'] = $item['data'];
$child = $this->Model_name->call_child($name);
foreach($child as $value) {
$array['child'] = array(
'child_name' => $value['child_name'],
'child_data' => $value['child_data']
);
}
}
In model
public function call_head()
{
$query = "CALL PROCEDURE_HEAD()";
$result = $this->db->query($query)->result_array();
$query->next_result();
$query->free_result();
return $result;
}
public function call_child($name)
{
$query = "CALL PROCEDURE_CHILD($name)";
$result = $this->db->query($query)->result_array();
$query->next_result();
$query->free_result();
return $result;
}

output and call array from class function (rollingcurl)

Excuse my English, please.
I use Rollingcurl to crawl various pages.
Rollingcurl: https://github.com/LionsAd/rolling-curl
My class:
<?php
class Imdb
{
private $release;
public function __construct()
{
$this->release = "";
}
// SEARCH
public static function most_popular($response, $info)
{
$doc = new DOMDocument();
libxml_use_internal_errors(true); //disable libxml errors
if (!empty($response)) {
//if any html is actually returned
$doc->loadHTML($response);
libxml_clear_errors(); //remove errors for yucky html
$xpath = new DOMXPath($doc);
//get all the h2's with an id
$row = $xpath->query("//div[contains(#class, 'lister-item-image') and contains(#class, 'float-left')]/a/#href");
$nexts = $xpath->query("//a[contains(#class, 'lister-page-next') and contains(#class, 'next-page')]");
$names = $xpath->query('//img[#class="loadlate"]');
// NEXT URL - ONE TIME
$Count = 0;
$next_url = "";
foreach ($nexts as $next) {
$Count++;
if ($Count == 1) {
/*echo "Next URL: " . $next->getAttribute('href') . "<br/>";*/
$next_link = $next->getAttribute('href');
}
}
// RELEASE NAME
$rls_name = "";
foreach ($names as $name) {
$rls_name .= $name->getAttribute('alt');
}
// IMDB TT0000000 RLEASE
if ($row->length > 0) {
$link = "";
foreach ($row as $row) {
$tt_info .= #get_match('/tt\\d{7}/is', $doc->saveHtml($row), 0);
}
}
}
$array = array(
$next_link,
$rls_name,
$tt_info,
);
return ($array);
}
}
Output/Return:
$array = array(
$next_link,
$rls_name,
$tt_info,
);
return ($array);
Call:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
function get_match($regex, $content, $pos = 1)
{
/* do your job */
preg_match($regex, $content, $matches);
/* return our result */
return $matches[intval($pos)];
}
require "RollingCurl.php";
require "imdb_class.php";
$imdb = new Imdb;
if (isset($_GET['action']) || isset($_POST['action'])) {
$action = (isset($_GET['action'])) ? $_GET['action'] : $_POST['action'];
} else {
$action = "";
}
echo " 2222<br /><br />";
if ($action == "most_popular") {
$popular = '&num_votes=1000,&production_status=released&groups=top_1000&sort=moviemeter,asc&count=40&start=1';
if (isset($_GET['date'])) {
$link = "https://www.imdb.com/search/title?title_type=feature,tv_movie&release_date=,".$_GET['date'].$popular;
} else {
$link = "https://www.imdb.com/search/title?title_type=feature,tv_movie&release_date=,2018".$popular;
}
$urls = array($link);
$rc = new RollingCurl([$imdb, 'most_popular']); //[$imdb, 'most_popular']
$rc->window_size = 20;
foreach ($urls as $url) {
$request = new RollingCurlRequest($url);
$rc->add($request);
}
$stream = $rc->execute();
}
If I output everything as "echo" in the class, everything is also displayed. However, I want to call everything individually.
If I now try to output it like this, it doesn't work.
$stream[0]
$stream[1]
$stream[3]
Does anyone have any idea how this might work?
Thank you very much in advance.
RollingCurl doesn't do anything with the return value of the callback, and doesn't return it to the caller. $rc->execute() just returns true when there's a callback function. If you want to save anything, you need to do it in the callback function itself.
You should make most_popular a non-static function, and give it a property $results that you initialize to [] in the constructor.. Then it can do:
$this->results[] = $array;
After you do
$rc->execute();
you can do:
foreach ($imdb->results as $result) {
echo "Release name: $result[1]<br>TT Info: $result[2]<br>";
}
It would be better if you put the data you extracted from the document in arrays rather than concatenated strings, e.g.
$this->$rls_names = [];
foreach ($names as $name) {
$this->$rls_names[] = $name->getAttribute('alt');
}
$this->$tt_infos = [];
foreach ($rows as $row) {
$this->$tt_infos[] = #get_match('/tt\\d{7}/is', $doc->saveHtml($row), 0);
}
$this->next_link = $next[0]->getAttribute('href'); // no need for a loop to get the first element of an array

Wrong parameter count for bind_param in custom mysqli class

Trying to generate a custom mysqli class / wrapper with $this->_mysqli as a mysqli instance:
// Query string generator
private function gen_query($type, $data, $table){
switch ($type) {
case 'ins':
$query = "INSERT INTO " .$table .' ';
$query .= implode_key($opr= ', ', $data);
$query .= " VALUES " . value($data);
break;
case 'select':
// yet to generate
default:
$query ='';
break;
}
return $query;
}
// Generates bind parameters
private function gen_param($data){
$_param = "'";
foreach ($data as $v) {
$_param .= $this->detect_type($v);
}
$_param .= "', ";
foreach ($data as $k=>$v) {
if($v == end($data)) {
$_param .="$$k";
continue;
}
$_param .= "$$k, ";
}
return $_param;
}
public function insert( $table, $data ){
$table = $this->_prefix . $table;
$table = $this->escape($table);
$query = $this->gen_query('ins', $data, $table);
$stmt = $this->_mysqli->prepare($query);
foreach ($data as $key => $value) {
$$key = $value;
}
$test = $this->gen_param($data);
if(!$stmt->bind_param($test)) {
echo $this->_mysqli->error;
}
if($stmt->execute()){
print 'Success!'.'<br />';
} else {
die('Error : ('. $this->_mysqli->errno .') '. $this->_mysqli->error);
}
}
So when user inputs
$data = [ 'first_name' => 'foo', 'last_name' => 'bar', 'another_field' => 'blah'];
$db->insert('t1', $data);
I get this error:
Warning: Wrong parameter count for mysqli_stmt::bind_param() in path\to\class-db.php on line 138
This is line 138: if(!$stmt->bind_param($test))
Not sure why the question was downvoted. Anyways, I got this fixed by referring: this repo.
We'll need to get rid of gen_param, use an array instead and call using a callback function to get the parameter values right and refer the values.
The code is now:
public function insert( $table, $data ){
$table = $this->_prefix . $table;
$table = $this->escape($table);
$this->esc_sql_arr($data);
$query = $this->gen_query('ins', $data, $table);
$stmt = $this->_mysqli->prepare($query);
$this->_bind_param($data);
call_user_func_array(array($stmt, 'bind_param'),$this->return_ref($this->bind_arr));
if($stmt->execute()){
echo "Success!";
}else{
die('Error : ('. $this->_mysqli->errno .') '. $this->_mysqli->error);
}
$this->reset();
}
private function _bind_param($data){
foreach($data as $key=>$value) {
$this->_bind_values($value);
}
}
private function _bind_values($value) {
$this->bind_arr[0] .= $this->detect_type($value);
array_push($this->bind_arr, $value);
}
protected function return_ref(array &$arr)
{
//Reference in the function arguments are required for HHVM to work
//https://github.com/facebook/hhvm/issues/5155
//Referenced data array is required by mysqli since PHP 5.3+
if (strnatcmp(phpversion(), '5.3') >= 0) {
$refs = array();
foreach ($arr as $key => $value) {
$refs[$key] = & $arr[$key];
}
return $refs;
}
return $arr;
}
The code is nowhere near complete, but this got me started.

Entity metadata wrapper

i'm getting error with metadata wrapper.
i have a field test => entity reference multiple which is a selection list.I get the following Error EntityMetadataWrapperException : Invalid data value given. Be sure it matches the required data type and format.
$account = entity_load_single('user', $user->uid);
$acc_wrapper = entity_metadata_wrapper('user', $account);
$list = $acc_wrapper->test->value();
$exists = FALSE;
if (!empty($list)) {
foreach ($list as $item) {
if ($item->nid == $form_state['storage']['node']->nid) {
$exists = TRUE;
break;
}
}
}
if (!$exists) {
if (!$list) {
$list = array();
$list[] = $form_state['storage']['node']->nid;
}
$acc_wrapper->test->set($list);
$acc_wrapper->save();
1rst quick tips
$account = entity_load_single('user', $user->uid);
$acc_wrapper = entity_metadata_wrapper('user', $account);
You don't need to load the entity unless you need it loaded after (Or it's already loaded). All you need is the id, and let entity_metadata_wrapper magic operate.
$acc_wrapper = entity_metadata_wrapper('user', $user->uid);
I think your error is here
if (!$list) {
$list = array();
$list[] = $form_state['storage']['node']->nid;
}
$list is always initiated because of "$list = $acc_wrapper->test->value();", so you never fullfill the condition, and then you are trying to set it back and save it (because you are missing a '}' )... Makes no sense...
Could try this version ?
$acc_wrapper = entity_metadata_wrapper('user', $user->uid);
$list = $acc_wrapper->test->value();
$exists = FALSE;
if (!empty($list)) {
foreach ($list as $item) {
if ($item->nid == $form_state['storage']['node']->nid) {
$exists = TRUE;
break;
}
}
}
if (!$exists && !$list) {
$list = array($form_state['storage']['node']->nid);
$acc_wrapper->test = $list;
$acc_wrapper->save();
}

does in_array() not allow duplicates?

Alright, so i've got this code here (it's from a class)
function getResourceXML($id)
{
$xml = simplexml_load_file('resources.xml');
$array = array();
foreach($xml->catagory->resource as $children)
{
if(in_array($children['id'], $id))
{
array_push( $array, (string)$children['income'] );
}
print_r($array);
echo '<br />';
}
return $array;
}
function getResourceMultiplier()
{
$sql = "SELECT resourceArray FROM starinformation WHERE starOwner = :uid";
$que = $this->db->prepare($sql);
$que->bindParam('uid', $this->uid);
$resource = array();
try
{
$que->execute();
while($row = $que->fetch(PDO::FETCH_BOTH))
{
array_push($resource, $row[0]);
}
$resource = $this->getResourceXML($resource);
return $resource;
}
catch(PDOException $e) {}
}
I had to alter it after I realized my live server is php 4 instead of 5. It was working until i got ride of all the $array[] elements. now the array_push isn't inserting duplicate entries (at least I think that's what is going on)

Categories