When I change SELECT * to SELECT count(*) the script stops working altogether. How to I add a count(*) to this file and a statement if row count for $user >= 20 allow to INSERT else do nothing.
// Include needed files
include 'mysql.php';
// Connect to MySQL
connectMySQL();
//****** SECURITY CHECK *********
session_start();
if(isset($_SESSION['userid'])){
$user = mysql_real_escape_string($_SESSION['userid']);
//*******************************
// Retrieves variables through AJAX
$favid = mysql_real_escape_string($_GET['favid']);
// $favid = mysql_real_escape_string($_GET['favid']);
// Firstly, check if article is favourite or not
$query = mysql_query("SELECT * FROM ajaxfavourites WHERE user='$user' AND favid='$favid'");
$matches = mysql_num_rows($query);
// If it is not favourited, add as favourite
if($matches == '0'){
mysql_query("INSERT INTO ajaxfavourites (user, favid, exptime) VALUES ('$user', '$favid', CURRENT_TIMESTAMP)");
echo "";
}
// Instead, if it is favourited, then remove from favourites
if($matches != '0'){
mysql_query("DELETE FROM ajaxfavourites WHERE user='$user' AND favid='$favid'");
echo "";
}
} else {
// Someone tries to directly access the file!
echo "Invalid session!";
}
Thanks!
Please do necessary steps to avoid SQL injection, also try using mysqli_* functions instead of mysql_* functions
$query = mysql_query("SELECT COUNT(*) as cnt FROM ajaxfavourites WHERE user='$user' AND favid='$favid'");
$res = mysql_fetch_array($query);
// If it is not favourited, add as favourite
if($res[cnt] == 0){
mysql_query("INSERT INTO ajaxfavourites (user, favid, exptime) VALUES ('$user', '$favid', CURRENT_TIMESTAMP)");
echo "";
}
// Instead, if it is favourited, then remove from favourites
if($res[cnt] > 0){
mysql_query("DELETE FROM ajaxfavourites WHERE user='$user' AND favid='$favid'");
echo "";
}
I got it resolved. The reason it wasn't working was it took both values into consideration ($user and $favid). As a result it was always either 0 or 1.
I had to create another mysql query with just one value in it ($user) and then I was able to get the row count. Thanks everyone!
try to use below query, using below query if requested user's session will be 20+ then only insert statement will execute else insert statement will be ignore.
INSERT INTO ajaxfavourites(USER,favid ,exptime)
SELECT 1 AS USER, 1 AS favid, NOW() AS exptime
FROM ajaxfavourites WHERE USER=1 HAVING COUNT(*) >=20;
Related
I have one login page and its database. i want to take the email from there and store it in another table of the same database. Code is give below please have a look and tell me.
Table 1
<?php
session_start();
$email = $_POST['email'];
$password = $_POST['password'];
include 'connection.php';
$sql = "SELECT * FROM users WHERE email='$email' AND password='$password'";
$res = mysql_query($sql);
$count = mysql_num_rows($res);
if($count == 0)
{
echo "Username Password Incorrect";
}
else
{
$_SESSION['email'] = $email;
header("location:home2.php")
}
?>
Table 2
<?php
$email= (HOW TO GET IT FROM SESSION?)
$company = $_POST['company'];
$project = $_POST['project'];
$duration = $_POST['duration'];
$key_learning = $_POST['key_learning'];
include 'connection.php';
$sql = "INSERT INTO `internship`(`id`, `email`, `company`, `project`, `duration`, `key_learning`) VALUES ('', '$email', '$company','$project', '$duration', '$key_learning')";
$res = mysql_query($sql);
$count = mysql_num_rows($res);
if($count == 1)
{
echo "Fail";
}
else
{
$_SESSION['email'] = $email;
header("location:home3.php");
}
?>
From table 1 i want to take email if using session and want to store it in table 2. How to do it?
$email= (HOW TO GET IT FROM SESSION?)
If the 2nd code block is in the same execution context as the first, you can just use the variable $email that you created.
If you're trying to retrieve data from session as the user navigates to a new page, you do:
<?php
session_start();
$email = isset($_SESSION['email'])? $_SESSION['email'] : null;
By the way, in the 2nd code block you're trying to use mysql_num_rows to analyze the effect of an INSERT query. You can't do that. According to the manual:
[mysql_num_rows] retrieves the number of rows from a result set. This
command is only valid for statements like SELECT or SHOW that return
an actual result set. To retrieve the number of rows affected by a
INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().
$res = mysql_query($sql) or die(mysql_error());
if(mysql_affected_rows()){
//success
}else{
//failure
}
You should not be using mysql_ functions anyway and you should most definitely not be inserting user provided values (username, email, password) directly in your SQL statement
<?php
include('session.php');
?>
<?php
require_once('mysql_connect.php');
$query2 ="SELECT id, username, banned FROM login WHERE username ='$login_session'";
$result2 = mysql_query($query2) OR die($mysql_error());
$row = mysql_num_rows($result2);
if($row['banned'] == 1) {
die();
}
?>
Session.php
<?php
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "", "");
// Selecting Database
$db = mysql_select_db("", $connection);
session_start();// Starting Session
// Storing Session
$user_check=$_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql=mysql_query("select username from login where username='$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session =$row['username'];
if(!isset($login_session)){
mysql_close($connection); // Closing Connection
header('Location: login.php'); // Redirecting To Home Page
}
?>
As you can see , im trying to stop people who are banned from loading profile.php
it doesnt stop the profile page from loading
thanks fred, that worked – KIXEYE
make it to an answer, ill mark as answered as soon as i can – KIXEYE
As per the OP's wish:
You're using the wrong function for $row. Either use one that will fetch a row as an array, or change if($row['banned'] == 1) to if($row == 1) to work with mysql_num_rows.
Footnotes:
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
Example pulled from https://stackoverflow.com/a/6620252/
$user = "bob";
$user = mysql_real_escape_string($user);
$result = mysql_query("SELECT COUNT(*) AS num_rows FROM my_table WHERE username='{$user}' LIMIT 1;");
$row = mysql_fetch_array($result);
if($row["num_rows"] > 0){
//user exists
}
Edit:
If your banned row contains 1 or 0 to check if they're banned, then add another parameter to your where clause. I.e.: WHERE username ='$login_session' AND banned !=1 if banned column is an int type. If not, wrap 1 in quotes.
This translates to WHERE username exists and is 'John' and banned does NOT equal 1. Or make it 0, it's your choice.
Then why don't you just fetch user who are not banned:
$ses_sql = mysql_query("SELECT username FROM login WHERE username='$user_check' AND banned <> 1",$connection);
$numofresult = mysql_num_rows($ses_sql);
Then check if it has a result:
if($numofresult > 0){
/* SUCCESS */
}
else {
/* BANNED */
}
To compromise SQL injections, use mysql_real_escape_string() function.
$user = mysql_real_escape_string($username,$connection);
But a better recommendation is to use mysqli_* prepared statement or PDO.
if($stmt = $connection->prepare("SELECT username FROM login WHERE username='$user_check' AND banned <> 1")){
$stmt->execute();
$stmt->store_result();
$numofresult = $stmt->num_rows;
$stmt->close();
}
mysql_num_rows() returns a number of rows, not the rows themselves.
You should use mysql_fetch_assoc() or similar function.
So I am trying to develop an app and I need an API, so I am trying now PHP in order to pass my variables from the app to the MYSQL. I am trying with $_GET first in order to see if everything works fine. I tried to pass variables to the database through MYSQL Workbench and then from the app and worked fine. But, when I emptied the table and tried again it didn't work! So I am guessing that my loop doesn't respond well to the fact that my table is empty(?)
This is the code that checks for the email and username if exists and if not insert the variables:
$result = 'notSet';
$query=mysql_query("SELECT * FROM project");
while ($row = mysql_fetch_assoc($query)) {
if(strcmp($row['email'],$email)==0){ //strcmp uses two strings and it returns an integer, if 0 then no differences if more than 0 then there are
$result = 'Email exists';
}else{
if(strcmp($row['username'],$username)==0){
$result = 'Username exists';
}else{
//encryption
$insert = mysql_query("INSERT INTO project VALUES ('$userid', '$fullname','$username','$password','$course','$year','$age','$email')");
$result = 'Registered';
session_start();
$session = session_id();
$SESSION['username']=$username;
}
}
}
Any ideas??
Your table is empty. $query is returning false. Because of this your loop is not executed. You should change the code like this:
if($query){
while(){
//check username and email
}
}
else{
// execute insert query
}
Can you try this code:
$result = 'notSet';
$query = mysql_query("SELECT * FROM project WHERE email = '$email' OR username = '$username' ");
if(mysql_num_rows($query) === 0 ){
$insert = mysql_query("INSERT INTO project VALUES ('$userid', '$fullname','$username','$password','$course','$year','$age','$email')");
$result = 'Registered';
session_start();
$session = session_id();
$SESSION['username']=$username;
}
else{
$result = 'Username or Email exists';
}
We should add single quotes ' only if field type is not integer type. For eg if userid field is integer type and rest of fields are not integer type then query will be
$insert = mysql_query("INSERT INTO project VALUES ($userid, '$fullname','$username','$password','$course','$year','$age','$email')") or die(mysql_error());
thanks
First: you should switch to PDO or mysqli, because the mysql_* functions are deprecated. Please follow the links in Shais comment.
To get the INSERT done, you've got to change your logic. With your code right now, it will never be executed for an empty resultset. You could do it so:
$query=mysql_query("SELECT * FROM project");
if (mysql_num_rows($query) > 0) {
// we've got results, let's loop through the resultset
while($row = mysql_fetch_assoc($query)) {
// do something with the result
}
}
else {
// we've got no results,
// do the insert
}
mysql_query will return a resource for SELECT type queries. A resource evaluates in PHP to true. You can use mysql_num_rows() to check, whether your resultset is not empty.
Excerpt from the linked manual:
Use mysql_num_rows() to find out how many rows were returned for a
SELECT statement
PS: Please consider the content of the red box.
<?php
$query=mysql_query("INSERT INTO project set id=$userid,
'fullname'=$fullname,
'username'=$username,
'password'=$password,
'course'=$course,
'year'=$year,
'age'=$age,
'email'=$email
");
?>
Can someone please help me. I'm trying to create a basic like system by inserting the values into mysql and auto incrementing the number of times the column 'likes' has been updated.
Basically the script will insert where there is not currently any record and update if there is a record.
I am trying to insert 'user_id' as a value, aswell but only the liked_id is being inserted into the table. the 'likes' column is being auto incremented as it should be but i need to find out how i can insert the user_id which is the users session id aswel and this isn't being put in. also i am trying to update the column 'user_id_has_liked' from enum value 0 to 1 as a final result.
can someone please show me where i am going wrong. thanks
<?php
require_once('includes/session.php');
require_once('includes/functions.php');
require('includes/_config/connection.php');
session_start();
confirm_logged_in();
if (isset ($_GET['to'])) {
$user_to_id = $_GET['to'];
}
if (!isset($_GET['to']))
exit('No user specified.');
$user_id = $_GET['to'];
$result = mysql_query("SELECT * FROM ptb_likes WHERE liked_id ='".$user_to_id."' ");
if( mysql_num_rows($result) > 0) {
mysql_query("UPDATE ptb_likes SET likes = likes +1 WHERE liked_id = '".$user_to_id."' ");
$user_to_id = mysql_query("ALTER TABLE likes AUTO_INCREMENT = $id");
}
else
{
mysql_query("INSERT INTO ptb_likes (user_id,liked_id) VALUES ('".$_SESSION['user_id'].",".$user_to_id."') ");
}
$result1 = mysql_query("UPDATE ptb_likes SET user_id_has_liked='1' WHERE user_id=".$_SESSION['user_id']."")
or die(mysql_error());
if($result)
{
header("Location: {$_SERVER['HTTP_REFERER']}");
}
?>
As the others said, mysql_* statements are depricated, use mysqli_* statements...
The first issue is the code in the user id insert statement was missing some quotes, it should look like this:
mysql_query("INSERT INTO ptb_likes (user_id,liked_id) VALUES ('".$_SESSION['user_id']."','".$user_to_id."') ");
The user_id_has_liked query issue could be caused by the enum variable being an integer in mysql. you could also try saving your query to a query variable and passing the variable to your query function for readability...
$query = "UPDATE ptb_likes SET user_id_has_liked='1' WHERE user_id=".$_SESSION['user_id'];
$result1 = mysql_query($query) or die(mysql_error());
Some code starts with selecting data then check if row numbers are 0 to insert then continue the normal process. The problem is that the normal process is depending on the select statement which does not exist because it was stored before the insert. How can I refresh data request inside PHP without ajax or anything related to html? Here's an example to explain:
$user = $_GET['user']; // not stored user
$select = mysql_query("SELECT * FROM `table` WHERE username = ".$user);
$row = mysql_fetch_array($select);
$rownum = mysql_num_rows($select);
if(!$rownum){
mysql_query("INSERT INTO table (username, something) VALUES ('$user', 1)");
}
/* Here comes the problem */
if($row['something'] == 0){
die("Not found !"); // THIS if returns true since it was not found at first place before inserting
// i want it to refresh the $select data so it could be read as 1
}
How I solved it so far is by repeatedly using the $select and $row code below the insert statement
if(!$rownum){
mysql_query("INSERT INTO table (username, something) VALUES ('$user', 1)");
}
$select = mysql_query("SELECT * FROM `table` WHERE username = ".$user);
$row = mysql_fetch_array($select);
[..]
I want a simpler way to do this
If you know whats in the newly created record, you could just create a new array $row=array('username'->'bob', ...);
BUT if you have default values in the table, or add other things later, you going to have to do a second select.
$user=urldecode($_GET['user']);
$result=mysql_query("SELECT * FROM `table` WHERE username='".mysql_real_escape_string($user)."'");
if(!$result) die("SQL ERROR");
if(mysql_num_rows($result)>0)
{
$row = mysql_fetch_array($select);
}
else
{
mysql_query("INSERT INTO table (username, something) VALUES ('".mysql_real_escape_string($user)."', 1)");
$result=mysql_query("SELECT * FROM `table` WHERE username='".mysql_real_escape_string($user)."'");
if(!$result) die("SQL ERROR");
if(mysql_num_rows($result)==0) die("MAJOR ERRORS IN SQL");
$row = mysql_fetch_array($result);
}
I prefer to use $result as this is the result of you running the query.