I want to set a ON DUPLICATE KEY UPDATE in this function.
How i can make this?
public function insert($table, $values) {
try {
foreach ($values as $key => $value)
$field_names[] = $key . ' = :' . $key;
$sql = "INSERT INTO " . $table . " SET " . implode(', ', $field_names);
$stmt = self::$PDO->prepare($sql);
foreach ($values as $key => $value)
$stmt->bindValue(':' . $key, $value);
$stmt->execute();
} catch (PDOException $exception) {
die($exception->getMessage());
}
}
Can someone help me please?
Thanks
Related
As a beginner ionic dev I really don't have enough knowledge about the back-end especially arrays. I hope you guys takes time to answer this.
register.php
<?php
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
require "dbconnect.php";
$data = file_get_contents("php://input");
if (isset($data)) {
$request = json_decode($data);
$firstname = $request->firstname;
$lastname = $request->lastname;
$username = $request->username;
$userrole = $request->userrole;
$userpass = $request->userpass;
}
$firstname = stripslashes($firstname);
$userpass = stripslashes($userpass);
$userpass = sha1($userpass."#la]#}^(dy*%-Ga=/,Ga!.");
$sql = "INSERT INTO useraccount (firstname, lastname, username, userrole, userpass)
VALUES ('$firstname', '$lastname', '$username', '$userrole', '$userpass')";
if ($con->query($sql) === TRUE) {
$status = "success";
$message = "New account created successfully";
}
else {
$status = "fail";
$message = "Error: " . $sql . "<br>" . $con->error;
}
echo json_encode(array('status' => $status, 'message' => $message, 'data' => $data));
?>
One of those variables in your VALUES clause ($userrole) is actually an array of values. You need to either select one of them:
VALUES ('$firstname', '$lastname', '$username', '$userrole[0]', '$userpass')";
or find some way to convert the array to a string e.g. using implode:
VALUES ('$firstname', '$lastname', '$username', '" . implode(',', $userrole) . "', '$userpass')";
I have added a drop down menu to my wordpress theme. I've got it installed and it works fine. However, now I would like to display the latest posts from each category in drop down menu. Can anyone help point me in the right direction.
an example of what I'm looking for
Here is the current code of my drop down menu
class CSS_Menu_Walker extends Walker {
var $db_fields = array('parent' => 'menu_item_parent', 'id' => 'db_id');
function start_lvl(&$output, $depth = 0, $args = array()) {
$indent = str_repeat("\t", $depth);
$output .= "\n$indent<ul>\n";
}
function end_lvl(&$output, $depth = 0, $args = array()) {
$indent = str_repeat("\t", $depth);
$output .= "$indent</ul>\n";
}
function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {
global $wp_query;
$indent = ($depth) ? str_repeat("\t", $depth) : '';
$class_names = $value = '';
$classes = empty($item->classes) ? array() : (array) $item->classes;
/* Add active class */
if (in_array('current-menu-item', $classes)) {
$classes[] = 'active';
unset($classes['current-menu-item']);
}
/* Check for children */
$children = get_posts(array('post_type' => 'nav_menu_item', 'nopaging' => true, 'numberposts' => 1, 'meta_key' => '_menu_item_menu_item_parent', 'meta_value' => $item->ID));
if (!empty($children)) {
$classes[] = 'has-sub';
}
$class_names = join(' ', apply_filters('nav_menu_css_class', array_filter($classes), $item, $args));
$class_names = $class_names ? ' class="' . esc_attr($class_names) . '"' : '';
$id = apply_filters('nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args);
$id = $id ? ' id="' . esc_attr($id) . '"' : '';
$output .= $indent . '<li' . $id . $value . $class_names .'>';
$attributes = ! empty($item->attr_title) ? ' title="' . esc_attr($item->attr_title) .'"' : '';
$attributes .= ! empty($item->target) ? ' target="' . esc_attr($item->target ) .'"' : '';
$attributes .= ! empty($item->xfn) ? ' rel="' . esc_attr($item->xfn ) .'"' : '';
$attributes .= ! empty($item->url) ? ' href="' . esc_attr($item->url ) .'"' : '';
$item_output = $args->before;
$item_output .= '<a'. $attributes .'><span>';
$item_output .= $args->link_before . apply_filters('the_title', $item->title, $item->ID) . $args->link_after;
$item_output .= '</span></a>';
$item_output .= $args->after;
$output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth, $args);
}
function end_el(&$output, $item, $depth = 0, $args = array()) {
$output .= "</li>\n";
}
}
This method uses the built-in wp_get_recent_posts function. All you need to do is copy and paste the following code in your theme’s functions.php file or a site-specific plugin.
function wpb_recentposts_dropdown() {
$string .= '<select id="rpdropdown">
<option value="" selected>Select a Post<option>';
$args = array( 'numberposts' => '5', 'post_status' => 'publish' );
$recent_posts = wp_get_recent_posts($args);
foreach( $recent_posts as $recent ){
$string .= '<option value="' . get_permalink($recent["ID"]) . '">' . $recent["post_title"].'</option> ';
}
$string .= '</select>
<script type="text/javascript"> var urlmenu = document.getElementById( "rpdropdown" ); urlmenu.onchange = function() {
window.open( this.options[ this.selectedIndex ].value, "_self" );
};
</script>';
return $string;
}
add_shortcode('rp_dropdown', 'wpb_recentposts_dropdown');
add_filter('widget_text','do_shortcode');
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.
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;
}
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()