getting error in my php query - php

I am getting an error message in my php query.
Error being displayed:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1294251744','127.0.0.1','/register')' at line 2
my code:
<?php
require_once("includes/database.php");
//Set timeout to 5 minutes
$timeoutseconds = 300 ;
//get the time
$timestamp = time();
//Delete all users that are no online after the time out allowed
$timeout = $timestamp - $timeoutseconds ;
// stores users IP addresss
$user_ip = $_SERVER['REMOTE_ADDR'];
// Automatically collects the hostname or domain like example.com)
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$path = rtrim(dirname($_SERVER['PHP_SELF']), '/');
//insert the values
$sql = "INSERT INTO totalonline(timestamp, ip, file)
VALUES (''$timestamp','$user_ip','$path')";
$result = mysql_query($sql, $conndb) or die(mysql_error());
//delete values when they leave
mysql_query("DELETE FROM totalonline WHERE timestamp < $timeout");
//grab the results
$sql = "SELECT DISTINCT ip FROM totalonline WHERE file='$path' ";
$result = mysql_query($sql, $conndb) or die(mysql_error());
//number of rows = the number of people online
$user = mysql_num_rows($result);
//spit out the results
if( $user == 1 ) {
echo "$user User online";
} else {
echo "$user User online";
}
?>

Change this:
//insert the values
$sql = "INSERT INTO totalonline(timestamp, ip, file)
VALUES (''$timestamp','$user_ip','$path')";
to this:
//insert the values
$sql = "INSERT INTO totalonline(timestamp, ip, file)
VALUES ('$timestamp','$user_ip','$path')";
You had two single quotes instead of one.
Also, near the end, you probably want to change this:
if( $user == 1 ) {
echo "$user User online";
} else {
echo "$user User online";
}
to this:
if( $user == 1 ) {
echo "$user User online";
} else {
echo "$user User offline";
}

You have double ' in the values field;)
//insert the values
$sql = "INSERT INTO totalonline(timestamp, ip, file)
VALUES (''$timestamp','$user_ip','$path')";
Right before $timestamp.
It's better to do
//insert the values
$sql = 'INSERT INTO totalonline(timestamp, ip, file)
VALUES ('.$timestamp.',"'.$user_ip."',"'.$path.'")';
because that way you make sure the db understands ip and path are strings.

Related

Creating PHP analytics for each user profile

I'm trying to create analytic data for each of the User Profiles by telling them how many visitors visited from city & country visited their profile.
This is what I'm currently doing.
session_start();
$analyticsuser = $_SESSION["analyticsuser"];
if($analyticsuser!=$author) //$author is where the id of each profile is stored.
{
$ip = $_SERVER['REMOTE_ADDR'];
$query = #unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
if($query && $query['status'] == 'success')
{
$userip = $query['query'];
$usercountry = $query ['country'];
$usercity = $query['city'];
$connection = mysqli_connect("HOSTNAME","USERNAME","PASSWORD","leo_site") or die("Error " . mysqli_error($connection));
$sqlanalytics = "INSERT INTO member_analytics VALUES(NULL,\"$userip\",\"$author\",\"$usercity\",\"$usercountry\",now());";
$resanalytics = mysqli_query($connection, $sqlanalytics) or die("Error " . mysqli_error($connection));
}
else { echo 'Unable to get location'; }
}
$_SESSION["analyticsuser"] = $author;
I'm trying to get how many visitors visited their profile from different city & countries.
The problem I'm facing now is, if I visit a profile again after visiting another profile, the data is still recorded. This should not happen as we have already recorded the visitor for that profile.
There are so many ways to solve this issue, one of them which I mostly used is an feature of mysql.
First create a composite key using author and userip.
After that at place of insert run replace query. As per nature of replace query if its find same author and userip combination field it replace that row by new data and if there is no combination found it will insert it.
$sqlanalytics = "REPLACE INTO member_analytics VALUES(NULL,\"$userip\",\"$author\",\"$usercity\",\"$usercountry\",now());";
I have solved my problem, You have to read session ID to check everytime if a profile is already visited by a visitor.
Below is the correct code.
session_start();
$new_sessionid = session_id();
$connection = mysqli_connect("HOSTNAME","USERNAME","PASSWORD","leo_site") or die("Error " . mysqli_error($connection));
$sqlcanalytics = "SELECT * FROM member_analytics WHERE sessid=\"$new_sessionid\" AND uid=\"$author\";";
$rescanalytics = mysqli_query($connection, $sqlcanalytics) or die("Error " . mysqli_error($connection));
$numcanalytics = mysqli_num_rows($rescanalytics);
if($numcanalytics==0)
{
$ip = $_SERVER['REMOTE_ADDR'];
$query = #unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
if($query && $query['status'] == 'success')
{
$userip = $query['query'];
$userisp = $query['isp'];
$organization = $query['org'];
$usercountry = $query ['country'];
$userregion = $query['regionName'];
$usercity = $query['city'];
$sqlanalytics = "INSERT INTO member_analytics VALUES(NULL,\"$userip\",\"$author\",\"$new_sessionid\",\"$usercity\",\"$usercountry\",now());";
$resanalytics = mysqli_query($connection, $sqlanalytics) or die("Error " . mysqli_error($connection));
}
else { echo 'Unable to get location'; }
}
Thanks for the help!

Php login script with login attemp

How can i limit the failed logins with this script? If the login fails, i insert it into the sql. (Is it the right way?)
But how can i check at the next login, that the user can now log in? I would take the login limit in 1 hour.
Aniway, is this code is good for that?
<?php
$loginError = array();
if(isset($_POST['login_submit']))
{
if(empty($_POST['email']) or !isset($_POST['email'])){$loginError[] = "Hiányzó email cím.";}
if(empty($_POST['pass']) or !isset($_POST['pass'])){$loginError[] = "Hiányzó jelszó.";}
if(strlen($_POST['email']) > 50 ){$loginError[] = "Hibás adat az email mezőben.";}
if(strlen($_POST['pass']) > 40 ){$loginError[] = "Hibás adat a jelszó mezőben.";}
if(count($loginError) == 0 )
{
$email = mysqli_real_escape_string($kapcs,$_POST['email']);
$pass = sha1($_POST['pass']);
$lekerdezes = mysqli_query($kapcs, "SELECT * FROM admin_user WHERE email = '$email'") or die(mysqli_error($kapcs));
if(mysqli_num_rows($lekerdezes) > 0 )
{
$adat = mysqli_fetch_assoc($lekerdezes);
if($adat['status'] == 1 )
{
if($adat['pass'] == $pass)
{
$_SESSION['adatok'] = $adat;
$_SESSION['email'] = $adat['email'];
$_SESSION['userid'] = $adat['id'];
header("Location:home.php");
}
else
{
$sql = "INSERT INTO loginattempts(log_address, log_datetime) VALUES ('".$_SERVER['REMOTE_ADDR']."', NOW())";
$insert_login_attempt = mysqli_query($kapcs, $sql) or die(mysqli_error($kapcs));
$loginError[] = "Hibás email cím vagy jelszó.";
}
}
else
{
$sql = "INSERT INTO loginattempts(log_address, log_datetime) VALUES ('".$_SERVER['REMOTE_ADDR']."', NOW())";
$insert_login_attempt = mysqli_query($kapcs, $sql) or die(mysqli_error($kapcs));
$loginError[] = "Még nincs aktiválva a fiók.";
}
}
else
{
$sql = "INSERT INTO loginattempts(log_address, log_datetime) VALUES ('".$_SERVER['REMOTE_ADDR']."', NOW())";
$insert_login_attempt = mysqli_query($kapcs, $sql) or die(mysqli_error($kapcs));
$loginError[] = "Hibás email cím vagy jelszó.";
}
}
}
?>
I would create a field in the database called status (blocked/ok) and assuming youve got a field timestamp for the last login...
Then Id connect to the database in case the login fails and save the status bloqued and the time stamp. the next attempt you would check the time.now vs last access...
I good suggestion would be create a function for the database connection so you can call it a couple of time without repeat the code, also dont forget use the try/except fot the db connection.

Resource id #6 error, Not sure how to fix it

I keep getting a 'Resource id # 6' failure when submitting a script on my website. The code I'm using is the same type of code I use for registering for the website and that works but this script doesn't work at all. What my code does is send a booking request with the fields as shown to the database. I keep getting a Resource id#6 error , and I've googled what that is but I can't seem to figure out whats wrong. I am a beginner at php , so any tips on whats to look for to avoid a resource id # 6 error would be a lot of help
<?php
//$pattern="/^.+#.+/.com/";
//error_reporting(0);
if(isset($_POST["submit"])){
$Name_of_Person = $_POST['Name_of_Person'];
$Name_of_Group = $_POST['Name_of_Group'];
$room = $_POST['room'];
$How_Many_People = $_POST['How_Many_People'];
$Date_of_Booking = $_POST['Date_of_Booking'];
$End_time = $_POST['End_time'];
$Purpose = $_POST['Purpose'];
$Contact_Number = $_POST['Contact_Number'];
$Contact_Email = $_POST['Contact_Email'];
$Alcohol = $_POST['Alcohol'];
$Security = $_POST['Security'];
$Projector = $_POST['Projector'];
$Extra_Chairs = $_POST['Extra_Chairs'];
$Extra_Info = $_POST['Extra_Info'];
$Activated = '0';
$con = mysql_connect('localhost','root','test123') or die("couldn't connect");
mysql_select_db('bookerdb') or die("couldn't connect to DB");
//if(filter_var($email, FILTER_VALIDATE_EMAIL)){//(preg_match($pattern, $_POST['Contact_Email'])){
$query = mysql_query("SELECT * FROM `booking_table` WHERE Date_of_Booking='".$Date_of_Booking."' AND room='".$room."'");
$numrows = mysql_num_rows($query);
echo $query;
if($numrows==0){
$sql="INSERT INTO `booking_table` (Name_of_Person,Name_of_Group,room,How_Many_People,Date_of_Booking,End_time,Purpose,Contact_Number,Contact_Email,Alcohol,Security,Projector,Extra_Chairs,Extra_Info, Activated) VALUES ('$Name_of_Person','$Name_of_Group','$room','$How_Many_People','$Date_of_Booking','$End_time','$Purpose','$Contact_Number','$Alcohol','$Security','$Projector','$Extra_Chairs','$Extra_Info',$Activated)";
$result = mysql_query($sql);
if($result){
echo "Sent to be approved";
$redirect_page = '../ASC.php';
$redirect = true;
if($redirect==true){
header('Location: ' .$redirect_page);
}
}else{
echo "Failed";
}
}else{
echo"There is already a requested booking on that date & time";
$redirect_page = '../EAR.php';
$redirect = true;
if($redirect==true){
header('Location: ' .$redirect_page);
}
}
/*}else{
echo "error";
$redirect_page = '../EWF.php';
$redirect = true;
if($redirect==true){
header('Location: ' .$redirect_page);
}
}*/
}
?>
You have error in your second SQL query. You try to insert 14 values into 15 columns (in values you forgot $Contact_Email).
$sql="INSERT INTO `booking_table` (Name_of_Person,Name_of_Group,room,How_Many_People,Date_of_Booking,End_time,Purpose,Contact_Number,Contact_Email,Alcohol,Security,Projector,Extra_Chairs,Extra_Info, Activated) VALUES ('$Name_of_Person','$Name_of_Group','$room','$How_Many_People','$Date_of_Booking','$End_time','$Purpose','$Contact_Number','$Contact_Email','$Alcohol','$Security','$Projector','$Extra_Chairs','$Extra_Info',$Activated)";
Than remove echo $query from your code, line 30.
In $query isn't query, but mysql result object. You can't work with that by this way, you can't echo it.

Efficiently Banning IPs Using php and mysql?

CREATE TABLE `banned_ip` (
`id` INT( 25 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`ip` VARCHAR( 25 ) NOT NULL ,
`reason` TEXT NOT NULL )
Config.php
<?php
// config
$config['host'] = "localhost"; // host name of your mysql server
$config['user'] = "username"; // your mysql username
$config['pass'] = "password"; // your mysql password
$config['db'] = "database"; // the database your table is in.
// the # sign is an error supressor, meaning we can use our own error messages, this connects and selects db
#mysql_connect("$config[host]","$config[user]","$config[pass]")
or die("There was an error connecting to the database, MySql said:<br />".mysql_error()."");
#mysql_select_db("$config[db]")
or die("There was an error connecting to the database, MySql said:<br />".mysql_error()."");
?>
Ban.php
<?php
include("connect.php");
$ip = $_SERVER['REMOTE_ADDR'];
$find_ip = mysql_query("SELECT * FROM banned_ip WHERE ip='$ip'");
$ban = mysql_fetch_array($find_ip);
if($ip == $ban['ip']){
die("You are banned from this site!");
else {
echo "Your Were not Banned";
$sql = "INSERT INTO user(ip) VALUES('$ip')";
}
?>
What I am doing is check my database for a ip , if it is banned or not. IF not banned, Showing him message "Your Were not Banned" and banning him.
Storing his ip in database. And then if he comes again on site, is will be show "You are banned from this site!"
By this i am giving each ip only one time access to my content. Is this script efficeint enough? This script is not working for me. It is not banning my ip , instead it keeps showing me my content.
You are working with different tables obviously. You do a select query for banned_ip, to check if the IP is banned. But if he is not banned, you try to insert into the user table. This way you do note down all banned IPs, but you don't select them.
Also, when you query the database, it's bad behaviour to do SELECT *. Select only the values you need (in this case it doesn't even matter what, since you check if he finds an row for the ip).
There's never a 100% sure way to prevent non-logged-in users from accessing content. If you ban an IP, you might ban several persons at once (like schools). Using cookies (and also Sessions) is not efficient enough, since the cookie can be deleted.
<?php
include("connect.php");
$ip = $_SERVER['REMOTE_ADDR'];
$find_ip = mysql_query("SELECT ip FROM banned_ip WHERE ip='$ip'");
$ban = mysql_fetch_array($find_ip);
if($ip == $ban['ip']){
die("You are banned from this site!");
else {
echo "Your Were not Banned";
$sql = "INSERT INTO banned_ip (ip) VALUES('$ip')";
}
?>
<?php> include "connect_to_mysql.php";
$proxy_headers = array(
'HTTP_VIA',
'HTTP_X_FORWARDED_FOR',
'HTTP_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_FORWARDED',
'HTTP_CLIENT_IP',
'HTTP_FORWARDED_FOR_IP',
'VIA',
'X_FORWARDED_FOR',
'FORWARDED_FOR',
'X_FORWARDED',
'FORWARDED',
'CLIENT_IP',
'FORWARDED_FOR_IP',
'HTTP_PROXY_CONNECTION'
);
foreach($proxy_headers as $x){
if (isset($_SERVER[$x])) die("You are using a proxy!");
}
$counter = 1873;
$MM_redirectLoginFailed = "sorry_search.php";
$MM_redirecttoReferrer = false;
$dynamicList="";
$dynamicListaa="";
$sql = mysql_query("SELECT * FROM ip WHERE ip LIKE '%54.36.%'");
$productCount = mysql_num_rows($sql); // count the output amount
if ($productCount > 0) {
// get all the product details
while($row = mysql_fetch_array($sql)){
$product_name = $row["ip"];
$counter++;
$sql2 = mysql_query("INSERT INTO bannedIp (bannedip_id, bannedip) VALUES ('".$counter."', '".$product_name."')") or die(mysql_error());
echo $sql2;
print($product_name);
}
} else {
header("Location: ". $MM_redirectLoginFailed );
}
$ip = $_SERVER['REMOTE_ADDR'];
$find_ip = mysql_query("SELECT * FROM bannedIp WHERE bannedip='$ip'");
$ban = mysql_fetch_array($find_ip);
if($ip == $ban['bannedip']){
die("You are banned from this site2!");
}
$ip_parts = explode (".", $_SERVER['REMOTE_ADDR']);
$parts = $ip_parts[0] . $ip_parts[1];
if($parts == 5436)
{
die("You are banned from this site1!");
}
<?>

Cannot execute sql INSERT query (mysql_query) in php script. PHP/MySQL -- Time Sensitive

UPDATE: NOW RESOLVED - Thanks everyone!
Fix: I had a column named "referred_by" and in my code it's called "referred_by_id" - so it was trying to INSERT to a column that didn't exist -- once I fixed this, it decided to work!
I have limited time left to work on this project. The clock is ticking.
I'm trying to INSERT $php_variables into a TABLE called "clients".
I've been trying for hours to get this script to work, and I got it to work once, but then I realized I forgot a field, so I had to add another column to the TABLE and when I updated the script it stopped working. I reverted by but now it's still not working and I'm just frustrating myself too much.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
if (!isset($_COOKIE["user"]))
{
header ("Location: ./login.php");
}
else
{
include ("./source.php");
echo $doctype;
}
$birthday = $birth_year . "-" . $birth_month . "-" . $birth_day;
$join_date = date("Y-m-d");
$error_type = 0;
$link = mysql_connect("SERVER", "USERNAME", "PASSWORD");
if (!$link)
{
$error = "Cannot connect to MySQL.";
$error_type = 1;
}
$select_db = mysql_select_db("DATABASE", $link);
if (!$select_db)
{
$error = "Cannot connect to Database.";
$error_type = 2;
}
if ($referred_by != "")
{
$result = mysql_query("
SELECT id FROM clients WHERE referral_code = $referred_by
");
if (!$result)
{
$error = "Cannot find referral.";
$error_type = 3;
}
while ($row = mysql_fetch_array($result))
{
$referred_by_id = $row['id'];
}
}
else
{
$referred_by_id = 0;
}
$first_name = mysql_real_escape_string($_POST['first_name']);
$last_name = mysql_real_escape_string($_POST['last_name']);
$birth_month = mysql_real_escape_string($_POST['birth_month']);
$birth_day = mysql_real_escape_string($_POST['birth_day']);
$birth_year = mysql_real_escape_string($_POST['birth_year']);
$email = mysql_real_escape_string($_POST['email']);
$address = mysql_real_escape_string($_POST['address']);
$city = mysql_real_escape_string($_POST['city']);
$state = mysql_real_escape_string($_POST['state']);
$zip_code = mysql_real_escape_string($_POST['zip_code']);
$phone_home = mysql_real_escape_string($_POST['phone_home']);
$phone_cell = mysql_real_escape_string($_POST['phone_cell']);
$referral_code = mysql_real_escape_string($_POST['referral_code']);
$referred_by = mysql_real_escape_string($_POST['referred_by']);
$organization = mysql_real_escape_string($_POST['organization']);
$gov_type = mysql_real_escape_string($_POST['gov_type']);
$gov_code = mysql_real_escape_string($_POST['gov_code']);
$test_query = mysql_query
("
INSERT INTO clients (first_name, last_name, birthday, join_date, email, address, city, state, zip_code,
phone_home, phone_cell, referral_code, referred_by_id, organization, gov_type, gov_code)
VALUES ('".$first_name."', '".$last_name."', '".$birthday."', '".$join_date."', '".$email."', '".$address."', '".$city."', '".$state."', '".$zip_code."',
'".$phone_home."', '".$phone_cell."', '".$referral_code."', '".$referred_by_id."', '".$organization."', '".$gov_type."', '".$gov_code."')
");
if (!$test_query)
{
die(mysql_error($link));
}
if ($error_type > 0)
{
$title_name = "Error";
}
if ($error_type == 0)
{
$title_name = "Success";
}
?>
<html>
<head>
<title><?php echo $title . " - " . $title_name; ?></title>
<?php echo $meta; ?>
<?php echo $style; ?>
</head>
<body>
<?php echo $logo; ?>
<?php echo $sublogo; ?>
<?php echo $nav; ?>
<div id="content">
<div id="main">
<span class="event_title"><?php echo $title_name; ?></span><br><br>
<?php
if ($error_type == 0)
{
echo "Client was added to the database successfully.";
}
else
{
echo $error;
}
?>
</div>
<?php echo $copyright ?>
</div>
</body>
</html>
Definitely not working as is. Looks you have a 500 error, since you have an else with a missing if:
else
{
$referred_by_id = 0;
}
Otherwise, you'll need to post your DB schema.
Also, note that you're really taking the long way around with this code, which makes it difficult to read & maintain. You're also missing any sort of checks for SQL injection... you really need to pass things through mysql_real_escape_string (and really, you should use mysqli, since the mysql interface was basically deprecated years ago).
$keys = array('first_name',
'last_name',
'birthday',
'join_date',
'email',
'address',
'city',
'state',
'zip_code',
'phone_home',
'phone_cell',
'referral_code',
'referred_by_id',
'organization',
'gov_type',
'gov_code');
$_REQUEST['birthdate'] = $_REQUEST['birth_year'].'-'.$_REQUEST['birth_month'].'-'.$_REQUEST['birth_day'];
$_REQUEST['join_date'] = date('Y-m-d',time());
$params = array();
foreach ($keys as $key)
{
$params[] = mysql_real_escape_string($request[$key]);
}
$sql = 'INSERT INTO clients ('.implode(',', $keys).') ';
$sql .= ' VALUES (\''.implode('\',\'', $params).'\') ';
You've an error on line 81:
else
{
$referred_by_id = 0;
}
I don't see an IF construct before that, make the appropriate correction and run the script again.
Without looking at the table structure to make sure all the fields are there, I'm going to assume it's something with the data.
Any quotes in the data will lead to problems (including SQL injection security holes). You should wrap each $_POST[] with mysql_real_escape_string(), such as:
$first_name = mysql_real_escape_string($_POST['first_name']);
EDIT: Further debugging...
As someone suggested (sorry, can't find the comment), try:
$sql = "
INSERT INTO clients (first_name, last_name, birthday, join_date, email, address, city, state, zip_code,
phone_home, phone_cell, referral_code, referred_by_id, organization, gov_type, gov_code)
VALUES ('".$first_name."', '".$last_name."', '".$birthday."', '".$join_date."', '".$email."', '".$address."', '".$city."', '".$state."', '".$zip_code."',
'".$phone_home."', '".$phone_cell."', '".$referral_code."', '".$referred_by_id."', '".$organization."', '".$gov_type."', '".$gov_code."'
)";
// Debug:
print "<pre>". $sql ."</pre>";
mysql_query($sql);
The SQL statement should be printed out when submitting the form. Take that SQL statement and try to execute it directly in MySQL to see if it works, or if it generates an error.

Categories