variable values conflicts with multiple user - php

Iam new to PHP, trying to do personalized search engine it works fine with the single user... but simultaneously 2 user uses.. the values in the Variable showing wrong values.
Eg:
if user1 search "Apple" then $qry="Apple", same time user2 search "orange" then $qry="orange" that time the user1 will get the remaining stuffs related "orange".
function storewords($str,$id)
{
$words= str_word_count($str,1);
$cntstr = count($words);
//echo $cntstr;
for($i=0;$i<$cntstr;$i++)
{
$allwords= $words[$i];
$insert = "INSERT INTO freq (word,extra) VALUES ('".$allwords."','".$id."')";
$add_member = mysql_query($insert);
}
}
Which i have process of preprocessing, extracting concept for each user's content.. each user have different content.
I think i have expressed my doubt in correct word, if no please excuse. Please help me, Thanks in advance

You just have to store user id somehow, to get separate "searches" for each user later.
$insert = "INSERT INTO freq (userid,word,extra) VALUES (...)";
Then you should select from that table using SELECT with filter like this: "WHERE userid=$current_user_id"

Related

Like system In Php

Hey I want to create like system in php But I am facing some problem on it ...
How can I create Like system that allow only one like per one user??
This is my code
<?php
if(isset($_POST['like'])){
$q = "SELECT * FROM likes WHERE `username` = '".$_SESSION['recieveruser']."'";
$r = mysqli_query($con, $q);
$count = mysqli_num_rows($r);
if ($count == "0") {
$q1 = "INSERT INTO likes (`username`, `likecount`)VALUES('".$_SESSION['recieveruser']."', '1')";
$result1 = mysqli_query($con, $q1);
} else {
while($row = mysqli_fetch_array($r)) {
$liked = $row['likecount'];
}
$likeus = ++$liked;
$q2 = "UPDATE likes SET likecount='".$likeus."' WHERE username = '".$_SESSION['recieveruser']."'";
$result2 = mysqli_query($con, $q2);
}
}
give me some suggestions
I want only one like per user
In this code every user can give Many likes to another user but I want only one like per one user and I want to display the name of the user who gave like if it's possible
This is only user like code...
I created simliar like system on my website. In my likes table, I had these columns:
Id of comment, that has been liked
Id of user who liked
Id of like (for removal)
When user clicked like, I inserted new row into likes table, with two known values. ID of like was autoincremented.
To show number of likes, I filtered by id of comment and grouped by users id (just to be sure). The number was obtained using count.
select count(*) from likes where comment_id = 666 group by user_id;
Even if you let user insert multiple times, the like counts only as one. But best would be to check, if current user already liked and dont let him do that. For this task, insert on duplicate key update could be used, to spare if exists db request (select).
You should not use the code you posted above. First of all, your code is vulnerable to SQL-Injections and therefore you should use Prepared Statements (https://www.php.net/manual/de/mysqli.quickstart.prepared-statements.php). Second, $_SESSION variables are depricated (https://www.php.net/manual/en/reserved.variables.session.php).
Lets assume you want users only to be able to like a post once. Then, instead of the column likecount you would need a post-id which uniquely identifies the post.
Define the combination post-id and username as a primary key in your database.
Now your code just have to check whether you find the username with the according post-id in the table likes.
In case you do not find the username with the according post-id in the table, you have to INSERT the username and the post-id

How to update database values for a whole day

I am building a web application, for travelling. I have managed to get users to be able to insert how much they have spent on each category (i.e. travel, accomodation, food, etc) into the database once from a form. However, I want them to be able to contiously add to the total value of each category for just that day using the same form, and then everyday have a new total for each category as well.
I'm not quite sure how I would do that at the moment.
Here is my code so far for inserting the values into the database from my form (which works):
if(isset($_POST['addinfo_button'])){
$Food = $_POST['food'];
$Transport = $_POST['transport'];
$Accom = $_POST['accomodation'];
$Entertain = $_POST['entertainment'];
$Souvenir = $_POST['souvenirs'];
$Misc = $_POST['miscellaneous'];
$Date = date("Y-m-d");
$Trip_id;
$sql = "SELECT * FROM trips WHERE id =$user_id_session AND date1 <= '$Date' && date2 >= '$Date'";
$records = mysql_query($sql);
while($trip=mysql_fetch_assoc($records)){
$Trip_id = $trip['trip_id'];
}
$foreignkey = $user_info['id'];
$sql = $con->query("INSERT INTO todays_spend (food, transport, accomodation, entertainment, souvenirs, miscellaneous,date, trip_id, id)Values('{$Food}', '{$Transport}', '{$Accom}', '{$Entertain}','{$Souvenir}', '{$Misc}','{$Date}','{$Trip_id}','{$foreignkey}')");
header('Location: budgetbuddy.php');
}
Would I have to do something similar to this? or modify this one slightly?
Could not write code for you. But I can give you an Idea how you can achieve this having only one form.
Create a table with your needs.I mean your entertainement, food, etc along with their name and Id. If you can make user enter their name or anything that users can uniquely identified. Then things go easier. When a user enter their how much they spent insert into table along with their name or identifier. Next time same user enter details simply find if already user has anything updated on same day , if user added anything before simply update the table by adding previously existing values to new values. Update them. Now you easily even find how much each user spent on particuler catogery.Hope it helps. Thank you.

how to fetch data from database dynamically for multiple user in PHP and MySQL

This question is bit complex atleast for me. Well, I am working on a project and need some bit more help..
Actually i have a module , where when 1 user login he get limited data from 1 table and he update its records. That is done !
second thing, the issue : i have 5 user who will login and will work on data.
but no user should get same data, like we have 1000 records.
Then when 1st user login: he get 10 records from 1 - 10.
2nd user login : he get next 10 ; 11- 20.
same so on..
and when next day they login ; they get records from 51.
because 5 user last day worked on first 50 data records.
My issue is how to achieve that 2 goals ?
do i need a framework for this ?
or it can be done using simple php n sql ?
any support will be helpful for me. :)
Ok. This is just a raw answer to give you a better idea. This is how you will insert the login .
Consider having a table containing following fields,
Table Name: Temp_Table
user, assigned_rows_last_no, date_assigned
<?php
$con=mysqli_connect("example.com","hiren","abc123","my_db");
// These things can be included into a single file say config.php and including in every file so that you dont need to specify connection string everytime.
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//This query required to be included into the file, which is exactly after login.php
$sql = mysqli_query($con,"SELECT assigned_rows_last_no FROM Temp_Table ORDER BY assigned_rows_last_no DESC LIMIT 1");
// This is because I want the last row number assigned to the user.
IF ($sql == 0) // Check whether the return answer is NULL or not.
{
// If the result is empty than add new entry of the user with defined row number.
// Suppose that current username can be retrieved from SESSION and stored into a variable.
$insertquery = mysqli_query($con, "INSERT INTO Temp_Table Values ('" . $username . $"', 10, CURDATE()");
mysqli_close($con);
}
else
{
// Select the last entry of row and add 10 to it. Ex. User2 has been assigned to 11-20, table contains 20 in the row of user2, now user3 comes, this query will select the row_no, add 10 and insert again into the table (i.e. value 30 which means 21-30.)
settype($sql, "int");
$sql = $sql + 10;
$insertquery = mysqli_query($con, "INSERT INTO Temp_Table Values ('" . $username . $"', '" . $sql . "', CURDATE()");
mysqli_close($con);
}
mysqli_close($con);
?>
The field Date will help you to recognize the entries of today, so that you can set your logic for "There should be no duplicate entries for the same user on same day"
Now, Make you own page, which check the above mentioned things, and assign the rows to the users.
Note: This code will only be able to clear out the logic for you, I am not sure whether it will work in your code without any changes.
You don't need a extra framework. Simply done with php 'n' sql!
Why you don't save the last edited lines (linenumbers) in a extra SQL-Table? Maybe with the username / userid.

I want to get output result from second table based on first table rows output in json-php

I have knowledge of PHP but I am still learning Json. First of all I want to clear what I am looking for. I have two tables in mysql database, table1(users) and table2(business). Table "users" contains these rows(id, uid, business_name) and table "business" contains these rows(id, uid, category).
I have following code in PHP page:
if(isset($_GET['catName'])) {
$cat = $_GET['catName'];
$stmt = $pdo->prepare("SELECT id, uid, category FROM business WHERE category = ? ");
$stmt->execute(array($_GET['catName']));
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
I am able to get json output on my html page e.g.
101, 102, 103 and so on.
But I want to get business_name rows like ABC Business, XYZ Business, 123 Business and so on from second table "business" based on the output uid from first table. In brief, I want business_name output instead of uid output from second table.
Please help me. Thank you so much in advance.
You have an associative array, with the results from the query. It sounds like you want the business names, but you are not querying for them.
So the first step would be fix your broken query!
It's difficult to tell what you want from the query, but you're mixing the users table with the business table, so I'm guessing you really want business names based on users.
SELECT b.business_name FROM users u JOIN business b ON u.uid = b.uid WHERE category = ?
Then, you have to access your $arr variable correctly to get the business names
foreach ($arr as $bus_sql_result) {
echo $bus_sql_result['business_name']."\n";
}
This is not in JSON format, I'm not sure what JSON has to do with what you want, but if you really want it that way, you could try something like
$business_names = array();
foreach ($arr as $bus_sql_result) {
$business_names[] = $bus_sql_result['business_name'];
}
echo json_encode($business_names);
Thank you so much Chris and Jormundir. Joining the both tables really solved my problem. This is what I have done:
$stmt = $pdo->prepare("SELECT business.uid, users.business_name FROM business,users WHERE business.uid = users.uid AND business.category= ? ");
In html page I have put "business_name" array instead of "uid" and I have got result whatever I was looking for.
Thanks you so much all of you.

How do I insert a related row into a mysql database?

I'm completely stumped. I have two tables set up in my database, one called subjects and one called pages. I gave the pages a subject_id in my database to connect them to subjects. I've dynamically displayed a nav containing the subjects and there child pages. I've also created a few php files that delete subjects, edit subjects, and edit pages. I've now added a link onto each subject so that when you click on the subject, it takes you to a page where, hopefully, I'll be able to add a new page under the chosen parent subject. It's also worth noting that i am sending the parent subject id in the link to add the page.
Here's the fraction of code that i believe is somehow giving me problems:
if(empty($errors)){
$id = mysql_prep($_GET['subj']);
$menu_name = mysql_prep($_POST['menu_name']);
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);
$content = mysql_prep($_POST['content']);
$subject = get_subject_by_id($id));//This fetches the subject id from the db
$query = "INSERT INTO
pages WHERE subject_id = $subject
(
menu_name, position, visible, content
) VALUES (
'{$menu_name}', {$position}, {$visible}, '{$content}'
)";
$result = mysql_query($query, $db_connect);
if (mysql_affected_rows() == 1){
echo "<p>suceess</p>";
} else { ....
I know this is out of context but i thought someone might have some luck by spotting the problem. If anybody has ANY insight on this I would appreciate it.
You can't have a where clause in an insert statement.
Without the where clause the table will get the inserted row. If you are trying to update an existing row, which would justify a where clause, then you need to use an update statement.
the correct INSERT syntax is:
INSERT INTO pages (subject_id, menu_name, position, visible, content) VALUES (?,?,?,?,?)
of course, bind with the appropriate parameters and do not use string interpolation.

Categories