don't know why it happens, here is the sample of the code
$uid = Yii::$app->user->identity->ID;
if($id != null){
$model = self::findOne($id);
}
else{
$model = self::find()->select('ID, connection_uri, version, username, password')->where('
enabled = :en AND user_id = :userid
' ,[':en' => 1, ':userid' => $uid])->one();
}
When this line is being processed $uid = Yii::$app->user->identity->ID;
the whole server is getting very slower and I cannot do any other thing only to wait while the function is being finished. When I delete that line and for example type this : $uid = 1; then everything is ok. Do you have any ideas why it might happen?
Try with :
$uid = Yii::$app->user->identity->id;
Related
I want to test my Php api in postman, please guide me,
Below code working fine and this php api code using for Android Retrofit but i want to test this api in postman.
<?php
require 'db.php';
$data = json_decode(file_get_contents('php://input'), true);
if($data['mobile'] == '' or $data['password'] == '')
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}
else
{
$mobile = strip_tags(mysqli_real_escape_string($con,$data['mobile']));
$password = strip_tags(mysqli_real_escape_string($con,$data['password']));
$chek = $con->query("select * from user where (mobile='".$mobile."' or email='".$mobile."') and status = 1 and password='".$password."'");
$status = $con->query("select * from user where status = 1");
if($status->num_rows !=0)
{
if($chek->num_rows != 0)
{
$c = $con->query("select * from user where (mobile='".$mobile."' or email='".$mobile."') and status = 1 and password='".$password."'");
$c = $c->fetch_assoc();
$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Login successfully!");
}
else
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Invalid Email/Mobile No or Password!!!");
}
}
else
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Your Status Deactivate!!!");
}
}
echo json_encode($returnArr);
Thanks in advance :)
In postmane first create new request.
Then select POST as request and insert your localhost URL ( eg. http://localhost/project_folder_name/YOUR_FILE_NAME.php )
In below tab select Body.
In Body select raw to pass request data.
Pass below json
{ "mobile":"asdsad", "password":"asdasd" }
click send button you will get result
Atteached screen shot of postman request.
List item
I want to count the amount of updates made on a record. The field name is pm_v. I got the following codes:
Update function:
function update_products_materials(){
$query = "UPDATE
" . $this->table_name . "
SET
pm_id = :pm_id1,
pm_code = :pm_code,
pm_name = :pm_name,
pm_department = :pm_department,
pm_temp = :pm_temp,
pm_color = :pm_color,
pm_v = pm_v +1
WHERE
pm_id = :pm_id2";
$stmt = $this->conn->prepare($query);
$this->pm_id=htmlspecialchars(strip_tags($this->pm_id));
$this->pm_code=htmlspecialchars(strip_tags($this->pm_code));
$this->pm_name=htmlspecialchars(strip_tags($this->pm_name));
$this->pm_department=htmlspecialchars(strip_tags($this->pm_department));
$this->pm_temp=htmlspecialchars(strip_tags($this->pm_temp));
$this->pm_color=htmlspecialchars(strip_tags($this->pm_color));
$stmt->bindParam(':pm_id1', $this->pm_id);
$stmt->bindParam(':pm_id2', $this->pm_id);
$stmt->bindParam(':pm_code', $this->pm_code);
$stmt->bindParam(':pm_name', $this->pm_name);
$stmt->bindParam(':pm_department', $this->pm_department);
$stmt->bindParam(':pm_temp', $this->pm_temp);
$stmt->bindParam(':pm_color', $this->pm_color);
$stmt->execute();
return $stmt;
}
This is the only place where I use pm_v.
The function is called in the following code:
$database = new Database();
$db = $database->getConnection();
// initialize objects
$products_materials = new Products_Materials($db);
$products_materials->id = $id;
$products_materials->view_products_materials();
$products_materials->update_products_materials();
if(isset($_POST["update"])){
$products_materials->pm_id=$id;
$products_materials->pm_code=$_POST['pm_code'];
$products_materials->pm_name=$_POST['pm_name'];
$products_materials->pm_department=$_POST['pm_department'];
$products_materials->pm_temp=isset($_POST['pm_temp']) ? $_POST['pm_temp'] : '';
$products_materials->pm_color=isset($_POST['pm_color']) ? $_POST['pm_color'] : '';
if($products_materials->update_products_materials() && (isset($_POST["update"]))){
header("Location: view_products_materials.php?id={$id}");
$_POST=array();
} else {
echo "<div class='alert alert-danger' role='alert'>Unable to save record.</div>";
}
}
Somehow, when I update a record it does +3 instead of +1. Can anyone explain why this is happening and how I can get it right?
I have a form where the user can add courses and when the user clicks on the edit button he is redirected to another page so as to modify the data in the form. But when the user clicks on the Save button, nothing happens. A blank page appears. In the normal situation, "successful" needs to appear on the page.
Codes which handles the update query:
<?php
require_once(dirname(dirname(dirname(__FILE__))) . '/config.php');
global $DB;
$id = required_param('facid', PARAM_TEXT);
$name = required_param('name', PARAM_TEXT);
$course_detail = required_param('course_detail', PARAM_TEXT);
$course_outline = required_param('course_outline', PARAM_TEXT);
$course_obj = required_param('course_obj', PARAM_TEXT);
//$programme = required_param('programme', PARAM_TEXT);
$update = $DB->execute_sql("UPDATE {courses} SET name = '$name' AND course_detail = '$course_detail' WHERE id = '$id'");
if(!$update)
{
echo "Could not update";
}
else
{
echo "Successful";
}
?>
I can understand that the SQL statement is wrong but i can't seem to fix it as it is quite different from the PHP codes I've learned. I also tried checking on this link but can't seem to find the answer. I'm new to Moodle.
Any help please?
I know its late but might help some one in future so posting the answer,
As per Moodle docs below is the code to update the record while $dataobjec is the associative array. $dataobject must have an id field in order to update the record
$DB->update_record($table, $dataobject, $bulk=false)
$dataobject= array(
'id' => $_POST['id'],
'value2' => $_POST['value2'],
'value2' => $_POST['value3']
);
I could finally solve it so i thought of posting the answer for future new Moodle developers.
Codes:
<?php
require_once(dirname(dirname(dirname(__FILE__))) . '/config.php');
global $DB;
$id = required_param('facid', PARAM_TEXT);
$name = required_param('name', PARAM_TEXT);
$course_detail = required_param('course_detail', PARAM_TEXT);
$course_outline = required_param('course_outline', PARAM_TEXT);
$course_obj = required_param('course_obj', PARAM_TEXT);
//$programme = required_param('programme', PARAM_TEXT);
$record = new stdclass;
$record->id = $id;
$record->name = $name;
$record->course_detail = $course_detail;
$record->course_outline = $course_outline;
$record->course_obj = $course_obj;
$sql = $DB->update_record('courses', $record);
if(!$sql)
{
echo "Could not update";
}
else
{
echo "Successful";
}
?>
I have the following variable $user_id being set by
//Check if user is logged in
session_start();
if (!isset ($_SESSION['user_id']))
{
header("location:login.php");
}
elseif(isset ($_SESSION['user_id']))
{
$user_id = $_SESSION['user_id'];
}
and then within the same function file I have the following:
function course_menu()
{
$sqlSubscription = "SELECT * FROM subscriptions WHERE `user_id` = '".$user_id."'";
$subscriptionResult = mysql_query($sqlSubscription);
while ($rows = mysql_fetch_assoc($subscriptionResult))
{
$user_id = $rows['user_id'];
$course_id = $rows['course_id'];
$course_title = $rows['course_title'];
if ($data_id == $rows['course_id'])
{
echo
'<li>
',$course_title,'
</li>';
}
else
{
echo
'<li>',$course_title,' </li>';
}
}
}
The problem is I keep getting undefined variable user_id every time I try to run the function. I can echo $user_id on another page lets say index.php by using require_once function.php and then echo $user_id, but for some reason the function itself can't access it?
I think it might be because it's outside its scope - but if so I'm not entirely sure what to do about it.
My question is, how can I get the function to be able to use the variable $user_id?
EDIT
So I've started doing
$user_id = $_SESSION['user_id'];
global $conn;
$sqlSubscription = "SELECT * FROM subscriptions WHERE `user_id` = '".$user_id."'";
$subscriptionResult = $conn->query($sqlSubscription);
while ($rows = mysqli_fetch_assoc($subscriptionResult))
{
$user_id = $rows['user_id'];
$course_id = $rows['course_id'];
$course_title = $rows['course_title'];
if ($data_id == $rows['course_id'])
{
echo
'<li>
',$course_title,'
</li>';
}
else
{
echo
'<li>',$course_title,' </li>';
}
}
which seems to work fine, but it's a bit tedious to add a new connection each time with a function or set the $user_id manually. Is there any way around this as I have several functions that require a connection to the db to pull data. Is there a better way to structure this type of stuff? I'm not very familiar with OOP but I can try it out if I can get some direction, here's another function that I use (and there are at least another 5-6 that require db connections)
function render_dashboard()
{
$user_id = $_SESSION['user_id'];
global $conn;
//Following brings up the number of subscription days left on the user dashboard
$sqlDate = "SELECT * FROM subscriptions WHERE `user_id` = '".$user_id."'" ;
$date = $conn->query($sqlDate);
while ($daterows = mysqli_fetch_assoc($date))
{
$course_registered = $daterows['course_title'];
$date_time = $daterows['end_date'];
$calculate_remaining = ((strtotime("$date_time")) - time())/86400;
$round_remaining = round("$calculate_remaining", 0, PHP_ROUND_HALF_UP);
// Here we assign the right term to the amount of time remaining I.E DAY/DAYS/EXPIRED
if($round_remaining > 1)
{
$remaining = $course_registered." ".$round_remaining." "."Days Remaining";
$subscriptionStatus = 2;
echo '<p>',$remaining,'</p>';
}
elseif ($round_remaining == 1)
{
$remaining = $course_registered." ".$round_remaining." "."Day Remaining";
$subscriptionStatus = 1;
echo '<p>',$remaining,'</p>';
}
elseif ($round_remaining <= 0)
{
$remaining = $course_registered." "."Expired"." ".$date_time;
$subscriptionStatus = 0;
echo '<p>',$remaining,'</p>';
}
}
//Check for most recent viewed video
$sqlVideo = "SELECT `last_video` FROM users WHERE `user_id` = '".$user_id."'" ;
$videoResult = $conn->query($sqlVideo);
if ($videoRows = mysqli_fetch_assoc($videoResult))
{
$last_video = $videoRows['last_video'];
$videoLink = "SELECT `chapter_id` FROM chapters WHERE `chapter_title` = '".$last_video."'";
if ($chapteridResult = mysql_fetch_assoc(mysql_query($videoLink)));
{
$chapter_id = $chapteridResult['chapter_id'];
}
$videoLink = "SELECT `course_id` FROM chapters WHERE `chapter_title` = '".$last_video."'";
if ($courseResult = mysql_fetch_assoc(mysql_query($videoLink)));
{
$course_id = $courseResult['course_id'];
}
}
}
The function course_menu() will not recognize your $user_id, Since it is outside its scope.
Make use of global keyword to solve this issue.
function course_menu()
{
global $user_id;
// your remaining code .........
The solution to getting around it without using global is to either DEFINE and pass it through ie - define ('var', '$var') then function x($var) or dependency injection as stated here How can I use "Dependency Injection" in simple php functions, and should I bother?
I am having some problem with my apache server when handling big amount of traffic. after some optimizations I did. I still have the same problem. I check my log file and it turned out that I have a lot of php processing. The following code is getting processed about 800 times a minute (when I have high traffic) and casing my server to crash.
1) is there any parts of the code that I need to rewrite that would make it take less php processing ?
2) is it a good idea to have all of this code before the html starts ?
<?php
$ip = $_SERVER['REMOTE_ADDR'];
mysql_connect('', '', '');
mysql_select_db('');
if(empty($_GET['i']) == false){
$get_image = mysql_real_escape_string($_GET['i']);
$check_if_image = mysql_query("SELECT `id`, `image_name`, `image_type`, `image_caption`, `image_voteup`, `image_votedown`, `image_views`, `fb_userid` FROM images_new WHERE image_name = '$get_image'");
if(mysql_num_rows($check_if_image) == 1){
$result = mysql_fetch_assoc($check_if_image);
$image_id = $result['id'];
$image_name = $result['image_name'];
$image_type = $result['image_type'];
$image_caption = stripslashes($result['image_caption']);
$image_voteup = $result['image_voteup'];
$image_votedown = $result['image_votedown'];
//$image_date = $result['image_date'];
$image_views = $result['image_views'];
$fb_username = $result['fb_username'];
$fb_userid = $result['fb_userid'];
//next image
$next_image_id = $image_id + 1;
$check_next_image = mysql_query("SELECT `image_name` FROM images_new WHERE id = '$next_image_id'");
if(mysql_num_rows($check_next_image) == 1){
$next_image_result = mysql_fetch_assoc($check_next_image);
$next_image_name = $next_image_result['image_name'];
}
// pre image
$pre_image_id = $image_id - 1;
$check_pre_image = mysql_query("SELECT `image_name` FROM images_new WHERE id = '$pre_image_id'");
if(mysql_num_rows($check_pre_image) == 1){
$pre_image_result = mysql_fetch_assoc($check_pre_image);
$pre_image_name = $pre_image_result['image_name'];
}
//shares, comments, and likes
$fb_page_url = "http://www.xxx.com/images.php?i=".$get_image;
$fb_url = "http://api.facebook.com/restserver.php?method=links.getStats&urls=".urlencode($fb_page_url);
$fb_xml = file_get_contents($fb_url);
$fb_xml = simplexml_load_string($fb_xml);
$fb_shares = $fb_xml->link_stat->share_count;
$fb_likes = $fb_xml->link_stat->like_count;
$fb_likes_and_shares = $fb_likes + $fb_shares;
$fb_comments = $fb_xml->link_stat->commentsbox_count;
//facebook
require_once('scripts/facebook.php');
$config = array('appId' => '','secret' => '');
$params = array('scope'=>'user_likes,publish_actions,email,offline_access,user_birthday');
$facebook = new Facebook($config);
$user = $facebook->getUser();
if($user){
try{
$user_profile = $facebook->api('/me','GET');
$user_id = $user_profile['username'];
$expire_time = time() + 30758400;
//insert cookie id
if (!isset($_COOKIE['id'])){
$cookie_id = $user_profile['username'];
setcookie("id", $cookie_id, $expire_time, '/');
}
//insert cookie name
if (!isset($_COOKIE['name'])){
$user_name = $user_profile['first_name'];
setcookie("name", $user_name, $expire_time, '/');
}
//check if the user like the fan page
$isFan = $facebook->api(array(
"method" => "pages.isFan",
"page_id" => ''
));
}catch(FacebookApiException $e) {
error_log($e->getType());
error_log($e->getMessage());
}
}else{//if no user
if(isset($_COOKIE['name'])){
$user_name = $user_profile['first_name'];
setcookie("name", $user_name, time() - 30758400, '/');
}
}
//increase views
if($facebook->getUser()){
mysql_query("UPDATE images_main SET image_views = image_views + 1 WHERE image_name='$image_name'");
mysql_query("UPDATE images_new SET image_views = image_views + 1 WHERE image_name='$image_name'");
}
}else{//image was not found in the database.
header('Location: index.php');
}
}else{//redirect if get is empty
header('Location: index.php');
}
?>
I would say the key factor is your call to the Facebook API, such things are always expensive and easily cacheable, put that code in a separate page/include and cache it as you like.
Also as a side note, you should consider reducing the number of db queries and you may wish to update your db driver... as invariably everyone points out #Madara Uchiha
I see a few items right off the bat.
First query:
$check_if_image = mysql_query("SELECT `id`, `image_name`, `image_type`, `image_caption`, `image_voteup`, `image_votedown`, `image_views`, `fb_userid` FROM images_new WHERE image_name = '$get_image'");
If you only need one result back, put a 'LIMIT 1' at then end (unless this field has a UNIQUE index, in which case this shouldn't matter). Also make sure this field is indexed and preferably a VARCHAR field instead of TEXT or BLOB.
Next, you are running 2 queries to get the previous and next images. I would combine this into 1 query like this:
SELECT `image_name` FROM images_new WHERE id IN ('$next_image_id', '$pre_image_id')
Also, you can apply the first optimization I mentioned to these 2 queries:
if($facebook->getUser()){
mysql_query("UPDATE images_main SET image_views = image_views + 1 WHERE image_name='$image_name'");
mysql_query("UPDATE images_new SET image_views = image_views + 1 WHERE image_name='$image_name'");
}
Lastly, going through the Facebook API is going to add load time that you cannot do much about. Hopefully this gets you started down the right path.