mysql_num_rows() error - mysql

I am displaying an editable table in drupal with the following code
function _MYMODULE_sql_to_table($sql) {
$html = "";
// execute sql
$resource = db_query($sql);
// fetch database results in an array
$results = array();
while ($row = db_fetch_array($resource)) {
$results[] = $row;
$id = $row['id'];
$email = $row['email'];
$comment = $row['comment'];
// drupal_set_message('Email: '.$email. ' comment: '.$comment. ' id: '.$id);
}
// ensure results exist
if (!count($results)) {
$html .= "Sorry, no results could be found.";
return $html;
}
// create an array to contain all table rows
$rows = array();
// get a list of column headers
$columnNames = array_keys($results[0]);
// loop through results and create table rows
foreach ($results as $key => $data) {
// create row data
$row = array(
'edit' => l(t('Edit'),"admin/content/test/".$data['id']."/ContactUs", $options=array()),);
// loop through column names
foreach ($columnNames as $c) {
$row[] = array(
'data' => $data[$c],
'class' => strtolower(str_replace(' ', '-', $c)),
);
}
// add row to rows array
$rows[] = $row;
}
// loop through column names and create headers
$header = array();
foreach ($columnNames as $c) {
$header[] = array(
'data' => $c,
'class' => strtolower(str_replace(' ', '-', $c)),
);
}
// generate table html
$html .= theme('table', $header, $rows);
return $html;
}
// then you can call it in your code...
function _MYMODULE_some_page_callback() {
$html = "";
$sql = "select * from {contact3}";
$html .= _MYMODULE_sql_to_table($sql);
return $html;
}
However, I keep getting the mysql_num_rows() error as
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource. What is causing it?

Which version of Drupal are you using?
try db_affected_rows()
or db_num_rows()

Related

multiple array for json from one table

I've an review table in my database and same has been associated with the products on my website, however while posting the json encode i am unable to see multiple array through my code.
Please help me in updating the same.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$id = $_GET['id'];
require('adminpanel/includes/application_top.php');
$sql = "SELECT * FROM drug_reviewpage WHERE fld_product_id='" . $id . "'";
$r = mysql_query($sql);
$res = mysql_fetch_array($r);
$result = array();
array_push($result, array(
"fld_review_message" => $res['fld_review_message'],
"fld_fullname" => $res['fld_fullname'],
"fld_rate" => $res['fld_rate'],
"fld_date" => $res['fld_date']
));
echo json_encode(array("result"=>$result));
mysql_close($conection);
}
?>

wordpress json_decode is not working, I am trying to get value form wp_option table

When I am trying to decode JSON with this code the output is
ArrayArray ( [0] => )
I do not know why WordPress doesn't support this
<?php
global $wpdb;
$mylink = $wpdb->get_results( "SELECT option_value FROM wp_options WHERE option_id=62167", ARRAY_N );
$raw = stripslashes_deep($mylink);
$data = array();
foreach ($raw as $json) {
echo $json;
$item = #json_decode($json, true);
$data[] = $item;
print_r($data);
}
?>
Hello you need to unserealize the data first when your query get data from database,
That is serealized data and when we get it from db we need to unserealize it.
global $wpdb;
$mylink = $wpdb->get_results("SELECT option_value FROM wp_options WHERE option_id=1223",ARRAY_A);
$raw = stripslashes_deep($mylink);
$data = $raw[0]['option_value'];
$datas = unserialize($data);
foreach ($datas as $key => $value) {
print_r($value);
}

How can I restore a MySQL database from CakePHP model cache?

in app\tmp\cache\models there is a file called:
myapp_cake_model_default_mydb_users
The contents are:
1446583948
a:14:{s:2:"id";a:6:{s:4:"type";s:7:"integer";s:4:"null";b:0;s:7:"default";N;s:6:"length";i:11;s:8:"unsigned";b:0;s:3:"key";s:7:"primary";}s:8:"username";a:7:{s:4:"type";s:6:"string";s:4:"null";b:0;s:7:"default";N;s:6:"length";i:255;s:3:"key";s:5:"index";s:7:"collate";s:15:"utf8_general_ci";s:7:"charset";s:4:"utf8";}s:8:"password";a:6:{s:4:"type";s:6:"string";s:4:"null";b:1;s:7:"default";N;s:6:"length";i:255;s:7:"collate";s:15:"utf8_general_ci";s:7:"charset";s:4:"utf8";}s:17:"num_free_listings";a:5:{s:4:"type";s:7:"integer";s:4:"null";b:1;s:7:"default";s:1:"0";s:6:"length";i:2;s:8:"unsigned";b:0;}s:3:"pin";a:6:{s:4:"type";s:6:"string";s:4:"null";b:1;s:7:"default";N;s:6:"length";i:255;s:7:"collate";s:15:"utf8_general_ci";s:7:"charset";s:4:"utf8";}s:7:"is_ldap";a:4:{s:4:"type";s:7:"boolean";s:4:"null";b:0;s:7:"default";N;s:6:"length";i:1;}s:13:"ldap_username";a:6:{s:4:"type";s:6:"string";s:4:"null";b:1;s:7:"default";N;s:6:"length";i:255;s:7:"collate";s:15:"utf8_general_ci";s:7:"charset";s:4:"utf8";}s:8:"fullname";a:6:{s:4:"type";s:6:"string";s:4:"null";b:0;s:7:"default";N;s:6:"length";i:255;s:7:"collate";s:15:"utf8_general_ci";s:7:"charset";s:4:"utf8";}s:8:"group_id";a:5:{s:4:"type";s:7:"integer";s:4:"null";b:0;s:7:"default";s:1:"2";s:6:"length";i:11;s:8:"unsigned";b:0;}s:16:"password_changed";a:4:{s:4:"type";s:4:"date";s:4:"null";b:1;s:7:"default";N;s:6:"length";N;}s:10:"last_login";a:4:{s:4:"type";s:8:"datetime";s:4:"null";b:1;s:7:"default";N;s:6:"length";N;}s:6:"status";a:6:{s:4:"type";s:26:"enum('active','suspended')";s:4:"null";b:0;s:7:"default";s:6:"active";s:6:"length";i:9;s:7:"collate";s:15:"utf8_general_ci";s:7:"charset";s:4:"utf8";}s:7:"created";a:4:{s:4:"type";s:8:"datetime";s:4:"null";b:0;s:7:"default";N;s:6:"length";N;}s:8:"modified";a:4:{s:4:"type";s:8:"datetime";s:4:"null";b:0;s:7:"default";N;s:6:"length";N;}}
Can I convert this (serialized php?) to SQL and recreate my table, if so how? Many thanks in advance.
In PHP create a file:
<?php
class AppSchema extends CakeSchema {
public function before($event = array()) {
return true;
}
public function after($event = array()) {
}
$dir = 'files/';
$files = [
'table_names' => 'myapp_cake_model_default_mydb_tablenames',
];
foreach ($files as $table => $file){
$content = file(realpath( $dir.$file ));
$content = unserialize($content[1]);
$info = null;
foreach ($content as $field => $prop){
$info .= "'$field' => array(";
foreach ($prop as $key => $value){
$info .= "'$key' => ";
if($key == 'null'){
$info .= empty($value)?'false':'true';
}elseif($key == 'default'){
$info .= empty($value)?'null':"'$value'";
}elseif($key == 'unsigned'){
$info .= empty($value)?'false':'true';
}else{
$info .= empty($value)?"''":"'$value'";
}
$info .= ", ";
}
$info .= "),\n";
}
echo "public $".$table." = array(
".$info."'indexes' => array(
'PRIMARY' => array('column' => 'id', 'unique' => 1),
),
'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB')
);\n\n";
}
?>
}
Then run it in the browser and you should get some code to paste a the schema.php file. Then use the Cake console to create the tables in the MySQL database.

Data form models is not shown in controller even if exist (Yii 2.0.6)

I have this peace of code in my controller where I want to echo on the screen the JSON result for the data in the model:
public function actionIndex()
{
$searchModel = new TestTableSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
var_dump($dataProvider->getModels());
echo json_encode([
"searchModel" => $searchModel,
"getCount" => $dataProvider->getCount(),
"dataProvider" => $dataProvider->models
]);
}
So $dataProvider actually is not empty and it contains the data (which can be seen from var_dump() command), but the data are not returned as I'm expecting.
Even $dataProvider->getCount() is returning that there are two entries. This is the output that I got: http://prntscr.com/8hcel9.
I'm interested in showing the dataProvider part, where the items in array should not be empty.
You need to convert the object to array
try this way :
use yii\helpers\ArrayHelper;
......
public function actionIndex()
{
$searchModel = new TestTableSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
var_dump($dataProvider->getModels());
echo json_encode([
"searchModel" => $searchModel,
"getCount" => $dataProvider->getCount(),
"dataProvider" => ArrayHelper::toArray($dataProvider->models), // object to Array
]);
}
This has not much to do with Yii. It's just a PHP problem. You can solve it like this (according to this):
echo "<pre>";
echo json_encode([
"searchModel" => json_readable_encode($searchModel),
"getCount" => $dataProvider->getCount(),
"dataProvider" => json_readable_encode($dataProvider->models)
]);
echo "</pre>";
function json_readable_encode($in, $indent = 0, $from_array = false) {
$_myself = __FUNCTION__;
$_escape = function ($str) {
return preg_replace("!([\b\t\n\r\f\"\\'])!", "\\\\\\1", $str);
};
$out = '';
foreach ($in as $key => $value) {
$out .= str_repeat("\t", $indent + 1);
$out .= "\"" . $_escape((string)$key) . "\": ";
if (is_object($value) || is_array($value)) {
$out .= "\n";
$out .= $_myself($value, $indent + 1);
} elseif (is_bool($value)) {
$out .= $value ? 'true' : 'false';
} elseif (is_null($value)) {
$out .= 'null';
} elseif (is_string($value)) {
$out .= "\"" . $_escape($value) . "\"";
} else {
$out .= $value;
}
$out .= ",\n";
}
if (!empty($out)) {
$out = substr($out, 0, -2);
}
$out = str_repeat("\t", $indent) . "{\n" . $out;
$out .= "\n" . str_repeat("\t", $indent) . "}";
return $out;
}

Convert MySQL to pdo statement with json

I am having an issue with getting this working with PDO not sure how to do it. I tried but kept getting an error. I will keep trying to figure it out. If anyone can point me in the write direction would be a big help
/** Function to Add Product **/
function add_product() {
$data = json_decode(file_get_contents("php://input"));
$prod_name = $data->prod_name;
$prod_desc = $data->prod_desc;
$prod_price = $data->prod_price;
$prod_quantity = $data->prod_quantity;
print_r($data);
$qry = 'INSERT INTO product (prod_name,prod_desc,prod_price,prod_quantity) values ("' . $prod_name . '","' . $prod_desc . '",' .$prod_price . ','.$prod_quantity.')';
$qry_res = mysql_query($qry);
if ($qry_res) {
$arr = array('msg' => "Product Added Successfully!!!", 'error' => '');
$jsn = json_encode($arr);
// print_r($jsn);
}
else {
$arr = array('msg' => "", 'error' => 'Error In inserting record');
$jsn = json_encode($arr);
// print_r($jsn);
}
}
/** Function to Get Product **/
function get_product() {
$qry = mysql_query('SELECT * from product');
$data = array();
while($rows = mysql_fetch_array($qry))
{
$data[] = array(
"id" => $rows['id'],
"prod_name" => $rows['prod_name'],
"prod_desc" => $rows['prod_desc'],
"prod_price" => $rows['prod_price'],
"prod_quantity" => $rows['prod_quantity']
);
}
print_r(json_encode($data));
return json_encode($data);
}
what I tried and I get no data inserting
/** Function to Add Product **/
function add_product() {
$data = json_decode(file_get_contents("php://input"));
$prod_name = $data->prod_name;
$prod_desc = $data->prod_desc;
$prod_price = $data->prod_price;
$prod_quantity = $data->prod_quantity;
print_r($data);
$qry = "INSERT INTO product (prod_name,prod_desc,prod_price,prod_quantity) VALUES (:prod_name,:prod_desc,:prod_price,:prod_quantity)";
$q = $conn->prepare($qry);
$q->execute(array(':prod_name'=>$prod_name,
':prod_desc'=>$prod_desc,
':prod_price'=>$prod_price,
':prod_quantity'=>$prod_quantity,
));
$qry_res = mssql_query($qry);
if ($qry_res) {
$arr = array('msg' => "Product Added Successfully!!!", 'error' => '');
$jsn = json_encode($arr);
// print_r($jsn);
}
else {
$arr = array('msg' => "", 'error' => 'Error In inserting record');
$jsn = json_encode($arr);
// print_r($jsn);
}
}
db setup
<?php
/****** Database Details *********/
$host = "localhost";
$user = "root";
$pass = "";
$database = "shopping";
$con = mysql_connect($host,$user,$pass);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
//echo 'Connected successfully';
mysql_select_db($database,$con);
/*******************************/
?>