SOLVED
I have a problem that has been tearing me apart for the last two weeks.
I want to be able to delete a post in my table based upon a given variable. Because of the different user content it's pretty difficult to delete a post that belongs to that certain user.
What I really want to know is how to get that certain ID from $rad on the admin.php to the delete query on perform_remove_time.php. Should I use GET or POST or any other method? I will have "input sanitize" with real_escape_string later on and I'm also aware of mysqli vs mysql. My code isn't pretty please bear with me.
From perform_remove_time.php
<?
$user_id = $_SESSION['user_id'];
$time_id = ($_GET['time_id']);
$sql = "DELETE FROM time WHERE time_id = '$time_id' AND user_id = '$user_id'";
$result = mysql_query($sql);
if($result) {
echo "<h3>Time deleted!</h3>";
header("location:admin.php");
} else {
echo "Something is wrong!";
}
?>
This is where the posts is fetched and displayed - admin.php
$user_id = $_SESSION['user_id'];
$time_id = ($_GET['time_id']);
$sql = "SELECT * FROM time WHERE user_id = '$user_id' ORDER BY time_id DESC";
$result = mysql_db_query("database","$sql") or die (mysql_error());
while ($rad=mysql_fetch_array($result)) {
?>
<?='Work session: '.$rad["time_id"]?> | Time on projekt: <?=$rad["hours"]?> | Delete work session
Also from admin.php further up on the page
if (!isset($_SESSION['user'])) {
header("Location:default.php");
die();
}
From my observation, your delete link in 'admin.php' would not get you to 'perform_remove_time.php' with the right GET parameter (time_id) for your delete code to work.
So i made a little modification to your delete link:
<? echo "<a href='perform_remove_time.php?time_id=".$rad['time_id']."'> | Delete work session</a>"; ?>
That modification would enable your delete link get to 'perform_remove_time.php' with the right GET parameter for it to work
Update
The code snippet from perform_remove_time.php looks fine to me, and would work as long as $time_id and $user_id contains valid values and also if your sql statement is correct. Now, from the code snippet you posted, I discovered that in perform_remove_time.php $time_id would contain nothing because there was no time_id GET parameter in your delete link code | Delete work session, the GET Parameter there is id, so I simply changed id to time_id to get things working.
new delete link code
<? echo "<a href='perform_remove_time.php?time_id=".$rad['time_id']."'> | Delete work session</a>"; ?>
Related
I have been trying to write a code in PHP that generates a random code, stores it in the database and asks the user to enter it. if the code is entered more than 3 times, the code needs to be expired. this is my code:
<?php
include("ProcessCode.php");
$con = mysqli_connect("localhost","root","") ;
if(mysqli_select_db($con,"login"))
{
echo 'database selected' ;
}
$rand=rand();
echo $rand ;
$sql = "INSERT INTO random (number) VALUES ('$rand') " ;
if(mysqli_query($con,$sql))
{
echo 'inserted' ;
}
?>
$CodeCheck=$_POST['code'];
//Establishing Connection with server
$conn = mysqli_connect("localhost", "root", "");
//Selecting Database
$db = mysqli_select_db($conn, "login");
//sql query to fetch information of registerd user and finds user match.
$query = mysqli_query($conn, "select * from random WHERE number='$CodeCheck'");
$rows = mysqli_num_rows($query);
if (mysqli_num_rows($query) > 0)
{
echo " Code exists already.";
}
if($rows == 1)
{
header("Location: Success.php");
}
else
{
$error = " Code is Invalid";
echo $error;
}
could you please explain how to implement the expiry part?
in your table you could have a field for count. When use login and login is wrong, add + 1 to your count. When user login successfuly, reset the count. If count meet +3, reset the code.
i understand from your question that you need the logic on how to make the random_code expired after inserting from interacted users on your website 3 times ,assuming that , as long as the code is not expired he will be able to do his inserts and you may load it on your page .
i would do that through database queries .
Please follow this instruction listed below
instructions :
while your php page generate the random code , you may store it in database table with a auto reference key , for instance ,
assuming that you have randomly generated a code as below :
"Some random code here"
the above code which was generated by your php page have load it from mysql table called Random_Generated_Code , i would go to edit this table and add new field in it and call it generated_Code_Reference_Key ( could be auto serial number ) to avoid any duplication as well make additional field called Expire_Flag which we are going to use later.
so once your page have loaded the above example code , you should retrieve the generated_Code_Reference_Key along with it and keep it in hidden variable on your page
it should be loaded on the page based on expire_Flag value as a condition
select generated_code from Random_Generated_Code where expire_flag = ""
now once the user try to insert that generated code , in each time he insert it define another table in your database lets call it ( inserted_Codes_by_users) and store in it the username of whoever is doing that on your website as well you have to store the generated_Code_Reference_Key which we are storing in hidden variable as mentioned earlier to indicate which code was used while inserting.
now during page load or any event you want you can find expired code by make select statement from the inserted_Codes_by_users table
select count(generated_Code_Reference_Key) as The_Code_Used_Qty from inserted_Codes_by_users where username = username_of_that_user
so you can get how many times this user have inserted this specific generated_random_Code
retrieve result of the query in a variable and to make sense lets call it The_Code_Used_Qty and make if condition on page load event or any event you like
if The_Code_Used_Qty = 3 then
fire update statement to first table which loaded that random generated code
and update the expire_flag field for that code (Expired) based on reference_key
update Random_Generated_Code set expire_Flag = "expired" where generated_Code_Reference_Key = "generated_Code_Reference_Key" << the one u stored in hidden variable
end if
so now that will get you directly to the point of why we are loading random_generated_code table first time with that condition expire_flag = ""
as it will only retrieve the codes which is not expired .
hopefully this will help you to achieve what you want .
good luck and let me know if you need any help or if you face any confusion while reading my answer.
Good luck .
I've put certain values like a user id into the url e.g /index.php?id=1 in previous PHP files.
I have a HTML form that has an action like this:
<form name="staffResponse" method="post" action="respond_ticket.php?id=<?php echo $_GET['id']; ?>">
Which when you go to respond_ticket.php and simply echo the value for the id and look at the URL it does it successfully. Whats more the data that I am posting to that file is also done without problem. However I want to then write that information to a table but it does not seem to work.
Here is the respond_ticket.php file
<?php
include 'database/db.php';
$id = $_GET['id'];
$staffResponse = $_POST['staffResponse'];
$sql = "INSERT INTO tickets (staffResponse) VALUES ('$staffResponse') WHERE id='$id'";
$result = mysqli_query($connection, $sql);
if ($result === TRUE) {
echo '<p>Response ' . $staffResponse . ', has been added</p>';
}
else {
echo '<p class="warning">Unable to respond</p>';
}
?>
The db.php file has all the necessary information for connection to the database i.e name password etc. It also opens the question there too.
I keep just getting the warning message that I wrote.
you cant do an insert with a where modifier like this. change it to update ;)
UPDATE tickets SET staffResponse = '$staffResponse' WHERE id = '$id'
You are not supposed to use a WHERE clause with INSERT
$sql = "INSERT INTO tickets (staffResponse) VALUES ('$staffResponse')";
You may wish to set your tickets table up with auto increment so you dont need to insert an id if you haven't done that already.
use ON DUPLICATE UPDATE if it helps
INSERT INTO tickets (id,staffResponse) VALUES ('$id','$staffResponse')
ON DUPLICATE KEY UPDATE id=VALUES(id), staffResponse=VALUES(staffResponse)
I hope this is not a bad question. I've been trying to understand what I'm doing wrong but I can't.
I'm pretty new to php and mysql so I'm really confused...
I have this database (I will attach a mysql workbench model screenshot)
And I'm trying to insert the sales into sale and print_for_sale tables. The queries seem to be working and the data shows up in phpmyadmin. No error pops up. However the sale user in the sale table is always the same id. Even if I use a different user login. And in the print_for_sale table the fk_sale_id is always the same id. And the price_print_for_sale is always the same as well. That is not supposed to happen. What am I doing wrong?
Can anyone help me?
Thank you!
Here is my php code:
<?php
session_start();
$user_id = $_SESSION['user_id'];
print_r($_POST);
$id_print= $_POST['print_id'];
include('database.php');
$bought_sizes=$_POST['sizes'];
$number_of_bought_sizes= count($bought_sizes);
//header('location:index.php?area=printstore');
$sqlinsertsale = "insert into sale
(fk_sale_user,
fk_payment_id)
values(".$user_id.", 1)";
//payment is not yet defined so I'm using 1 just to try.
mysql_query($sqlinsertsale);
for($i=0; $i< $number_of_bought_sizes; $i++){
$selectmultiple = "select *
from print_has_size
inner join size on fk_size_id = size_id
inner join print on fk_print_id = print_id
where print_id =".$id_print."";
$resultmultiple = mysql_query($selectmultiple);
$linemultiple = mysql_fetch_assoc($resultmultiple);
$size_price = $linemultiple["size_price"];
$selectsale = "select *
from sale";
$resultsale = mysql_query($selectsale);
$linesale = mysql_fetch_assoc($resultsale);
$sale_id = $linesale["sale_id"];
//$sale_id = mysql_insert_id();
/*PARA CADA 1 DOS TAMNHO*/
$sqlinsertprintforsale = "insert into print_for_sale
(fk_sale_id,
price_print_for_sale)
values(".$sale_id.", ".$size_price.")";
mysql_query($sqlinsertprintforsale);
}
?>
I'm also going to attach a screenshot of the selection page so you can see the markup in case it helps.
Edit:
(I'm adding the php code from where I check the user login)
<?php
session_start();
include('database.php');
$user=mysql_real_escape_string($_POST['user_login']);
$pass=mysql_real_escape_string($_POST['user_pass']);
$sql="select user_id, user_name
from user
where
user_login='".$user."'
and user_pass = MD5('".$pass."')";
echo $sql;
$result = mysql_query($sql);
$num_of_regs = mysql_num_rows($result);
echo "<br>".$num_of_regs;
if($num_of_regs!=1) {
header('location:index.php?login=done');
}
else {
$line = mysql_fetch_assoc($result);
$user_name = $line['user_name'];
$user_id = $line['user_id'];
$_SESSION['user_name'] = $user_name;
$_SESSION['user_id'] = $user_id;
header('location:index.php');
}
?>
And I did a log out system too.
<?php
session_start();
session_destroy();
header('location:index.php');
?>
Now I noticed that the sale table is not receiving data..
Only the print_for sale is. Wrong data still. Same IDs... Why? :(
This is the only error message that I get when I used the code
ini_set('display_errors', true); error_reporting(E_ALL);
Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /Applications/XAMPP/xamppfiles/htdocs/printstore/database.php on line 7
Added
echo $_SESSION['user_id'];
And this is my output for user 1:
And for user 2:
it seems to be ok, it recognizes user 1 and 2.
Table sale is not being refreshed when I make a "new purchase" and table print_for_sale is refreshed with the same sale id. Always 3 (as shown in the screenshot)
I deleted every row from sale in phpmyadmin and tried again. It's working. Sale table seems to be working fine. The only problem now is the table print_for_sale which even when I use a different user (and it shows up ok in the sale table), it still shows the same sale_id and the same price_print_price which is always 25). And in this case I never selected anything costing 25. -
Give this a shot. It seems that you're getting the same result because you never loop through your results. Also make sure that your field names are exactly the same as your field names in your DB.
$selectsale = "select *
from sale";
$resultsale = mysql_query($selectsale);
while($linesale = mysql_fetch_assoc($resultsale))
{
$sale_id = $linesale["sale_id"];
}
when you logout you should destroy your sessions
I assume you have a logout page like logout.php. In it you should set below lines. If you don't do that session values can't change.
<?php
session_start();
session_destroy();
?>
Also if you store your user id on a session variable, only closing all browser windows than reopen and login will help you.
Extra info for you future code life: WHY PDO http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
First of all I stored users in the same table and I created a page called welcome.php, where I want it to be echoing out user info from MySQL based on their entry.
Now when I created first user and echo it out to this welcome.php, it comes out from the table, and if I create another user info in the same table for it to echo out at the same welcome.php based on the user login info such as, if I create a user called John Fred etc and a user called Michael Kenneth etc.
So user John Fred comes out to the welcome.php with its information from the same table, and then user Michael Kenneth doesn't come to welcome.php when i sign with user Michael Kenneth instead it shows only user John Fred. I don't know where this error comes from; maybe from the login.php, or from welcome.php.
Here is my code echoing in welcome.php
<?php
$tnumber2 = "{$_SESSION['tnumber2']}";
// Connect to the database
$db = mysql_connect("$Sname","$Uname","$Pname") or die("Could not connect to the Database.");
$select = mysql_select_db("$Dname") or die("Could not select the Database.");
$sql="SELECT * FROM `$Tname` LIMIT 0, 25 ;";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
?>
<? echo $rows['tnumber2']; ?>
Another script for other user info which I store for another table:
<?php
// Connect to the database
$tnumber2 = "{$_SESSION['tnumber2']}";
$db = mysql_connect("$Sname","$Uname","$Pname") or die("Could not connect to the Database.");
$select = mysql_select_db("$Dname") or die("Could not select the Database.");
$sql="SELECT * FROM `$UPname` LIMIT 0, 25 ;";
$result=mysql_query($sql);
?>
<?php
while($rows=mysql_fetch_array($result)){ // Start looping table row
?>
<? echo $rows['pdate']; ?>
<?php
// Exit looping and close connection
}
mysql_close();
?>
And here is my login.php in this case am using one input form:
<?php
session_start();
ob_start();
?>
<?php
if ($_POST['submit']) {
$tnumber2 = $_POST['user'];
if ($tnumber2) {
require("connect.php");
$query = mysql_query("SELECT * FROM users WHERE tnumber2='$tnumber2'");
$numrows = mysql_num_rows($query);
if($numrows == 1) {
$row = mysql_fetch_assoc($query);
$id = $row['id'];
$tnumber2 = $row['tnumber2'];
if ($tnumber2 == $tnumber2) {
$_SESSION['id'] = $id;
$_SESSION['tnumber2'] = $tnumber2;
header("Location: welcome.php");
}
}
else
include "error.php";
}
}
?>
I have tried all I can on this, maybe I might be a fool to think that such thing is possible but I am not a PHP professional, just a learner, please any help will be gladly appreciated.
Assuming the session has indeed stored the data of the logged-in user, you need to change "welcome.php" so it reads the correct user with a WHERE clause:
<?php
// Retrieve the ID of the user (and untaint it too)
$id = (int) $_SESSION['id'];
// Connect to the database (I've removed the unnecessary quotes)
$db = mysql_connect($Sname, $Uname, $Pname) or die("Could not connect to the Database.");
$select = mysql_select_db($Dname) or die("Could not select the Database.");
// Here is the query from the users table, we're selecting one user here
$sql="SELECT * FROM `users` WHERE `id` = $id;";
$result = mysql_query($sql);
$rows = mysql_fetch_array($result);
?>
<!-- Let's see what is in rows now, should be just one record -->
<?php print_r($rows) ?>
I would advise that you try to understand each part of the code above, and indeed the same for the code you have - don't just copy-and-paste without knowing what each bit does. If you get stuck on something, don't be afraid to look it up in the manual!
I've used print_r to just dump the row result - you can use the contents of that to determine what columns and other data you wish to extract out of it. After you have done that, the print_r can be removed.
Bear in mind that your login is not testing for password correctness - it only checks that someone has entered a particular username in login.php. If you want users to log on with a username and password, that needs to be designed and implemented as well. There are many questions on this site with best-practice techniques on how to do that, if that's of interest to you.
It has, incidentally, been rather difficult to understand what you are doing. I don't think this is a problem with your English, which seems fine to me. Rather, it's worth remembering to write in short sentences (no more than 20 words, say) and short paragraphs (no more than 4 or 5 sentences). And keep your descriptions as short as you can - it makes the difference between people helping you and their deciding they don't understand what you are trying to do. I expect this advice would be just as relevant in your native language as well!
Also, remember to add as much useful information to a question as you can, and if people ask for clarification, make sure you answer all their questions. Remember that people here are volunteers, and you need to make their job as easy as possible.
Please could someone help im building my first website that pulls info from a MySQL table, so far ive successfully managed to connect to the database and pull the information i need.
my website is set up to display a single record from the table, which it is doing however i need some way of changing the URL for each record, so i can link pages to specific records. i have seen on websites like facebook everyones profile ends with a unique number. e.g. http://www.facebook.com/profile.php?id=793636552
Id like to base my ID on the primary key on my table e.g. location_id
ive included my php code so far,
<?php
require "connect.php";
$query = "select * from location limit 1";
$result = #mysql_query($query, $connection)
or die ("Unable to perform query<br>$query");
?>
<?php
while($row= mysql_fetch_array($result))
{
?>
<?php echo $row['image'] ?>
<?php
}
?>
Thanks
Use $_GET to retrieve things from the script's query (aka command line, in a way):
<?php
$id = (intval)$_GET['id']; // force this query parameter to be treated as an integer
$query = "SELECT * FROM location WHERE id={$id};";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) == 0) {
echo 'nothing found';
} else {
$row = mysql_fetch_assoc($result);
echo $row['image'];
}
There are many things to consider if this is your first foray into MsSQL development.
SQL Injection
Someone might INSERT / DELETE, etc things via using your id from your url (be careful!, clean your input)
Leaking data
Someone might request id = 1234924 and you expected id = 12134 (so some sensitive data could be shown, etc;).
Use a light framework
If you haven't looked before, I would suggest something like a framework (CodeIgniter, or CakePHP), mysql calls, connections, validations are all boilerplate code (always have to do them). Best to save time and get into making your app rather than re-inventing the wheel.
Once you have selected the record from the database, you can redirect the user to a different url using the header() function. Example:
header('Location: http://yoursite.com/page.php?id=123');
You would need to create a link to the same (or a new page) with the URL as you desire, and then logic to check for the parameter to pull a certain image...
if you're listing all of them, you could:
echo "" . $row['name'] . ""
This would make the link.. now when they click it, in samepage.php you would want to look for it:
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
//query the db and pull that image..
}
What you are looking for is the query string or get variables. You can access a get variable through php with $_GET['name']. For example:
http://www.facebook.com/profile.php?id=793636552
everything after the ? is the query string. The name of the variable is id, so to access it through your php you would use $_GET['id']. You can build onto these this an & in between the variables. For example:
http://www.facebook.com/profile.php?id=793636552&photo=12345
And here we have $_GET['id'] and $_GET['photo'].
variables can be pulled out of URL's very easily:
www.site.com/index.php?id=12345
we can access the number after id with $_GET['id']
echo $_GET['id'];
outputs:
12345
so if you had a list of records (or images, in your case), you can link to them even easier:
$query = mysql_query(...);
$numrows = mysql_num_rows($query);
for ($num=0;$num<=$numrows;$num++) {
$array = mysql_fetch_array($query);
echo "<a href=\"./index.php?id=". $row['id'] ."\" />Image #". $row['id'] ."</a>";
}
that will display all of your records like so:
Image #1 (links to: http://www.site.com/index.php?id=1)
Image #2 (links to: http://www.site.com/index.php?id=2)
Image #3 (links to: http://www.site.com/index.php?id=3)
...