Having trouble allowing people to BUMP a unique entry in table - php

So, my table has a bunch of codes in it and I don't want more than one of the same code in the table so I have it as "UNIQUE."
But, at the same time, I want them to be able to bump their code once every hour.
function some_more_custom_content() {
$output="<BR>";
ob_start();
if ($_REQUEST['code'] != "") {
$code = $_REQUEST['code'];
$query="INSERT INTO `fc` (`code`,`datetime`) values ('" . mysql_real_escape_string($code) . "', now())";
$result=mysql_query($query) or die(mysql_error());
$seconds = time() - strtotime($fetch_array["datetime"]);
if($sql){
echo("Intserted " . htmlentities($code) ." into the top.");
}else{
if ($seconds < 60*60) {
echo ("The code " . htmlentities($code) ." was updated less than an hour ago.");
} else {
$query="DELETE FROM `fc` (`code`,`datetime`) values ('" . mysql_real_escape_string($code) . "', now())";
echo ("Inserted " . htmlentities($code) ." into the top.");
}
}}
Now, I tried to get it so that when the code works it submits the code as normal, which I think works.
Now, if it gets a code that is already there I get the duplicate error "Duplicate entry 'Bob' for key 1"
But, I just want it to delete the old query that it found and to resubmit if it's been more than one hour since last submission.
Any ideas what I am doing wrong?

You can just update the date/time field in the database to reflect the time of the "bump".
if ($_REQUEST['code'] != "")
{
$code = $_REQUEST['code'];
$sql = "SELECT * FROM fc WHERE code = '" . mysql_real_escape_string($code) . "'";
$result = mysql_query($sql);
if (mysql_num_rows($result))
{
$row = mysql_fetch_array($result);
$seconds = time() - strtotime($row["datetime"]);
if ($seconds > 60*60)
{
$sql = "UPDATE fc SET datetime = NOW() WHERE code = '" . mysql_real_escape_string($code) . "'";
mysql_query($sql);
echo("Intserted " . htmlentities($code) ." into the top.");
}
else
{
echo ("The code " . htmlentities($code) ." was updated less than an hour ago.");
}
}
else
{
$sql = "INSERT INTO fc (code, datetime) VALUES ('" . mysql_real_escape_string($code) . "', NOW())";
mysql_query($sql);
echo("Intserted " . htmlentities($code) ." into the top.");
}
}
(I probably shouldn't have re-written your code for you, and there are a few more improvements that could be made, but that reflects the best changes I can make with the minimum of changes (does that make any sense?))

Frank, you do not need two different queries
$query="INSERT INTO `fc` (`code`,`datetime`)
values ('" . mysql_real_escape_string($code) . "', now())
ON DUPLICATE KEY UPDATE datetime = case when now() - interval 1 hour > `datetime`
then NOW()
else `datetime`
end";

Related

insert with a select statement and php variables in 1 MySQL query

i have something like this to insert data from a form to my MySQL table. is my use of select statements in the insert valid? please enlighten me.
if(isset($_POST['date']) && isset($_POST['docName']) && isset($_POST['docSpec']) && isset($_POST['time']) && isset($_POST['symptoms']) )
{
$nameOfUser = $_COOKIE['userlogin'];
$docName = $_POST['docName'];
$date = $_POST['date'];
$symptoms = $_POST['symptoms'];
$time = date('H:i:s',strtotime($_POST['time']));
$id = mt_rand(1000,9999); //generate random appointment id
$insertQuery = "insert into appointment values
($id,(select doctorid from doctors where doctorName like '$docName' ),
$date,$symptoms,
(select patientid from patient where patientFName like '$nameOfUser'), $time)";
if(mysqli_query($conn,$insertQuery)===true)
{
echo "<script>alert('success');</script>";
}
else
{
die('Invalid query: ' . mysql_error());
$message .= 'Whole query: ' . $query;
die($message);
}
}
it says invalid query. the columns in the insert statement is already in right order. can anyone help me?
You have to specify the columns that you are inserting into -
insert into appointment (col1, col2, col3, ...) values
($id,(select doctorid from doctors where doctorName like '$docName' ), $date,$symptoms,(select patientid from patient where patientFName like '$nameOfUser'),$time)";
It looks like you have 6 columns.
EDIT: This syntax may help to clear things up -
$insertQuery = "INSERT INTO `appointment` (`col1`, `col2`, `col3`,`col4`,`col5`,`col6`) ";
$insertQuery .= "VALUES (";
$insertQuery .= "'" . $id . "'";
$insertQuery .= ", '" . "(SELECT `doctorid` FROM `doctors` WHERE `doctorName` LIKE '%" . $docName . "%')" . "'";
$insertQuery .= ", '" . $date . "'";
$insertQuery .= ", '" . $symptoms . "'";
$insertQuery .= ", '" . "(SELECT `patientid` FROM `patient` WHERE `patientName` LIKE '%" . $nameOfUser . "%')" . "'";
$insertQuery .= ", '" . $time . "'";
$insertQuery .= ")";
You're also using LIKE without giving it the chance to find other elements because you're not using wildcards.

Update a sql table field one time with php

Below is my small code for inserting some info into AthleteID. It doesn't actually insert the information to the table though, any help is appreciated. (sorry for asking twice, but I think my first question isn't addressing whatever issue is holding me up here!)
<?php
require_once('resources/connection.php');
echo 'hello noob' . '<br />';
$query = mysql_query('SELECT LName, MyWebSiteUserID FROM tuser WHERE MyWebSiteUserID = MyWebSiteUserID');
$athleteId = strtoupper(substr($row["LName"], 0, 2)) . $row["MyWebSiteUserID"];
$update = "UPDATE `tuser` SET `AthleteID`='$athleteId' WHERE `MyWebSiteUserID` = `MyWebSiteUserID`;";
while($row = mysql_fetch_array($query)){
mysql_query( $update);
}
Where to begin..
1) Your using mysql and not mysqli. mysql is now deprecated but you could be on a PHP 4 system so keep that in mind.
2) You are building the $athleteID before you have found out what LName and SkillshowUserID is.
3) Your using a where of 1 = 1. You dont need this as it will return true for every row.
4) So...
// Execute a query
$results = mysql_query('SELECT LName, MyWebsiteID FROM tuser WHERE SkillshowUserID = SkillshowUserID');
// Loop through the result set
while($row = mysql_fetch_array($query))
{
// Generate the athleteId
$athleteId = strtoupper(substr($row["LName"], 0, 2)) . $row["MyWebsiteID"];
// Generate an sql update statement
$update = "UPDATE `tuser` SET `AthleteID`='" . $athleteId . "' " .
" WHERE LName = '" . $row['LName'] . "' " .
" AND MyWebsiteID = '" . $row['MyWebsiteID'] . "';";
// Fire off that bad boy
mysql_query($update);
}

How can I get the number of rows in a MySQL table with PHP?

Why is my code returning a 500 Internal Server error on the line $result = mysql_query("SELECT * FROM institutions"); Am I doing something horrifically wrong? All I am trying to do is count the number of rows in a MySQL table (called 'institutions') after I have just added a row to that table.
$institution_sql = "
INSERT INTO `institutions`
(`InstitutionName`, `HeaderPictureID`, `Description`, `DevicesInfo`, `DoingInfo`, `FacebookPage`, `Location`, `TwitterHandle`, `Website`, `CreatedAt`)
VALUES
(" . nz($_POST['TempInstitutionName']) . ", 74, 'N/A', 'N/A', 'N/A', 'N/A', 'On the Internet', 'N/A', 'N/A', NOW())
";
$mysqli->query($institution_sql);
if ($mysqli->errno) {
$dbreturn['status'] = "PASSWORD_FAILURE";
} else {
$dbreturn['status'] = "EXEC_SUCCESS";
$result = mysql_query("SELECT * FROM institutions");
$rows = mysql_num_rows($result);
echo "There are " . $rows . " rows in my table.";
$insert_sql = "
INSERT INTO `users`
(`Handle`, `Email`, `FirstName`, `LastName`, `InstitutionID`, `TempInstitutionName`, `TwitterHandle`, `ProfilePictureID`, `HeaderPictureID`, `AccountType`, `CreatedAt`)
VALUES
(" . nz($_POST['Handle']) . ", " . nz($_POST['Email']) . ", " . nz($_POST['FirstName']) . ", " . nz($_POST['LastName']) . ", $num_rows, " . nz($_POST['TempInstitutionName']) . ", " . nz($_POST['TwitterHandle']) . ", " . nz('75') . ", " . nz('74') . ", " . nz($_POST['AccountType']) . ",NOW())
";
$mysqli->query($insert_sql);
if ($mysqli->errno) {
$dbreturn['status'] = "EXEC_FAILURE";
} else {
$dbreturn['status'] = "EXEC_SUCCESS";
$insertid = $mysqli->insert_id;
$password_sql = "
INSERT INTO `passwords`
(`UserID`)
VALUES
('$insertid')
";
$mysqli->query($password_sql);
if ($mysqli->errno) {
$dbreturn['status'] = "PASSWORD_FAILURE";
} else {
$dbreturn['status'] = "EXEC_SUCCESS";
}
} //todo: use a transaction here
}
your problem is that you mixing MYSQLI with MYSQL
rewrite your code using mysqli
$result = $mysqli->query("SELECT * FROM institutions");
$rows = $result->num_rows ;
// and so on ...
you are connecting via mysqli and then you use mysql in your code.
$result = mysql_query("SELECT count(*) FROM institutions");
This will directly return the number of rows.
This link can detail you
http://dev.mysql.com/doc/refman/5.1/en/counting-rows.html
Use
$result = $mysqli->query($institution_sql);
$result->num_rows;
Or for plain old mysql
$result = mysql_query($institution_sql);
mysql_num_rows($result);
Try this:
$result = mysql_query("SELECT count(*) FROM institutions");
MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/select.html
Also this: http://www.w3schools.com/sql/sql_func_count.asp
SQL COUNT(*) Syntax
The COUNT(*) function returns the number of records in a table:
...also, that should be:
VALUES
('" . nz($_POST['TempInstitutionName']) . "', 74
Note the single quotes [unless the 'nz' function takes care of that].

Insert into mysql and php using array

I have part of the code below:
while($array = $result->fetch_assoc() ){
$second_query = "INSERT INTO".TBL_USERSDONTPAY."VALUES ($array[\"username\"], $array[\"password\"], '0',$array[\"userid|\"], )";
$second_result = $database->query($second_query);
}
The query doesn't seem to work. Any clues? I think it's a problem with the quotes or something. How can actually pass array elements?
here is my whole code i want to move one row to another table
$q = "SELECT * FROM ".TBL_USERS." WHERE username = '$subuser'";
$result = $database->query($q);
if($result && $result->num_rows == 1){
while($array = $result->fetch_assoc() ){
$second_query = "INSERT INTO" . TBL_USERSDONTPAY . "VALUES ('" . $array['username'] . "', '" . $array['password'] . "', '0', '" . $array['userid'] ."')";
$second_result = $database->query($second_query);
if($second_result){
// it worked!
$q = "DELETE FROM ".TBL_USERS." WHERE username = '$subuser'";
$database->query($q);
}
}
}
You need to clean that query up and remove the final comma.
$second_query = "INSERT INTO " . TBL_USERSDONTPAY . " VALUES ('" . $array['username'] . "', '" . $array['password'] . "', '0', '" . $array['userid'] . "')";
I see several issues with your query code
escaping of the array indexes in your string:
you can either end the string and concatenate the parts together:
$second_query = "INSERT INTO " . TBL_USERSDONTPAY .
" VALUES ('" . $array['username'] . "', '" . $array['password'] . "', '0', '" . $array['userid'] . "')";
or use the {$var} syntax:
$second_query = "INSERT INTO " . TBL_USERSDONTPAY .
" VALUES ('{$array['username']}', '{$array['password']}', '0', '{$array['userid']}')";
missing spaces (see example code above .. you were missing the spaces before and after the table name)
missing field names. your query may work without if you specify all fields in the right order, but will fail misteriously when you alter the table later (e.g. add a field to the table)
$second_query = "INSERT INTO " . TBL_USERSDONTPAY .
" (username, password, foo, user_id)".
" VALUES ('{$array['username']}', '{$array['password']}', '0', '{$array['userid']}')";
please note you should actually insert the correct field names in the second line of my example above. You can find more information on this in the MySQL docs for INSERT

Only insert a row if for that day and that user, no row exists already

When someone visits X page for the first time, I insert a new row into the table with the current unix time()stamp.
I want to insert new rows, for that user, every 24 hours.. so for example:
Example A) Bob, goes to my site, it inserts a row.. 12 hours later, Bob comes back, it doesn't insert a new row as 24 hours haven't passed yet.
Example B) Bob, goes to my site, it inserts a row.. 24 hours later, Bob comes back, it DOES insert a new row as 24 hours HAVE passed.
I am toying around with this, but cannot think if this is right or not due to my brain being fried.
$time = time();
$difference = 86400;
$timedifference = $time + $difference;
When inserting the row:
mysql_query("INSERT INTO `logs` (`time`, `who`, `site`, `type`)
VALUES('" . $timedifference . "', '" . $ip . "', '" . $rid . "', 'out') ")
or die(mysql_error());
When checking to see if it has been 24 hours or more:
mysql_query("SELECT * FROM `logs`
WHERE `time` < '" . time() . "' AND `type` = 'out'
AND `site` = '" . $rid . "' AND `who` = '" . $ip . "'");
Can somebody please tell me if it's right?
Here is what I've come up with.. it seems to work:
//log check
$ip = ip2long($_SERVER['REMOTE_ADDR']);
$time = time(); //current time
$difference = 86400; //one day in seconds
$timedifference = $time + $difference; //time difference
$logQ = mysql_query("SELECT * FROM `logs` WHERE `time` > '" . time() .
"' AND `type` = 'out' AND `site` = '" . $id .
"' AND `who` = '" . $ip . "'");
$logR = mysql_num_rows($logQ);
if ($logR <= 0){
mysql_query("INSERT INTO `logs` (`time`, `who`, `site`, `type`) VALUES('" .
$timedifference . "', '" . $ip . "', '" . $id . "', 'out') ") or
die(mysql_error());
}
Try
insert ignore into logs
select unix_timestamp(now()), who, site, type
from logs
where
who='{$ip}' and
site='{$rid}' and
type='out' and
unix_timestamp(time)<=unix_timestamp(now())-86400 limit 1;
And check if there a return affected_rows,
if so, meaning the new log added.
I would insert $time, rather than $timedifference.
You need to check to see whether time is less than time() - 86400. If you made time a datetime column, you could do this directly in the query.
In your last query you are not checking whether there is an entry over 24 hours old, you are only checking if there's an entry that is older than NOW.
Correct procedure is:
Create an index on the records for the login time.
SELECT the last record by this ascending index, for a user ('who').
If there is a last, and last is less than 24 hours away from now (time()), then skip creation of a new record.
Otherwise, create one for now (time()).

Categories