value not inserting into mysql and not updating enum value to 1? - php

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());

Related

Correct way to update $_SESSION username in table

I've updated the post since I made a bit of change thanks to #user3282898! Though I still can't push the update to the DB.
The table column $id, $issue, $last_mod has already an existing content, I just need to update the content of issue andlast_modcolumn with respect to its$id`.
Here's what I have so far:
<?php
session_start();
session_regenerate_id();
if(!isset($_SESSION['username']))
{
header("Location: login.php");
}
?>
<?php
$conn = mysqli_connect("localhost", "root", "", "order");
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
//id value
$id = $_GET['id'];
$last_mod = $_SESSION['username'];
mysqli_query($conn, "UPDATE order.coupon SET issue='Resolved', last_mod=".$last_mod." WHERE id=".$_POST['id']) //update won't work
or die(mysqli_error());
header("Location: form.php");
}
else
{
header("Location: form.php");
}
?>
I've tried omitting the $last_mod to isolate the issue of updating and find that this statement works:
mysqli_query($conn, "UPDATE order.coupon SET issue='Resolved' WHERE id=$id")
However it won't work with $last_mod in it:
mysqli_query($conn, "UPDATE order.coupon SET issue='Resolved', last_mod=".$last_mod." WHERE id=".$_POST['id'])
or
mysqli_query($conn, "UPDATE order.coupon SET issue='Resolved', last_mod=".$last_mod." WHERE job_id=$job_id")
Your suggestion/opinion is always welcome, thanks in advance guys!
$_SESSION['username']='$last_mod'
You are updating the $_SESSION['username'] field in your table which does not exist!
The $_SESSION['username'] is the username and the column to be updated is the last_mod.
You should do this as i said in my comment:
UPDATE order.coupon SET last_mod='$last_mod' WHERE id='".$_POST['id']."'");
This should work for you.
$last_mod = $_SESSION['username'];
$query = "INSERT INTO coupon(last_mod)
VALUES ($last_mod)";
that query does not seem to make any sense; so how about ...
$sql = "UPDATE `coupon` SET `last_mod` = NOW() WHERE `coupon_id` = ?";
because it appears, as if you were trying to insert a username as the last_mod (last modification) timestamp of a coupon. just add a die($sql); whenever being uncertain why generated SQL won't work. besides, using the user_id (or the coupon_id) instead of the username would be suggested; because indexed INT fields are way quicker to query by.

Need to add count(*) to this file and an if statement

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;

How do I find out a specific row ID from a table?

Hello I’m working on a project (I’m a total newbie), here ‘s how the project goes…
I’ve created a Create User page, the user puts in the credentials and click on Create Account.
This redirects to another page (process.php) where all MySQL queries are executed-
Note: ID is set to Auto Increment, Not Null, Primary Key. All the data is inserted dynamically, so I don’t know which Username belongs to which ID and so on.
$query = “INSERT INTO users (Username, Something, Something Else) VALUES (‘John’, ‘Smith’, ‘Whatever’ )”
Everything gets stored into the “users” table.
Then it gets redirected to another page (content.php) where the User can review or see his/her credentials.
The problem is, I use SELECT * FROM users and mysql_fetch_array() but it always gives me the User with ID = 1 and not the current User (suppose user with ID = 11). I have no idea how to code this.
There are suppose 50 or more rows,
how can I retrieve a particular row if I don’t know its ID or any of its other field’s value?
You may use:
mysql_insert_id();
Get the ID generated in the last query. Reference: http://us1.php.net/mysql_insert_id
This function return the ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established.
Now you have the id, add that to your WHERE clause.
Note: It would be better if you use mysqli.
You are using mysql_fetch_array() just once, so it is getting you just one row.
what you are writing:
<?php
include('connection.php'); //establish connection in this file.
$sql = "select * from users";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo(row['id']);
?>
What should be there to fetch all the rows:
<?php
include('connection.php'); //establish connection in this file.
$sql = "select * from users";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo(row['id']);
}
?>
Now, what you need, is to get the user id of the registered user at that time.
For that, you need to create a session. Add session_start(); in your process.php and create a session there. Now to get the last id you have to make a query:
select *
from users
where id = (select max(id) from users);
Now this will give you the last id created. Store that in a session variable.
$_SESSION['id']=$id;
Now, on content.php add this:
session_start();
echo($_SESSION['id']);
You have to use WHERE:
SELECT * FROM users WHERE ID = 11
If you dont use WHERE, it will select all users, and your mysql_fetch_assoc will get you one row of all (ie. where ID = 1).
PS: mysql_* is deprecated, rather use mysqli_*.
Using mysql_ commands:
$query = "INSERT INTO users (`Username`, `Something`, `Something Else`) VALUES ('John', 'Smith', 'Whatever' )";
$result = mysql_query($query) or die( mysql_error() );
$user_id = mysql_insert_id();
header("Location: content.php?id=".$user_id);
Or another way to pass $user_id to your next page
$_SESSION['user_id'] = $user_id;
header("Location: content.php");
Using mysqli_ commands:
$query = "INSERT INTO users (`Username`, `Something`, `Something Else`) VALUES ('John', 'Smith', 'Whatever' )";
$result = mysqli_query($dbConn, $query) or die( printf("Error message: %s\n", mysqli_error($dbConn)) );
$user_id = mysqli_insert_id($dbConn);

PHP insert into database query

I am trying to insert values into a database table, a row is inserted but blank no values are inserted. Only the order_id which is the primary key with auto increment increase.
php code:
<?php
$user_get = mysql_query("SELECT * FROM users");
while($row_user = mysql_fetch_assoc($user_get)){
if($row_user['username'] == $_SESSION['username']){
$row_user['first_name'] = $res1;
$row_user['last_name'] = $res2;
$store_order ="INSERT INTO oko (user, product) VALUES ('$res1', '$res2')";
mysql_query($store_order);
}
}
?>
Your assignments are backwards. I think you meant to:
$res1 = $row_user['first_name'];
$res2 = $row_user['last_name'];
Don't you mean:
$res1 = $row_user['first_name'];
$res2 = $row_user['last_name'];
You could also update the SELECT to have a WHERE clause that checks $_SESSION['username'].
You could also just do an INSERT/SELECT:
INSERT INTO oko (user, product)
SELECT
first_name, last_name
FROM
users
WHERE
username = '$_SESSION["username"]'
Your code is vulnerable to injection. You should use properly parameterized queries with PDO/mysqli

Update/Insert into mysql query

I am trying to perform a update/insert into query for MySQL. Should insert, if not already in database.
However, it will not update. My db connection is good. I cannot figure it out.
$sql = "UPDATE jos_bl_paid SET u_id='$uid', m_id = '$mid', t_id = '$cus', pd = '1', paypal_payment='$txn',p_date=NOW() WHERE u_id = '$uid' AND '$mid' = m_id ";
$test45 = mysql_affected_rows();
if ($test45 == 0) {
$sql = "INSERT INTO jos_bl_paid(paypal_payment,u_id,m_id,pd,t_id,p_date)VALUES('$txn','$uid','$mid','1','$cus',NOW())";
if (!mysql_query($sql)) {
error_log(mysql_error());
exit(0);
}
echo 'Yes';
}else{
echo 'No';
}
From the code you are showing you aren't even running the update query. You need to put
if (!mysql_query($sql)) {
error_log(mysql_error());
exit(0);
}
before the line
$test45 = mysql_affected_rows();
for that to even return what you want
I would make these into one statement using the ON DUPLICATE KEY UPDATE mysql command. I would guess that your problem is that the insert may be failing because of some unique key set in you schema even though the actual uid doesn't yet exist so the update also fails. Can you post exactly what error message you get?
check your last value in update query i found an error there and have fixed it from my side
try this
$sql = mysql_query("UPDATE jos_bl_paid SET u_id='$uid',m_id = '$mid', t_id = '$cus', pd = '1', paypal_payment='$txn',p_date=NOW() WHERE u_id = '$uid' AND m_id = '$mid'") or die(mysql_error());
Answer is updated try the updated one
From the code you posted, it appears that you're setting the $sql string to an update statement, but not executing it before checking for the number of affected rows.
You'll probably need to call mysql_query($sql) before checking mysql_affected_rows();
Otherwise you're not telling the database to update anything.
If the new values in update are the same as old one mysql won't update the row and you will have mysql_affected_rows be 0. If you have primary key on fields u_id, m_id you can use INSERT ON DUPLICATE UPDATE http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
If you don't have such you may use the count query:
SELECT count(*) FROM jos_bl_paid WHERE u_id = '$uid' AND '$mid' = m_id
To decide if you should update or insert new one.

Categories