I am trying to make a rating system to my posts. First I have created a custom table that will contain post_id, post_title_, user ip, user machine, post rate, username, user id, timestamp.
Until now all is fine and I can insert data without any issue into this table. Next I am trying to create a function to verify if the user has already voted, to not allow user to rate more than one time per post, so created this function
function alreadyvoted($post_id) {
// variables
global $wpdb;
$table_name = $wpdb - > prefix.
"ratings_fansub";
$ip = $_SERVER['REMOTE_ADDR'];
$rate_userid = get_current_user_id();
$rate_user_machine = #gethostbyaddr($ip);
// getting data from databaase by current post_id
$results = $wpdb - > get_results('SELECT * FROM $table_name WHERE ratings_fansub_postid = $post_id ');
$NumRows = count($results);
$RandNum = rand(0, $NumRows);
$i = 0;
while ($i < $RandNum):
if ($rate_userid != 0) {
if ($rate_userid == $results[$RandNum] - > ratings_fansub_username)
return 1;
} else {
if ($rate_user_machine == $results[$RandNum] - > ratings_fansub_host or $ip == $results[$RandNum] - > ratings_fansub_ip)
return 1;
}
$i++;
endwhile;
}
But this function does not work, I believe I have made a mistake somewhere in the sql line but I can't figure out what it is.
Please check your table name in database. Table name like "wp_ratings_fansub" or not.
OR you can also print table name 'echo $wpdb - > prefix."ratings_fansub";exit();'
and check database table name is match or not.
i have fix it,
function alreadyvoted($post_id) {
// variables
global $wpdb;
$table_name = $wpdb - > prefix.
"ratings_fansub";
$ip = $_SERVER['REMOTE_ADDR'];
$rate_userid = get_current_user_id();
$rate_user_machine = #gethostbyaddr($ip);
// getting data from databaase by current post_id
$results = $wpdb - > get_results('SELECT * FROM wp_ratings_fansub WHERE ratings_fansub_postid ='.$post_id);
$NumRows = count($results);
$i = 0;
while ($i < $NumRows):
if ($rate_userid != 0) {
if ($results[$i] - > ratings_fansub_userid == $rate_userid)
return true;
} else {
if ($results[$i] - > ratings_fansub_host == $rate_user_machine or $results[$i] - > ratings_fansub_ip == $ip)
return true;
}
$i++;
endwhile;
return false;
} //end of function alreadyvoted
Related
I've written this function that returns a time(number )that must not exist in the same day in the database which means that the same time must not be repeated but when I execute it the time(number) is repeated
can you help me sort this one out?
screen shots of the tables
https://files.fm/u/9aw9yc8x
note: the table is empty and it will be filled when the entire code is executed I have just posted the function that must not repeat the time.
function checkTime($className,$day,$conn){
global $numberLimet,$Daily,$UserLimt,$exist;
$sqlHoure = "SELECT * from schedule WHERE classname='".$className."'";
$hourQuery = mysqli_query($conn,$sqlHoure);
$h = array();
while ($hour = mysqli_fetch_assoc($hourQuery)){
$h[$hour['hour']] = $hour['day1'];
// array_search();
}
$number = rand(1,7);
if(array_search($day,$h) && array_key_exists($number,$h)){
return 'error';
}else{
if($hour['hour'] != $number && $hour['day1'] != $day){
$numberLimet++;
if($numberLimet == $Daily){
$UserLimt = 1;
$FristAdd = false;
echo("UserLimt" . $UserLimt);
return 'errorLimit';
}else{
return $number;
}
}else{
}
}
return $h;
}
I have this helper method which job should be to prepare pagination data in order to retrieve it on controller...
Basically this is the code which happens in helper
if (!isset($_GET['page'])) {
$_GET['page'] = 1;
}
if (!isset($_GET['per_page'])) {
$_GET['per_page'] = 5;
}
$results = $ci->$model->get('', $_GET['per_page'], $_GET['page']);
And this is my model which should return data
public function get($tableName = "", $limit = null, $start = null)
{
if ($tableName == "") {
$tableName = $this->table;
}
if ($limit != null && $start != null) {
// problem is here with limit and start which returns wrong data
$this->db->limit($limit, $start);
$query = $this->db->get($tableName);
var_dump($query->result());
die();
}
} else {
$query = $this->db->get($tableName);
}
return $query->result();
}
Problem is that data returned from model isn't correct and i can't figure out how to get properly data based on page number and items per page....
So in my case if i request data with paramas $_GET['page'] = 1 and $_GET['per_page'] = 5 it will return 5 records, but starting with record 2 till record 6. So my question is how to properly request give me let say 5 records on starting page 1 and then give me another 5 records on page 2 ETC....
If you need any additional information please let me know and i will provide. Thank you
The problem lies within your $start variable. You should remember that when using getting the first the 5 records, you should use an offset 0 instead 1. Counting starts from 0 remember :)
The code should be
public function get($tableName = "", $limit = null, $start = null)
{
if ($tableName == "") {
$tableName = $this->table;
}
if ($limit != null && $start != null) {
// problem is here with limit and start which returns wrong data
//$this->db->limit($limit, $start);
// use this instead
$this->db->limit($limit, ( $start - 1 ) * $limit );
$query = $this->db->get($tableName);
var_dump($query->result());
die();
}
} else {
$query = $this->db->get($tableName);
}
return $query->result();
}
This is working example try to do like this: https://www.formget.com/pagination-in-codeigniter/
For part of a project i am working on in school i am building a room booking system. As part of this system, i have a page where users can enter criteria for a room and the page will return available rooms that fit that criteria and are free for booking. If a users search does not return any results i intend to lower the criteria entered, display a room that fits the altered criteria and display a message to the user informing them of the altered criteria. The call to function suggestroom() is shown here.
} else {
$reducecapacity = 1;
do {
$booking = new Booking();
$suggestedrooms = $booking->suggestroom(($capacity - $reducecapacity), $appletv, $printer);
$reducecapacity = $reducecapacity + 1;
} while($suggestedrooms === null);
echo 'This room has a cacpacity of: ' . ($capacity-($reducecapacity-1));
for($x=0; $x<count($suggestedrooms); $x++) {
echo $suggestedrooms[$x];
}
}
Public function SuggestRoom($capacity, $appletv, $printer) {
if($appletv == 1 and $printer ==0) {
$roomname = DB::GetInstance()->query("SELECT roomname FROM room WHERE capacity >= '$capacity' AND appletv ='$appletv'");
} elseif($appletv == 0 and $printer == 1) {
$roomname = DB::GetInstance()->query("SELECT roomname FROM room WHERE capacity >= '$capacity' AND printer = '$printer'");
} elseif($appletv == 1 and $printer == 1) {
$roomname = DB::GetInstance()->query("SELECT roomname FROM room WHERE capacity >= '$capacity' AND appletv ='$appletv' AND printer = '$printer'");
} else {
$roomname = DB::GetInstance()->query("SELECT roomname FROM room WHERE capacity >= '$capacity'");
}
$roomcount = $roomname->count();
if($roomcount == 0) {
echo 'No classes match your criteria';
} else {
for($x=0; $x<$roomcount; $x++) {
$RoomArray[$x] = $roomname->results()[$x]->roomname;
}
}
$LoopCount = 0;
$EndLoop = false;
$RNDnum = 0;
$availableroomcount = 0;
do {
$suggestedRoom = $RoomArray[$RNDnum];
$getRoomID = DB::GetInstance()->query("SELECT roomid FROM room WHERE roomname = '$suggestedRoom'");
$roomid = $getRoomID->results()[0]->roomid;
$bookingid = Input::get('bookingdate') . Input::get('period') . $roomid;
$CheckIfBooked = DB::GetInstance()->query("SELECT bookingid FROM booking WHERE bookingid = '$bookingid'");
if($CheckIfBooked->count() ==0) {
$availablerooms[$availableroomcount] = $suggestedRoom;
$availableroomcount = $availableroomcount+1;
}
if($LoopCount===$roomcount-1) {
$NoRoomMessage = true;
$EndLoop = true;
$suggestedRoom = null;
}
$LoopCount = $LoopCount+1;
$RNDnum = $RNDnum +1;
} while ($EndLoop <> 1);
return $availablerooms;
}
Thus, when there are no bookings, a null array will be returned to suggested rooms and this will continue until a room is found (if not, i will make it so other criteria is changed, not that far ahead yet).
A room can be found, and the code works however for x amount of times that the code is ran before a room is found i.e an empty array is returned, i get an undefined variable message. How can i get around this?
Switching off notices, warnings, errors is not the best way to code.
And unlike the above answers I prefer to always initialize a variable rather then using isset().
Use isset/empty
if(isset($var1) || !empty($var1)){
//do something
} else {
//do another
}
I'm working on made posts filter function on WP admin. First filter function works, but second not work. I'm suspect it's from $where .=, so I'm try to remove first one and just show second filter only. But doesn't work. Are there because incorrect $wpdb function?
function post_filter($where) {
if (is_admin()) {
global $wpdb;
if (isset($_GET['metakey_first']) && !empty($_GET['metakey_first']) && intval($_GET['metakey_first']) != 0) {
$metakey_first = intval($_GET['metakey_first']);
$where. = " AND ID IN (SELECT post_id FROM ".$wpdb - > postmeta."
WHERE meta_key='metakey_first' AND meta_value=$metakey_first)";
}
if (isset($_GET['metakey_second']) && !empty($_GET['metakey_second']) && intval($_GET['metakey_second']) != 0) {
$metakey_second = intval($_GET['metakey_second']);
$where. = " AND ID IN (SELECT post_id FROM ".$wpdb - > postmeta."
WHERE meta_key='metakey_second' AND meta_value=$metakey_second)";
}
}
return $where;
}
add_filter('posts_where', 'post_filter');
I have this function which creates random string:
function genID($length) {
$chars = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM#!";
//only allowed chars in the blowfish salt.
$size = strlen($chars); $str = "";
for ($i = 0; $i < $length; $i++)
$str .= $chars[rand(0, $size - 1)]; // strings can be used as char arrays
// Yes, I am aware this salt isn't generated using the OS source.
// use mycrypt_create_iv or /dev/urandom/
return $str;
}
This output something like:
#iBUQvldLq
Now I have users list with something like that:
userid | username | usermail ...
--------------------------------------
#iBUQvldLq test test#gmaik.com ....
Now when some one register I create new string and insert the new string to userid row in database, after that I create a new string, then I check if the new string created doesn't exist, something like this:
function newID()
{
$newid = genID(10);
$query = "SELECT * FROM users WHERE userid = '".$newid."'";
$result1 = mysql_query($query);
$num = mysql_num_rows($result1);
if($num == 1)
{
$newid = genID(10);
return $newid;
}
else
{
return $newid;
}
}
Any one have any idea how to loop on the check function?
I mean the generate function create new random string, then the function check if it already exist, then create new one, if not return the one created.
So now if he create new one, and the new one also match the same other userid, so how I loop until the new string won't match never to other userid string?
Something like loop:
create new string
verify if exist
if exist create new one
if the new one also exist create new one and so on
Till its never match other userid, make a loop, any idea ?
EDITED :
The new function for loop if any need:
function newID(){
$continue = true;
while ($continue) {
$newid = genID(10);
$query = mysql_query("SELECT * FROM users WHERE userid='".$newid."' LIMIT 1");
if (mysql_num_rows($query) != 1)
$continue = false;
return $newid;
}
}
$newid = newID();
It looks like your wanting code like this..
function uHash(){
$continue = true;
while ($continue) {
$hash = substr(MD5(microtime()), 0, 7);
$query = mysql_query("SELECT `Link` FROM Table WHERE `value`='$hash' LIMIT 1");
if (mysql_num_rows($query) != 1)
$continue = false;
return $hash;
}
}
The script will loop until it finds a unique value.
Setting your user_id column as an auto_increment field would solve this issue. [Best Approach]
If you really want to do with PHP, couple uniqid() with rand() to generate a unique seed that doesn't collide.
Something like this
<?php
echo $id = uniqid(rand(), true);
?>
Just you can use for unique id
<?php
function genID() {
return uniqid();
}
echo genID();
?>