encodejson is not giving proper format of json - json

if ($tag == 'get_rajkot')
{
$data=$db->get_rajkot();
if($data!=false)
{
$valueresult=array();
foreach ($data as $value)
{
$valueresult=$value;
echo json_encode($valueresult);
}
}
else
{
// failed to store
$response["error"] = 1;
$response["error_msg"] = "Error occured..No get_headlines image found...";
echo json_encode($response);
}
}
db_function.php
public function get_rajkot()
{
$result = mysql_query("SELECT * FROM wp_term_relationships join wp_posts where ID=`object_id` and term_taxonomy_id=19 ORDER BY object_id DESC LIMIT 10") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0)
{
$rows = array();
while($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
//print_r($rows);
}
return $rows;
}
else
{
// profile not found
return false;
}
}
Result:
It's not giving comma between two objects and brakets [] at the start and at the end.

set my sql char set after mysql_connect query like this...
this problem was occurring due to Gujarati font
$con = mysql_connect($host,$username,$password) or die(mysql_error());
mysql_set_charset('utf8mb4',$con);

Related

sql statement with where clause in function

I have written a function that will query the database. The sql statement includes a where clause. However, I keep getting this error
"Message: odbc_exec(): SQL error: [Microsoft][ODBC SQL Server
Driver][SQL Server]Invalid column name 'home'., SQL state S0022 in
SQLExecDirect".
The column name should be banner_category while "home_banner) is the value.
How should I go about achieving it?
public function get_landing_banners()
{
$query = $this->db->query(
'SELECT *
FROM o2o_banner
WHERE banner_category='home_banner'');
$data = array();
foreach ($query->result_array() as $row)
{
$data[] = $row;
}
return $data;
}
If you want to return an array try this:
public function get_landing_banners()
{
$this->db->select('*')->from('o2o_banner')->where('banner_category', 'home_banner');
$q = $this->db->get();
if ($q->num_rows() > 0) {
return $q->result_array();
}
}
Try this coding
public function get_landing_banners()
{
$query = $this->db->query(
'SELECT *
FROM o2o_banner
WHERE banner_category="home_banner"');
$data = array();
foreach ($query->result_array() as $row)
{
$data[] = $row;
}
return $data;
}

Find how many times every word is repeated in db

Am using drupal to manage my content. I want to search all my contents title and body and find how many times each word is repeated in the whole contents.
It may be by an sql query, but I have no experience with sql.
Any ideas?
This code searches the body field and ALL fields of ANY Content Types for a specific string. You can run it via command line. Say you save it as "fieldsearch.php", you can then run it as:
php fieldsearch.php "myStringForWhichToSearch"
You need to fill in your connection data and database name. It outputs the array of matching nodes but you can format that output into anything you'd like (I recommend csv).
<?php
//Set Parameters here
$env = "dev"; // Options [dev|prod] - Defaults to dev
$prodConnection = array(
"host" => "",
"user" => "",
"pass" => ""
);
$devConnection = array(
"host" => "",
"user" => "",
"pass" => ""
);
//Use the selected env settings
if($env == "prod"){
$connection = $prodConnection;
} else {
$connection = $devConnection;
}
function getTables($con, $database){
//Get the set of field tables
$sql = "SHOW TABLES FROM $database";
$result = mysqli_query($con, $sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
$tables = array();
while ($row = mysqli_fetch_row($result)) {
$tables[] = $row[0];
}
mysqli_free_result($result);
return $tables;
}
function getFieldTables($con,$database){
$allTables = getTables($con, $database);
$fieldTables = array();
foreach($allTables as $key => $table){
if( isFieldTable($table) ){
$fieldTables[] = $table;
}
}
//add the common tables
$fieldTables[] = "field_data_body";
$fieldTables[] = "field_data_comment_body";
return $fieldTables;
}
function isFieldTable($table){
//echo $table . "\n";
if( stripos($table, "field_data_field") !== FALSE){
return TRUE;
}
}
//Set the search term here:
if (array_key_exists(1, $argv)) {
$searchString = $argv[1];
}
else {
die('usage: php fieldsearch.php "search string"' . "\n");
}
$databaseName = "myDatabaseName";
$outArray = array();
//Connect
$con=mysqli_connect($connection['host'],$connection['user'],$connection['pass'],$databasePrefix.$databaseNum);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//getFieldTables
$fieldTables = getFieldTables($con, $databaseName);
//Query each field tables data for the string in question
foreach($fieldTables as $key => $table){
//get Field value column name
$valueCol = str_replace("field_data_field_", '', $table);
$result = mysqli_query($con,"SELECT
entity_id
FROM
$table
WHERE
field_" . $valueCol . "_value
LIKE
'%$searchString%';");
if($result){
while($row = mysqli_fetch_assoc($result)){
$dataArray[$table][$row['entity_id']]['nid'] = $row['entity_id'];
}
}
}
//Add the body table
$result = mysqli_query($con,"SELECT
entity_id
FROM
field_data_body
WHERE
body_value
LIKE
'%$searchString%';");
if($result){
while($row = mysqli_fetch_assoc($result)){
$dataArray['field_data_body'][$row['entity_id']]['nid'] = $row['entity_id'];
}
}
var_dump($dataArray);

Getting json_encode(): type is unsupported, encoded as null

I am working on web services where am using json_encode() to send my response .
It is working fine for every ther web service but I am getting json_encode(): type is unsupported, encoded as null for the following code only.
public function getjobdetailsAction()
{
$this->_helper->layout ()->disableLayout ();
$this->_helper->viewRenderer->setNoRender ( true );
$handle = fopen ( 'php://input', 'r' );
$jsonInput = fgets ( $handle );
$params = Zend_Json::decode ( $jsonInput );
if($params['user_id'] != "" && $params["job_id"] != "")
{
$job_id = $params["job_id"];
$jobObj=Extended\job::getRowObject( $job_id );
//check if job obj exist only then send job array to view.
if($jobObj)
{
$job_detail_r = array();
$job_detail_r['job_id'] = $job_id;
$job_detail_r['job_created_by'] = $jobObj->getIlookUser()->getId();
$job_detail_r['job_title'] = $jobObj->getJob_title();
$job_detail_r['url_fields'] = $jobObj->getUrl_fields();
$job_detail_r['job_reference'] = $jobObj->getJob_reference();
$job_detail_r['company_name'] = $jobObj->getCompany()->getName();
$job_detail_r['responsibilities'] = $jobObj->getResponsibilities();
$job_detail_r['industry_name'] = $jobObj->getIndustryRef()->getTitle();
$job_detail_r['skills_expertise'] = $jobObj->getSkills_n_expertise();
$job_detail_r['country'] = $jobObj->getCountryRef()->getName();
if( $jobObj->getState() )
{
$job_detail_r['state'] = $jobObj->getState()->getName();
}
else
{
$job_detail_r['state'] = "";
}
if($jobObj->getCity())
{
$job_detail_r['city'] = $jobObj->getCity()->getName();
}
else
{
$job_detail_r['city'] = "";
}
//$job_detail_r['job_function'] = $jobObj->getJobFunction()->getDescription();
$job_detail_r['job_description'] = $jobObj->getJob_description();
$job_detail_r['company_description'] = $jobObj->getCompany_desc();
if($jobObj->getSalaryRange())
{
$job_detail_r['salaryRange'] = $jobObj->getSalaryRange()->getCountryRef()->getCurrency_symbol()." ".$jobObj->getSalaryRange()->getMin_salary()." - ".$jobObj->getSalaryRange()->getMax_salary();
}
else
{
$job_detail_r['salaryRange'] = "";
}
$job_detail_r['jobType'] = $jobObj->getJobType()->getName();
//$job_detail_r['experienceLevel'] = $jobObj->getExperieneceLevel()->getMin_experience()." - ".$jobObj->getExperieneceLevel()->getMax_experience()." Years";
if($jobObj->getExperieneceLevel())
{
$job_detail_r['experienceLevel'] = $jobObj->getExperieneceLevel()->getDescription();
}
else
{
$job_detail_r['experienceLevel'] = "";
}
$job_detail_r['job_creator_image'] = Helper_common::getUserProfessionalPhoto( $jobObj->getIlookUser()->getId() );
$job_detail_r['time_of_post'] =$jobObj->getCreated_at()->format("Y-m-d H:i:s");
$job_detail_r['job_posted_by'] = $jobObj->getJob_posted_by();
$job_detail_r['apply_from'] = $jobObj->getApply_from();
if($jobObj->getJob_image() != "")
{
$job_detail_r['company_image'] = IMAGE_PATH."/jobs/".$jobObj->getJob_image();
}
else
{
$job_detail_r['company_image'] = IMAGE_PATH.'/no_image.png';
}
$job_detail_r['is_saved'] = Extended\saved_jobs::isJobSavedByMe($job_id,$params['user_id']);
$code = 200;
$msg = "Job details retrieved successfully";
$result = array("jobdetails"=>$job_detail_r);
}
else
{
$code = 301;
$msg = "Error in retrieving details";
}
}
else
{
$code = 301;
$msg = "Missing parameters";
}
echo Helper_common::successFailureMsgs($code,$msg,$result);
exit();
public static function successFailureMsgs( $code, $message, $result = array())
{
if($code == 200)
{
$result1 = array("Response"=>array("Code"=>$code,"Status"=>"OK","Message"=>$message,"result"=>$result));
}
else
{
$result1 = array("Response"=>array("Code"=>$code,"Status"=>"Error","Message"=>$message));
}
return Zend_Json::encode($result1);
}
In response I am getting correct response but the above error as well .
Please assist.
Thanks in advance.
For json_encode(), and therefore Zend_Json(), all types are accepted except resource.
So you have debbuger your table to see where the resource is located.
You can try something like this:
foreach ($job_detail_r as $k => $v){
if (is_resource($v))
echo $k . ' => ressource type = ' . get_resource_type($v);
}

Token field json syntax error bootstrap

I have around 700 product list in my Databse table.
I am using bootstrap's tokenfield for auotcomplete, i have to use auto complete in search textbox.
I am getting syntax error :
SyntaxError: missing ] after element list
...B','Lino Perros Men's Leather Wallet - Pink','Lenovo A269i','Lenovo S660 - Tita**
in console.
<?php $t = $this->general_model->auto_complete_sug(); ?>
$( document ).ready(function() {
$('#tokenfield-2').tokenfield({
autocomplete: {
source: <?=$t?>,
delay : 100
},
limit: 1,
minLength: 1,
showAutocompleteOnFocus: true
});
});
<input type="text" class="span2" name="search" id="tokenfield-2" placeholder="Search...">
In my model: I have created this functions:
public function auto_complete_sug()
{
$data = $this->auto_complete_token_fun();
$data1 = explode(',', $data);
$data1 = array_unique($data1);
foreach ($data1 as $value1) {
$temparr[] = $value1;
}
$str = '[';
$c = count($temparr);
$counter = 0;
foreach ($temparr as $val) {
$counter++;
$str .= "'".$val."'";
if($counter < $c){
$str .= ",";
}
}
$str .= ']';
return $str;
}
public function auto_complete_token_fun()
{
// $this->db->query("SET GLOBAL group_concat_max_len = 10000000");
$q = $this->db->query("SELECT GROUP_CONCAT( sub_category_name ) AS scname
FROM `tbl_subcategory` WHERE status = 'Active' ");
if($q->num_rows() > 0)
{
$d = $q->row_array();
return $d['scname'];
}
else
{
return '';
}
}
Please help!!

Registering user with PDO

I have a problem while processing the register
Here is the code for the function:
<?php
include $_SERVER['DOCUMENT_ROOT']. "/config/config.php";
$conn = new PDO('mysql:host=' . $ip . ';dbname=' . $database, $username, $password);
function registerUser($username, $password, $passwordagain, $email, $mcname)
{
$validusername= "/^[a-z0-9]+$/";
$validpassword= "/^[A-Za-z0-9]+$/";
$validemail= "/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/";
$validmcname= "/^[A-Za-z0-9]+$/";
$error = 0;
if(strlen($username)<4 || strlen($username)>24)
{
$error = 1;
}
if(strlen($password)<6 || strlen($password)>24)
{
$error = 1;
}
if(strlen($mcname)<4 || strlen($mcname)>24)
{
$error = 1;
}
if(!preg_match($validusername, $username))
{
$error = 1;
}
if(!preg_match($validpassword, $password))
{
$error = 1;
}
if(!preg_match($validemail, $email))
{
$error = 1;
}
if(!preg_match($validmcname, $mcname))
{
$error = 1;
}
if($password != $passwordagain)
{
$error = 1;
}
$userexistquery = $conn->query('SELECT * FROM users WHERE username=' . $username);
$userexist = $userexistquery->fetch();
if(count($userexist) != 0)
{
$error=1;
echo "<div class='erroralert'>Username already exists!</div>";
}
$emailexistquery = $conn->query('SELECT * FROM users WHERE email=' . $email);
$emailexist = $emailexistquery->fetch();
if($emailexist != 0)
{
$error=1;
echo "<div class='erroralert'>E-mail already exists!</div>";
}
if($error != 1)
{
$encryptedpassword = hash('sha512', $password);
$registeruser = $conn->query("INSERT INTO users(username, password, email, mcname) VALUES ('$username', '$encryptedpassword', '$email', '$mcname')");
echo "<div class='successalert'>Succesfully registred</div>";
}
else
{
echo "<div class='erroralert'>An error occured during registration.</div>";
}
}
?>
The error that gives me is:
Notice: Undefined variable: conn in C:\xampp\htdocs\functions\functions.php on line 45
Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\functions\functions.php on line 45
You instantiate your variable $conn outside of the function. You have to pass it as an argument in order to use it inside.