I have a system where the user sends an invitation, and once the official accepts, it will be saved to the database and sync to the official's calendar.
I'm trying to run a query where it checks if there are any events on that current time. Basically if it returns at least 1, it means the invitation wont send because there is a conflict but it just ignores the row count from MySQL database. Here is my code:
// variables
$id = $_GET['id'];
$dStart = $_POST['dStart'];
$dEnd = $_POST['dEnd'];
$time = $_POST['time'];
$time_end = $_POST['time_end'];
// convert them into date formats
$date = date("Y-m-d", strtotime($dStart));
$date2 = date("Y-m-d", strtotime($dEnd));
$time_f = date("H:i:s", strtotime($time));
$time_end_f = date("H:i:s", strtotime($time_end));
// set default timezone
date_default_timezone_set('Asia/Manila');
// check if date is occupied
$query_check = mysqli_query($con, "SELECT COUNT(*) as total FROM events WHERE (date_start = '$date') AND ((`time` BETWEEN '$time_f' AND '$time_end_f') OR (`time_end` BETWEEN '$time_f' AND '$time_end_f')) AND pastor_id = '$id' AND invite = 0 AND reschedule = 0") or die (mysqli_error($con));
$fetch_check = mysqli_fetch_array($query_check);
if ($fetch_check['total'] >= 1) {
echo "<center><p>Sorry, this time is occupied. Please select another schedule</p><p>If you haven't, please refer to this pastor's calendar which can be found by <a href='profile.php?id=$id&grid=true'>clicking here.</a></p></center>";
} else {
// generate random reference code
$ref_code = rand(1000000, 9999999);
$_SESSION['reference_code'] = $ref_code;
$ref_code_final = $_SESSION['reference_code'];
// insert to events table
$query = mysqli_query($con, "INSERT INTO `events` (`id`, `reference_code`, `name`, `description`, `date_start`, `date_end`, `time`, `time_end`, `pastor_id`, `pastor`, `category`, `venue`, `invite`, `sender_name`, `sender_address`, `sender_phone`) VALUES (NULL, '$ref_code_final', '$name', '$description', '$date', '$date2', '$time', '$time_end', '$id', '$pastor', '$category', '$venue', '1', '$sender', '$address', '$phone')");
header("Location: send.php?sendid=$id&success");
}
I checked so many times on PHPMyAdmin, the query returns at least 1 from my database. I made another .php file and ran the query there, echoed the result and it still outputs 1. But for some reason, when I use the query here it COMPLETELY ignores the if statement and goes directly to else
Related
I am trying to build an SQL query that will insert the check-in time for a child at a fictional daycare facility. Here is a condensed version of my query code:
$childFirstName = $_POST['childFirstName'];
$childLastName = $_POST['childLastName'];
$now = new DateTime();
$nowDate = $now->format('m-d-Y');
$nowTime = $now->format('h:i');
$sql_childID = "SELECT id FROM child
WHERE firstName = '$childFirstName'
AND lastName = '$childLastName'";
$result = $pdo->query($sql_childID);
$row = $result->fetch();
$sql = "INSERT INTO checkinout(date, in, child_id) VALUES(?,?,?)";
$statement = $pdo->prepare($sql);
$statement->bindValue(1, $nowDate);
$statement->bindValue(2, $nowTime);
$statement->bindValue(3, $row['id']);
$statement->execute();
The checkinout table uses VARCHAR datatypes for the date and in columns. Originally they were set to use DATETIME, but I received the same errors.
Right now I get the following errors returned...
You can see from the error messages that my values are getting passed in the way I want them to, but I don't understand where my syntax error would be.
Enclose your field names with backticks. Two of them are reserved words (date and in):
$sql = "INSERT INTO checkinout(`date`, `in`, `child_id`) VALUES(?,?,?)";
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
I need to insert data from a webpage into a database. I'm using this code to send it to the php file
$.getJSON('./calendar.php?action=save&id=0&start='+ds.getTime()/1000+'&end='+df.getTime()/1000,
{
'body':$('#calendar_new_entry_form_body').val(),
'title':$('#calendar_new_entry_form_title').val()
}
and then I want to insert the 4 fields into a mySQL database. Right now, I can retrieve the data using
$start_date=(int)$_REQUEST['start'] - 60*60;
$data=array(
'title'=>(isset($_REQUEST['title'])?$_REQUEST['title']:''),
'body' =>(isset($_REQUEST['body'])?$_REQUEST['body']:''),
'start'=>date('c',$start_date),
'end' =>date('c',(int)$_REQUEST['end'] - 60*60)
);
Then I save it into a session variable just to see if I am actually recieving it
$id=(int)$_REQUEST['id'];
if($id && isset($_SESSION['calendar'][$id])){
$_SESSION['calendar'][$id]=$data;
}
else{
$id= ++$_SESSION['calendar']['ids'];
$_SESSION['calendar'][$id]=$data;
}
I'm using var_dump on session in another page and the data is going through correctly.
session_start();
var_dump($_SESSION);
echo "<br>";
echo $_SESSION['calendar'][1]['title'];
echo "<br>";
echo $_SESSION['calendar'][1]['start'];
What I can't seem to be able to do, is insert this data into a database. Every time I try to run a query, nothing happens.
The query I'm using is:
$query1 = "INSERT INTO `doc`.`appointment` (`start`, `end`, `title`, `body`) VALUES ('$data['start']', '$data['end']', '$data['title']', '$data['body']');";
$result1 = $con->query($query1);
your query
$query1 = "INSERT INTO `doc`.`appointment` (`start`, `end`, `title`, `body`) VALUES ('$data['start']', '$data['end']', '$data['title']', '$data['body']');";
$result1 = $con->query($query1);
i have corrected it little bit try this
$query1 = "INSERT INTO `doc`.`appointment` (`start`, `end`, `title`, `body`) VALUES (".$data['start'].", ".$data['end'].", ".$data['title'].", ".$data['body'].")";
$result1 = $con->query($query1);
I have a highscores table, it seems to be working fine apart from the problem of at random times it seems to be resetting certain users back to 0, this is my query:
$user = isset($_GET['username']) ? $_GET['username'] : "";
$time = isset($_GET['time']) ? $_GET['time'] : "";
$videos = isset($_GET['videos']) ? $_GET['videos'] : "";
$credits = isset($_GET['credits']) ? $_GET['credits'] : "";
$user = mysql_real_escape_string($user);
$time = mysql_real_escape_string($time);
$videos = mysql_real_escape_string($videos);
$credits = mysql_real_escape_string($credits);
$secret = mysql_real_escape_string($secret);
// Main Query
$retval = mysql_query("
INSERT INTO
highscores(Username, Time, Videos, Credits)
VALUES
('$user', '$time', '$videos', '$credits')
ON DUPLICATE KEY UPDATE
Time = '$time',
Videos = '$videos',
Credits = '$credits'
",
$conn
);
It updates fine most of the time, can anyone see what the problem is?
I guess you want to update the credit and not zero it.
Say you set $credit to 0 before you execute the query, than the ON DUPLICATE KEY UPDATE part will cause the current user credits to be zeroed. Instead you should do something like this:
<?php
$user = 109;
$time = time();
$videos = 'something';
$credits = 0;
$retval = mysql_query("INSERT INTO
highscores
(Username, Time, Videos, Credits)
VALUES
('$user', '$time', '$videos', '$credits')
ON DUPLICATE KEY UPDATE
Time = '$time',
Videos = '$videos',
Credits = Credits + 1", $conn);
I think you are looking for
$query = sprintf("INSERT INTO highscores(Username, Time, Videos, Credits)
VALUES('%s', '%s', '%s', '%s')
ON DUPLICATE KEY UPDATE Time = Time + %2$s, Videos = Videos + %3$s, Credits = Credits + %4$s"
mysql_real_escape_string($user), // escape every variable you will be using in
mysql_real_escape_string($time), // an SQL query to protect yourself against
mysql_real_escape_string($videos), // SQL injection or use parametriezed
mysql_real_escape_string($credits)); // queries with wrappers such as PDO or MySQLi
$retval = mysql_query($query,$conn);
If a user exists already, this will just add to the current Credits the new value, but it won't change anything else. This seems logical to me. If you also need to increment other columns such as Videos, do the same thing I did for the Credits.
Other have pointed what causes this behaviour. Here's an alternative syntax for the ON DUPLICATE UPDATE
// Main Query
$retval = mysql_query("
INSERT INTO highscores
(Username, Time, Videos, Credits)
VALUES
('$user', '$time', '$videos', '$credits')
ON DUPLICATE KEY UPDATE
Time = Time + VALUES(Time),
Videos = Videos + VALUES(Videos),
Credits = Credits + VALUES(Credits)
",
$conn
);
I get the error: Column 'Time' cannot be null when using the query below, it works fine the first time when there is no duplicate but then when trying to update again I get the error: Column 'Time' cannot be null
mysql_query("
INSERT INTO
$table(Username, Time, Videos, Credits)
VALUES
('$user', '$time', '$videos', '$credits')
ON DUPLICATE KEY UPDATE
Time=Time+INTERVAL $time SECOND
Videos=Videos+'$videos',
Credits=Credits+'$credits'
",
$conn
);
Hope you can spot my error as I am new to this, thanks!
Here is some more of my code:
$conn = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
mysql_select_db(DB_NAME, $conn);
// Error checking
if(!$conn) {
die('Could not connect ' . mysql_error());
}
// Localize the GET variables
$user = isset($_GET['username']) ? $_GET['username'] : "";
$time = isset($_GET['time']) ? $_GET['time'] : "";
$videos = isset($_GET['videos']) ? $_GET['videos'] : "";
$credits = isset($_GET['credits']) ? $_GET['credits'] : "";
// Protect against sql injections
$user = mysql_real_escape_string($user);
$time = mysql_real_escape_string($time);
$videos = mysql_real_escape_string($videos);
$credits = mysql_real_escape_string($credits);
$secret = mysql_real_escape_string($secret);
// Insert
$retval = mysql_query("
INSERT INTO
$table(Username, Time, Videos, Credits)
VALUES
('$user', '$time', '$videos', '$credits')
ON DUPLICATE KEY UPDATE
Time = DATE_ADD(IFNULL(Time,now()),INTERVAL '$time' SECOND),
Videos = Videos+'$videos',
Credits = Credits+'$credits'
",
$conn
);
// End Query
if($retval) {
echo "Success! Updated $user with Time: $time - Videos: $videos - Credits: $credits";
} else {
echo "<b>ERROR:</b><br>" . mysql_error();
}
mysql_close($conn);
It should be:
mysql_query("
INSERT INTO
$table(Username, `Time`, Videos, Credits)
VALUES
('$user', '$time', '$videos', '$credits')
ON DUPLICATE KEY UPDATE
Time = DATE_ADD(IFNULL(`Time`,now()),INTERVAL '$time' SECOND)
,Videos = Videos+'$videos'
,Credits = Credits+'$credits'
",
$conn
);
Don't forget to put single quotes around all injected variables, otherwise mysql_real_escape_string will not protect you.
See:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add
If there's no duplicate, then this query will do an insert, and the Time value will be null, as no value was ever set. Null + anything is null, hence the error.
Try ... Time = COALESCE(Time, 0) + INTERVAL $time SECOND or similar to get aroun dit.
I’ve created a little weekly trivia game for my website. Basically its five questions, then at the end the user can add their score to a scoreboard.
The problem is that I want the scores to carry from week to week and cumulate. So let’s say you got 4 points one week, then 5 points the next. I want the scoreboard to reflect you have 9 points.
So I created a small form with an i
nvisible field that has the users score, a field for the username, and a field for the e-mail address. Next week, when the user takes the quiz again, I want their score to be updated if the username and e-mail match a record in the database. If no record does match, I want an entry to be created.
Here’s the script I came up with, however, it doesn’t work (which doesn’t surprise me, I’m pretty new to PHP/MySQL)
$name = $_POST['name']; //The Username
$score = $_POST['submitscore']; //The users score (0-5)
$email = $_POST['email'];//Users email address
$date = date("F j, Y, g:i a");//The date and time
if($name != '') {
$qry = "SELECT * FROM scoreboard WHERE name='$name'";
$result = mysql_query($qry);
if($result) {
if(mysql_num_rows($result) > 0) {
$sum = ($row['SUM(score)']+$score);
"UPDATE scoreboard SET score = '$sum' WHERE name = '$name'";
}
else
$q = mysql_query("INSERT INTO scoreboard (`name`, `email`, `date`, `score`) VALUES ('$name', '$email', '$date', '$score');");
#mysql_free_result($result);
}
else {
die("Query failed");
}
}
My table scoreboard looks like this
id........name........email...........date...........score
1........J.Doe.....j.doe#xyz.com.....7/27/11.........4
You're looking for INSERT... ON DUPLICATE KEY syntax
"INSERT INTO scoreboard (`name`, `email`, `date`, `score`) ".
" VALUES ('$name', '$email', '$date', '$score') ".
"ON DUPLICATE KEY UPDATE `score` = $sum";
Aside:
Use mysql_real_escape_string!
$name = mysql_real_escape_string( $_POST['name'] );
$score = mysql_real_escape_string( $_POST['submitscore'] );
$email = mysql_real_escape_string( $_POST['email'] );
$date = date("F j, Y, g:i a");//The date and time
EDIT
First, this doesn't really work unless you have a column SUM(SCORE):
$sum = ($row['SUM(score)']+$score);
If you want the sum of a column, you need to put that in the MySQL query directly. If you just want the score for that row, however, you can use $row['score']. If you need to add to an existing score you don't need to select for the value (thanks to a1ex07 for pointing this out)
ON DUPLICATE KEY UPDATE `score` = $score + score
This line is incorrect:
$sum = ($row['SUM(score)']+$score);
You probably want to replace it by:
$sum = ($row['score']+$score);
As you are new to PHP/MySQL I recommend you to read about MySQL Injections as your queries contain potential risks.
I'd have a database table to hold quizzes; a database table for members; and a database table that contains foreign keys to both tables along with a score so only one record can be created for each member and each quiz.
I'd also save the score in a session when the user finishes the quiz so the user can't then just submit any old score to your database; the score entered is the score your application generated.
This way, you can then just query SUM(score) of a member based on that member's ID.