I'm not even sure if this is possible, but essentially I want to have a function stored within my MySQL database, so here I have my database
Database->pages:
[id] [name ] [content ] [enabled] [main] [parent]
[6 ] [login] [login();] [1 ] [0 ] [5 ]
Now I'll have the set returned
public function viewPage() {
global $db;
$query = <<<SQL
SELECT content
FROM pages
WHERE id = :getid
SQL;
$resource = $db->sitedb->prepare( $query );
$resource->execute( array (
':getid' => $_GET['id'],
));
foreach($resource as $row){
echo $row['content'];
}
}
Last but not least I have my viewPage.php page that has
$static->viewPage();
So when I go to viewPage.php?id=6 I want it to pull the data and since content is login(); I want it to call the login(); function which would be translated into an include file. Is this even possible?
You can use variable functions to achieve this effect. We would need to verify that the function is_callable beforehand.
Let's say we get a row back with the field name set to login. You can do this:
if( is_callable($row['name']) )
$row['name']();
This will call the function login. You can also pass parameters if you want, as you would any other function.
Related
I have two PHP arrays in a section of a website I'm building for a class. One contains data that I created with a simple foobar array bit, and the other is created from a fetchAll() PDO call. I can't access the PDO array's element for some reason, so I created a sample array and called var_export() on both arrays to see if there were any differences. Here is the code:
if ($dao->userExistsLogin($_POST["email"], $_POST["password"]))
{
$useremail = $_POST["email"];
$_SESSION["authenticated"] = "true";
$logger->LogDebug("email from post array in login handler: " . $_POST["email"]);
$user_results = $dao->getIDFromEmail($useremail);
$logger->LogDebug(print_r($user_results, true));
$array = [
"foo" => "bar",
"bar" => "foo",
];
$logger->LogDebug(var_export($array, true));
$logger->LogDebug(var_export($user_results, true));
$logger->LogDebug(gettype($user_results));
$_SESSION['user_id'] = $user_results['id'];
header("Location: http://localhost/WIWO/user_account.php");
}
The GetIDFromEmail function is here:
public function getIDFromEmail($email)
{
$conn = $this->getConnection();
$getIDFromEmailQuery = "SELECT * FROM user WHERE email=:email";
$query = $conn->prepare($getIDFromEmailQuery);
$query->bindParam(":email", $email);
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
$this->logger->LogDebug(print_r($result, true));
return $result;
}
And here's what's in my logger from the var_export() commands:
2020-10-31 17:57:10 - DEBUG --> array (
'foo' => 'bar',
'bar' => 'foo',
)
2020-10-31 17:57:10 - DEBUG --> array (
0 =>
array (
'id' => '251',
'email' => 'heck',
'institution' => 'heck',
'access' => '1',
),
)
Why can I not access the second array at $_SESSION['user_id'] = $user_results['id'];? For some reason that line totally fails to do anything. I know the session is started and correct because other variables stored in the SESSION superglobal are showing up correctly, but the user_id never gets set. Does it have something to do with "0 =>" showing up in the var_export() of the second array? I notice that doesn't show up in the first array - is the second array malformed or something?
You're using PDOStatement::fetchAll(), which will always return an array of rows. Instead you might want to use PDOStatement::fetch() which will return precisely one row.
I haven't seen the userExistsLogin() method, but you could probably simplify your code if you have that method return the user id on success, and something falsey (e.g. 0, FALSE or NULL) on error. This will not only reduce code complexity, but it will reduce database load as well.
i am trying to call m custom function repeatedly with same or different parameters value,inside foreach loop parameters depending upon value to key provided my foreach.
foreach ($result as $r) {
if($r->marks1==null || $r->marks2==null)
{
echo $r->p_code;
$toUpdate=$this->getResult($username,$r->p_code);
print_r($toUpdate);
}
}
but when i am printing the latest query result i am getting $toUpdate get appended by latest parameter query.
Array
(
[query] => select * from `result` where (`studentid` = ?) and `studentid` = ? and `ccode` = ? and `a_no` = ? order by `date` desc limit 1
[bindings] => Array
(
[0] => XYZ
[1] => XYZ
[2] => course123code
[3] => 12321
)
[time] => 0.18
)
my user name getting same, while course code is get overrides while finding second result.
i want to get the result getResult() inside foreach loop so that it may give the related result for different parameters value.
public function getLatestResult($username,$course_code)
{
$user=new User;
$currentDetailOfUser=$this->userCurrentDetail($username);
$userdetail=json_decode($currentDetailOfUser,true);
$username =$userdetail['username'];
$studentid =$userdetail['userid'];
$studentBatch =$userdetail['batch'];
$programCode =$userdetail['programCode'];
$activeSemester =$userdetail['activesemester'];
$condition_key=array(
'studentid' =>$studentid
);
$getCurrentResult1 =$user->getDetail('student_result',$condition_key);
$getCurrentResult2 =$user->getDetail('student_result',$condition_key);
$resultAssessment1=$getCurrentResult1->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',1)->orderBy('date','Desc')->limit(1)->get();
$resultAssessment2=$getCurrentResult2->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',2)->orderBy('date','Desc')->limit(1)->get();
$recentResult=array_merge($resultAssessment1,$resultAssessment2);
return $recentResult;
}
This is a bad practice if you are fetching data from db inside the foreach loop.
BTW you can do this by keeping all new result in same array by index its some unique value, it will be look like this-
$toUpdate=array();
foreach ($result as $r) {
if($r->marks1==null || $r->marks2==null)
{
echo $r->p_code;
$toUpdate[$r->p_code]=$this->getResult($username,$r->p_code); // added $r->p_code as index to Array - $toUpdate
}
}
print_r($toUpdate); // this will give all the related result according your parameters
[UPDATE]
Try using unset($yourarray) for your next request these array will be new and they assign the new value each time -
public function getLatestResult($username,$course_code)
{
$user=new User;
$currentDetailOfUser=$this->userCurrentDetail($username);
$userdetail=json_decode($currentDetailOfUser,true);
$username =$userdetail['username'];
$studentid =$userdetail['userid'];
$studentBatch =$userdetail['batch'];
$programCode =$userdetail['programCode'];
$activeSemester =$userdetail['activesemester'];
$condition_key=array(
'studentid' =>$studentid
);
$getCurrentResult1 =$user->getDetail('student_result',$condition_key);
$getCurrentResult2 =$user->getDetail('student_result',$condition_key);
$resultAssessment1=$getCurrentResult1->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',1)->orderBy('date','Desc')->limit(1)->get();
$resultAssessment2=$getCurrentResult2->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',2)->orderBy('date','Desc')->limit(1)->get();
unset($currentDetailOfUser);
unset($userdetail);
unset($condition_key);
unset($recentResult);
$recentResult=array_merge($resultAssessment1,$resultAssessment2);
return $recentResult;
}
Hope this can help you.
I am trying to pass the post ids to the function's query->set and function will return the posts.
add_action( 'pre_get_posts', 'query_booked_posts' );
function query_booked_posts( $query ) {
if ( $condition ) { //the condition
if ( is_home() && $query->is_main_query() )
$results = $wpdb->get_col($wpdb->prepare( "SELECT booked_id FROM $wpdb->userbooking WHERE userid = %d",$current_user_id));
foreach($results as $result){
$results_separated = $result.',';
}
$query->set ('post__in', array($results_separated)); // pass results (post ids) to post__in
return $query;
}
}
After this, the function returns nothing.
If I do $query->set ('post__in', array(45,121));, the query will return the posts of id 45 and id 121, so the query works fine.
But I want to make $results_separated pass the post ids like 45,121,132 to the query, and then $query->set ('post__in', array($results_separated)); will work correctly.
How can I make this happen?
pre_get_posts reference
I guess you have actually a PHP problem. When you do array($results_separated) you're basically creating an array from a string that looks like this: "12,114,56,". By doing that, PHP is creating an array like this:
array(
0 => "12,114,56,"
)
And obviously WordPress cannot find any posts with such ID! What you want is actually an array like this:
array(
0 => "12",
1 => "114",
2 => "56"
)
And actually that's what get_col() returns, so you just need to pass $results to set() function:
$query->set ( 'post__in', $results );
EDIT: Actually I realised that your problem is when you call $wpdb->get_col(...), because it's interfering with the $query you will execute later on... Those variables are using some other global variables that probably get overriden, and that's why you're not getting any results...
Except the extra array() over $results_separated, in my case I had to apply
if (!$query->is_main_query()) {
return $query;
}
at the top of my function (found it in, otherwise, queries inside would be executed for several times and not properly.
Comments in the answer helped me to figure this out.
I usually save itens status within a code (let's save I have the table: students, to save studentes status, I use the field (students.status)).
But, Everytime I list Users I will not shown the status code (1 or 0 for example). I need show: Registered or Cancelled.
I can simply check it when I list, but, let's say I need do it a lot of times.
Is there anything than can help me doing it? would save a lot of work, every page I'll list the user, or even when I add/edit him or a drop-down menu that should come with those items.
I've checked the models associations, but the solution that I've found works if I have another table with user status saved for example (I honestly don't wanna create it).
Thanks.
This describes how to do what you want: http://www.dereuromark.de/2010/06/24/static-enums-or-semihardcoded-attributes/
If the status can be registered or cancelled then you can use enum data type in your table schema.
You can get the list of status from enum data type for populating drop down like this.
$status = $this->Model->getEnumValues('status');
Before this you need to add following code in your appModel.php
function getEnumValues($columnName=null)
{
if ($columnName==null) { return array(); } //no field specified
//Get the name of the table
$db =& ConnectionManager::getDataSource($this->useDbConfig);
$tableName = $db->fullTableName($this, false);
//Get the values for the specified column (database and version specific, needs testing)
$result = $this->query("SHOW COLUMNS FROM {$tableName} LIKE '{$columnName}'");
//figure out where in the result our Types are (this varies between mysql versions)
$types = null;
if ( isset( $result[0]['COLUMNS']['Type'] ) ) { $types = $result[0]['COLUMNS']['Type']; } //MySQL 5
elseif ( isset( $result[0][0]['Type'] ) ) { $types = $result[0][0]['Type']; } //MySQL 4
else { return array(); } //types return not accounted for
//Get the values
$values = explode("','", preg_replace("/(enum)\('(.+?)'\)/","\\2", $types) );
//explode doesn't do assoc arrays, but cake needs an assoc to assign values
$assoc_values = array();
foreach ( $values as $value ) {
//leave the call to humanize if you want it to look pretty
$assoc_values[$value] = Inflector::humanize($value);
}
return $assoc_values;
}
I hope this will work for you. Thanks
I ended up creating a Helper function for that (not sure if the best way, it's been working fine)
MyHelper.php
class MyHelper extends AppHelper {
public $helpers = array();
public $list = array(0 => 'Cancelled', 1 => 'Registered');
public function __construct(View $View, $settings = array()) {
parent::__construct($View, $settings);
}
public function beforeRender($viewFile) {
}
public function afterRender($viewFile) {
}
public function beforeLayout($viewLayout) {
}
public function afterLayout($viewLayout) {
}
public function translate($id){
return $this->list[$id];
}
}
In view.ctp, intestead of showing the item ID, I just call the translate function, returning the proper name.
To create drop-down menus, it's just call the array list in select options.
<?php
echo "User Status: " . $this->My->translate($this->User->status);
echo $this->Form->input('tipo', array('type' => 'select', 'options' => $this->My->list));
?>
I think I should have used enum too, and using the functions specified, I would have success too.
Thanks for the helps.
You might want to look at model associations. In your case, I would have a students table and a student_statuses table that contains an ID and a status name. Then, when finding students, you can also include their corresponding StudentStatus row.
This relationship would look as follows:
<?php
class Student extends AppModel {
public $belongsTo = array('StudentStatus');
}
<?php
class StudentStatus extends AppModel {
public $hasMany = array('Student');
}
Then when finding students…
<?php
class StudentsController extends AppController {
public function index() {
$this->set('students', $this->Student->find('all'));
}
}
You will get a result like this:
Array
(
[0] => Array
(
[Student] => Array
(
[id] => 1
[name] => Martin Bean
[student_status_id] => 1
[created] => 2013-09-29 21:12:42
[modified] => 2013-09-29 21:12:42
)
[StudentStatus] => Array
(
[0] => Array
(
[id] => 1
[name] => Approved
[created] => 2013-09-23 18:26:06
[modified] => 2013-10-01 18:53:16
)
)
)
)
So you can just print the students’ status in your view as follows:
<?php foreach ($students as $student): ?>
<p>
<?php echo h($student['Student']['name']); ?>
(<?php echo h($student['StudentStatus']['name']); ?>)
</p>
<?php endforeach; ?>
You say you don’t want to create a table for statuses, but the reason you’re having issues is because it’s how relational databases work and also the convention. You’ll save yourself a lot of headaches by doing so, and it’s also extensible if you decide you need to add additional statuses in the future. You may not think you do now, but believe me: one day you will.
I'm having an issue where I call the result_array() function on n query object from in codeigniter:
$this->db->select(array('a','b','c'));
$query = $this->db->get('basic');
print_r($query->list_fields());
$test = $query->result_array();
print_r($query->list_fields());
When I run this code, or:
$query = $this->db->get('basic');
print_r($query->list_fields());
print_r($query->list_fields());
or:
$query = $this->db->get('basic');
$test = $query->result_array();
print_r($query->list_fields());
The second list_fields() function always returns an array size 0, the first returns the correct list of field names.
In the last example where there is only one list_fields() function, the array is again size zero.
Any guidance in this matter will be greatly appreciated. I need the list_fields() function to be accessible after I read the result_array().
Here is the result of the first block of code:
Array
(
[0] => site_id
[1] => institution
[2] => caller
[3] => call_complete
[4] => call_details
[5] => id
[6] => timestamp
)
Array
(
)
Thank you, for your help
That looks to be a bug in the database driver. For example, in CI_DB_mysqli_result:
public function list_fields()
{
$field_names = array();
while ($field = $this->result_id->fetch_field())
{
$field_names[] = $field->name;
}
return $field_names;
}
A subsequent call will return array() because the while loop seeks over all the fields and leaves the pointer at the end of the list.
However, in the result class, result_id is public, so you can use mysqli_result::field_seek:
$query = $this->db->get('basic');
var_dump($query->list_fields());
// this should be called before any call to list_fields()
$query->result_id->field_seek(0);
var_dump($query->list_fields());
However, this is bad practise, as this only works for mysqli; for mysql, you'll need this:
mysql_field_seek($query->result_id, 0);
and for mssql:
mssql_field_seek($query->result_id, 0);
The correct way to do this is really to fix it in the database drivers. See this pull request :-)