Codeigniter - Create Unique Page View Counter - php

I am creating a visitor counter for each my pages. According to PageId and visitor Ip, I created two tables such as pageView and pageTotalView. But my code is not working. I found some codes in php. How do I convert these codes to Codeigniter in working?
Database Tables:
CREATE TABLE `pageView` (
`pageViewId` int(11) NOT NULL AUTO_INCREMENT,
`pageViewPageId` int(11) NULL,
`pageViewUserIP` text NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=latin1
// totalview
CREATE TABLE `pageTotalView` (
`pageTotalViewId` int(11) NOT NULL AUTO_INCREMENT,
`pageTotalViewPId` int(11) NULL,
`pageTotalVisit` text NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=latin1
PHP Codes:
// gets the user IP Address
$pageViewUserIP = $_SERVER['REMOTE_ADDR'];
$check_ip = mysql_query("select pageViewUserIP from pageViewwhere pageViewPageId = 'I dont know How I can get viewing Page Id' and pageViewUserIP = '$pageViewUserIP'");
if(mysql_num_rows($check_ip)>=1)
{
}
else
{
$insertview = mysql_query("insert into pageView values('','I dont know How I can get viewing Page Id','$pageViewUserIP')");
$updateview = mysql_query("update pageTotalView set pageTotalVisit = pageTotalVisit+1 where pageViewPageId ='I dont know How I can get viewing Page Id' ");
}
To sum up, these codes maybe working on php, but How can I use these codes in Codeigniter?

Related

Writing a better loop

I'm creating a script that will search the database and look for customers that are in the Realtors latitude and longitude boundary range. If the customer lat and long coordinates is within the range of the realtor's lat and long boundaries then this script will email only the Realtor in that customers range. I'm using a CRON job to run the php script. I got the script to email each person that is in range of the Realtors but when a third Realtor is entered into the database the email goes to the third Realtor even though the lat and long is out of range.
How do I write a better loop where each row gets checked if the client is in range of that Realtor and only email that Realtor only? Thanks.
Here is my SQL code.
CREATE TABLE `realtors` (
`rid` int(11) NOT NULL AUTO_INCREMENT,
`rEmail` varchar(255) NOT NULL,
`rZipCode` int(10) NOT NULL,
`rDist` int(11) NOT NULL,
`rlatitude` numeric(30,15) NOT NULL,
`rlongitude` numeric(30,15) NOT NULL,
PRIMARY KEY (`rid`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE `customers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`eMail` varchar(255) NOT NULL,
`zipCode` int(11) NOT NULL,
`clatitude` numeric(30,15) NOT NULL,
`clongitude` numeric(30,15) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
Here is my php code.
<?php
use geocodeloc\GeoLocation as GeoLocation;
require_once 'geocodeloc/GeoLocation.php';
//require_once 'phpmailer/PHPMailerAutoload.php';
$db = getDB();
//database prep for customers
$cust = $db->prepare("SELECT fullName, eMail, clatitude, clongitude FROM customers ORDER BY id DESC");
$cust->bindParam("fullName", $fullName,PDO::PARAM_STR);
$cust->bindParam("zipCode", $zipCode,PDO::PARAM_STR);
$cust->bindParam("eMail", $email,PDO::PARAM_STR);
$cust->bindParam("clatitude", $clatitude,PDO::PARAM_STR);
$cust->bindParam("clongitude", $clongitude,PDO::PARAM_STR);
$cust->execute();
$cust->rowCount();
//database prep for realtors
$realt = $db->prepare("SELECT rEmail, rDist, rlatitude, rlongitude FROM realtors ORDER BY rid DESC");
$realt->bindParam("rZipCode", $rZipCode,PDO::PARAM_STR);
$realt->bindParam("rEmail", $rEmail,PDO::PARAM_STR);
$realt->bindParam("rDist", $rDist,PDO::PARAM_STR);
$realt->bindParam("rlatitude", $rlatitude,PDO::PARAM_STR);
$realt->bindParam("rlongitude", $rlongitude,PDO::PARAM_STR);
$realt->execute();
$realt->rowCount();
$i = -1;
while ($realtor_row = $realt ->fetch(PDO::FETCH_ASSOC) AND $customers_row = $cust ->fetch(PDO::FETCH_ASSOC)) {
$i++;
$realtLatLong = GeoLocation::fromDegrees( $realtor_row['rlatitude'], $realtor_row['rlongitude']);
$coordinates = $realtLatLong->boundingCoordinates($realtor_row['rDist'], 'miles');
//look to see if customers latitude and longitude is within range of the realtors lat and long boundaries.
if($customers_row['clatitude'] && $customers_row['clongitude'] <= $coordinates){
//email the realtor
// the message
$msgBody = "This is a test";
// use wordwrap() if lines are longer than 70 characters
$msgBody = wordwrap($msgBody,70);
$Mailto = $realtor_row['rEmail'];
$FromName = $customers_row['fullName'];
// send email
mail($Mailto, $FromName , $msgBody);
}else{
//send to debug log
}
};
?>
Looping through the entire result set and doing the calculations is going to kill your database very quickly. Looping through one table and then looping through another to do a distance comparison is going to kill your database even faster. Luckily this is a re invention of the wheel. Mysql has built in functionality for this by way of ST_Distance
SELECT * FROM realtors INNER JOIN customers WHERE ST_within(customers.loc, realtors.loc) < 10; /* location in degrees */
Where one degree is approximately 111 kilometer. You whould need to change your table as follows
CREATE TABLE `realtors` (
`rid` int(11) NOT NULL AUTO_INCREMENT,
`rEmail` varchar(255) NOT NULL,
`rZipCode` int(10) NOT NULL,
`rDist` int(11) NOT NULL,
`loc` point NOT NULL,
PRIMARY KEY (`rid`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE `customers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`eMail` varchar(255) NOT NULL,
`zipCode` int(11) NOT NULL,
`loc` POINT not null,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
of course this requires mysql 5.7
Using a spatial data type means that you can use an index for spatial looksup. In an RDBS if a table contains N rows, having an indes means you do not need to check through all those N number of rows to find a result. Thus using spatial data here + an index you can avoid the NxM time complexity you might have with lat,lng in separate columns.
No matter how fast you can make your code, the complexity will still be NxM.
First thing you should do is to create a relationship between Customer and Realtor, i.e. a table with Customer.id and Realtor.id. Take a hit the first time you populate this table (no need to change your code). After that, you just need to create a relationship everytime a Customer or a Realtor got added.
When it's time to send your email, you just need to look at the relationship table.

$wpdb->insert is not respacting unique fields

I have been creating Wordpress plugin for a while. This is example of mysql table:
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id INT(11) NOT NULL AUTO_INCREMENT,
email VARCHAR(100) DEFAULT NULL,
telephone VARCHAR(15) DEFAULT NULL,
PRIMARY KEY(id),
UNIQUE (email, telephone)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='WP plugin sesa_players db' AUTO_INCREMENT=1 ;
";
Email should be unique, right? phpMyAdmin says it it.
This is wordpress code that inserts data into that table:
$err = $wpdb->insert($wpdb->prefix.$table_name, $data, $format);
var_dump($err);
It works, even more than it should. Assume email is m#m.com. First insert goes well. Second try fails because of duplicate entry as it should. var_dump is false.
BUT if I refresh wp page, third try with same email passes flawlessly, var_dump 1. Any repeated wp refresh opens db for duplicate entry.
Why? What am I doing wrong?
No, email is not UNIQUE here. Pair of email and telephone is UNIQUE in your table definition.
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id INT(11) NOT NULL AUTO_INCREMENT,
email VARCHAR(100) DEFAULT NULL,
telephone VARCHAR(15) DEFAULT NULL,
PRIMARY KEY(id),
UNIQUE (email),
UNIQUE (telephone)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='WP plugin sesa_players db' AUTO_INCREMENT=1 ;
";
Probably this is what you want.

Database structure for tags system

I'm making a simple PHP Forum, whereby tags are created alongside the main topic.
The table looks like this:
CREATE TABLE IF NOT EXISTS `topic` (
`topic_id ` int(100) NOT NULL AUTO_INCREMENT,
`topic_head` varchar(5) NOT NULL,
`topic_body` varchar(20) NOT NULL,
`topic_tag` varchar(20) NOT NULL,
`topic_date` varchar(20) NOT NULL,
`topic_owner` varchar(20) NOT NULL,
PRIMARY KEY (`topic_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
Specifically for the tags, I'll be performing a select query in the form of:
$tags = mysql_query("SELECT DISTINCT topic_tags
FROM forum_topics")
while($tags = mysql_fetch_assoc($tags){
$split_tags = "$tags";
$pieces = explode(",", $split_tags);
Currently, topic_tags are in the format tag1,tag2,tag3,tag4
How can I have it in such a way that each topic tag will be associated with each topic?
If I've understood correctly, what you want is another table for tags and then a third table to store the relationships. So:
CREATE TABLE `tags` (
`t_id` int(11) NOT NULL AUTO_INCREMENT,
`t_text` varchar(150) NOT NULL,
`t_datetime` datetime NOT NULL,
PRIMARY KEY (`t_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE `tag_pairs` (
`tp_id` int(11) NOT NULL AUTO_INCREMENT,
`tp_topic_id` int(11) NOT NULL,
`tp_tag_id` int(11) NOT NULL,
`tp_datetime` datetime NOT NULL,
PRIMARY KEY (`tp_id`),
FOREIGN KEY (`tp_topic_id`) REFERENCES topic('topic_id'),
FOREIGN KEY (`tp_tag_id`) REFERENCES tags('t_id')
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Then, to get tags for a topic based on its ID ($THIS_ID):
$query = mysql_query("
SELECT tags.t_text
FROM tags, tag_pairs, topic
WHERE topic.topic_id = '$THIS_ID'
AND tag_pairs.tp_topic_id = topic.topic_id
AND tag_pairs.tp_tag_id = tags.t_id
");
Call the columns just: id, head, body, tag_id (FK), date and user_id (FK)
This is much more understandable and also easier to use. Let me explain:
Right now you are using the columns as: topic_id, but it should be: topic.id. How do you get this? By simply using the tablename + column. So when the table is called topics and you have a column called id, you can use it by saying: topics.id. In the answer above from da5id, I can see that he is using topics.topic_id, a bit overkill isn't it? ;)
Also, read this article about database normal form 3 and google a bit yourself with database+3nf

Zend_Db_Select Select values not in specific table

I've googled my question and read through a bunch of forum posts but I've yet to find the answer I'm looking for hopefully someone here can help me out.
For a project I'm building I've set up the following 3 tables; users, projects and projectUsers.
I've set up a form where I can add users to projects by saving the userID and the projectID in the projectUsers table nothing special so far. The form contains a select element with userIDs that can be connected to a projectID (hidden field).
This form element is filled with a query set up with Zend_Db_Select it selects all the users from the users table and adds it to the select. However I want to filter that result so it excludes all of the users already added to that specific project.
Short version: I have a select element with users filled with a resultset from a (Zend_db_select) database query I want that resultset to be stripped from certain userIDs.
For extra reference the table scheme below:
CREATE TABLE IF NOT EXISTS `projects` (
`projectID` int(11) NOT NULL AUTO_INCREMENT,
`projectName` varchar(255) NOT NULL
PRIMARY KEY (`projectID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `projectUsers` (
`projectUserID` int(11) NOT NULL AUTO_INCREMENT,
`projectID` int(11) NOT NULL,
`userID` int(11) NOT NULL
PRIMARY KEY (`projectUserID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `users` (
`userID` int(11) NOT NULL AUTO_INCREMENT,
`userFirstName` varchar(255) DEFAULT NULL,
`userLastName` varchar(255) DEFAULT NULL
PRIMARY KEY (`userID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
Thanks in advance!
addint to Soica Micea ans
$blackList = array(1,3,5,6); //user id which you want to exclude
$db->select()->from('users', '*')
->joinLeft('projectUsers', 'projectUsers.projectUserID = users.userID', null)
->where('projectUsers.projectID = ?', someProjectID)
->where('projectUserID is null')
->where('users.userID not in (?)', implode(',',$blackList))
->query()->fetchAll();
This will select all users that have not been added to a project and ignore users from arrayOfUserIds
select()->from('users', '*')
->joinLeft('projectUsers', 'projectUsers.projectUserID = users.userID', null)
->where('projectUsers.projectID = ?', someProjectID)
->where('projectUserID is null')
->where('users.userID not in (?)', arrayOfUserIds)
->query()->fetchAll();

How do I log in and display information from two tables (MySQL)?

I'm new to MySQL and PHP so Im not sure how to approach this problem I'm having.
I have two tables right now.
CREATE TABLE `users` (
`userid` int(25) NOT NULL AUTO_INCREMENT,
`username` varchar(65) NOT NULL DEFAULT '',
`password` varchar(32) NOT NULL DEFAULT '',
`emailaddress` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`userid`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
and
CREATE TABLE `images` (
`userid` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`image` blob,
PRIMARY KEY (`userid`)
) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;
so what I want to do is when a user signs in I want to be able to display an image that the user uploaded.
do I have to do something to the tables to make theme reference from each other?
help please!
Do you want just?...
select image from images
left join users on users.userid=images.userid
where username='whateverusername';
in the second table , the attribute userid should be a foreign key (i'd rather use Innodb to make sure that there is a foreign key constraint but it's up to u to use innodb or not)
so your table should look like this
CREATE TABLE images ( userid int(10) unsigned NOT NULL, name
varchar(50) DEFAULT NULL, image blob, foreign key userid
references users(userid) on delete cascade ) ENGINE=InnoDB
AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;
once you do that, the table images will be linked to the table users which means that no record will be added to the table images unless the user id is already in the table users
if you wanna grab all the informations about that users including the image , you can perform a join between the two tables.
example with php
$con = mysql_connect("localhost","mysql_user","mysql_pwd");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$user_id = 1;
$results = array();
> $results =mysql_query("select t1.userid,t1.username,t2.name,t2.image from users as t1 left join images as t2 on t1.userid=t2.userid where userid = $user_id",$con);
UPDATE:
make sure that the type of userid in both tables match

Categories