My code is big and I can't just pull out few lines to show my problem so I am going to explain it by using imaginary code to simplify it.
Let's say I have to-do list as table and I've defined activity and time. I don't want to have duplicate rows so I created function to prevent it.
function check_date($day, $time) {
include 'db_connect.php';
$sql = "SELECT day, dan FROM todo ";
$sql .= "WHERE day = $day AND time = '{$time}'";
$result = mysqli_query($conn, $sql) or trigger_error(mysqli_error());
if(mysqli_num_rows($result) >= 1) {
$row = mysqli_fetch_assoc($result);
return 1;
} else {
return 0;
}
}
Call on function in main file:
if(check_termin_sala($day, $time)) {
$errors['busy'] = "You are busy.";
}
And query:
if(empty($errors) {
$query = "INSERT INTO todo (";
$query .= "day, time, activity";
$query .= ") VALUES (";
$query .= "'{$day}', '{$time}', '{$activity}')";
$result = mysqli_query($conn, $query);
if(!$result) {
die("Failed." . mysqli_error($conn));
}
}
Now I want update my row by changing just activity field, but fields day and time are unchanged so when I submit update I get error because exact day and time are already inserted. What should I do to exclude this check function affecting current row date and time?
I hope you will understand me. :)
Related
I created a sort of (available / unavailable) for staff to store the start and end times/dates of each working day.
Here are my goals:
After their personal id is being scanned, they will see their own picture. Also the database will do the following:
Database checks or there is any record for the current date.Yes = update stop time and date. No = Create new entry.
Code:
if (isset($_POST['action'])) {
$queryRegistration = "SELECT id, number, startdate FROM timeRegistration";
$resultRegistration = mysqli_query($conn, $queryRegistration);
while($row = mysqli_fetch_assoc($resultRegistration)) {
if ($row['number'] == $staffNumber) {
if ($row['startdate'] == $currentDate) {
echo $row['number'].' '.$row['id'];
echo '<div class="boxPersons">My Picture</div>';
}
}
}
}
Goal 1: Does not work. As it creates more divs. How can I manage it only creates one div?
Goal 2: I want to update or create it with functions like:
function newEntryDate() {
$sql = 'INSERT INTO timeRegistration (id, number, startdate, enddate, starttime, endtime, value) VALUES (NULL, "'. $staffNumber .'", "'. $currentDate .'", "", "'. $currentTime .'", "", "")';
return $sql;
}
Question: How can I make sure this works within my script? I don't know how to start.
Do something like this.
if your query is retrieving more than 1 row set a limit in query.
it is better to not use if statement in while loop.
if (isset($_POST['action'])) {
$queryRegistration = "SELECT id, number, startdate FROM timeRegistration where startdate =".$currentDate." AND number=".$staffNumber." limit 1;";
$resultRegistration = mysqli_query($conn, $queryRegistration);
$i=0;
while($row = mysqli_fetch_assoc($resultRegistration)) {
echo '<div class="boxPersons">My Picture</div>';
$i++;
}
if($i>0){
newEntryDate();
}
I have a database field which are
Appt_Datetime (which is call as DateTime in my table)
Svc_ID (which i call ApptType in my table)
I wanted the system to let the customer know that the datetime for the appt type is not available once someone else has book that slot.I have done a lot of research and trying out different codes but to no avail. I've seen answers on stackoverflow that uses PDO but im not so clear about it hence i'd like something to do with mysql. I have been stuck at with this at least few weeks now. Help
This is my call func:
$datetime = $_POST['DateTime'];
$appt = $_POST['ApptType'];
This is the query i last tried out but still is not working:
//Define query
$vquery = "SELECT * FROM Appointment where Appt_DateTime='$datetime' && Svc_ID='$appt'";
//Run Query
$result = mysql_query($query, $conn);
$row = mysql_fetch_assoc($result);
if($row==1)
{
echo "Date in not available";
}
else if($row==0)
{
$query = "INSERT INTO Appointment (Client_ID,Svc_ID,Appt_DateTime)
VALUES ('$_POST[ClientID]','$_POST[ApptType]','".date('Y-m-d H:i:s', strtotime($_POST[DateTime]))."')";
mysql_query($query,$conn);
}
Hint:
change this to $result = mysql_query($query, $conn); to $result = mysql_query($vquery, $conn);
at the time you are using $conn you do not have $query it is $vquery:
$result = mysql_query($vquery, $conn);
And as suggested above in comments better use mysqli or PDO.
you can try this condition..
//Define query
$vquery = "SELECT * FROM Appointment where Appt_DateTime='$datetime' && Svc_ID='$appt'";
//Run Query
if($result = mysql_query($vquery, $conn)){
//$row = mysql_fetch_assoc($result);
if(mysql_num_row($result)>0)
{
echo "Date in not available";
}
else
{
/* $query = "INSERT INTO Appointment (Client_ID,Svc_ID,Appt_DateTime)
VALUES ('$_POST[ClientID]','$_POST[ApptType]','".date('Y-m-d H:i:s', strtotime($_POST[DateTime]))."')";
mysql_query($query,$conn); */
echo "insert";
}
}else{
echo mysql_error();
}
I'm having a problem with the code listed below where I'm running a query on a database based on search criteria the user may have selected on a form.
At the moment, querying the database just on the author's name works fine. But if I uncomment the rest of the if-else statements, none of the queries work. I just get a blank table back with no results returned.
I've tried each if/else statement individually with the others commented out and they all work fine on their own, but not when they're all uncommented.
Can anyone point me in the right direction?
$query = "SELECT * FROM books WHERE book_no IS NOT NULL";
if ($_POST['author'])
$query .= " AND '$author' = author";
/*
else if ($_POST['author'] AND $_POST['year'])
$query .= " AND '$author' = author AND '$year' = year";
*/
/*
else if ($_POST['cover_art']) {
$query .= " AND '$cover_art' = cover_art";
}
*/
/*
else if ($_POST['interior_art']) {
$query .= " AND '$cover_art' = cover_art";
}
else {
// do something else
}
*/
Check this solution:
$author='Bred';
$year='2012';
$cover_art='';
$queryA=array();
if ($author<>'') $queryA []= "'$author' = author";
if ($year<>'') $queryA []= "'$year' = year";
if ($cover_art<>'') $queryA []= "'$cover_art' = cover_art";
$query = "SELECT * FROM books WHERE book_no IS NOT NULL";
if(count($queryA)>0) $query.=' AND '.implode(' AND ',$queryA);
echo $query;
I want to check and compare the information on my input form with information that is stored in my database.
Basically. if trainer, sessionslot eventdate is the same dbtrainer, dbeventdate dbsessionslot ECHO "Booked";
Else insert into booking table
I know very little about programming, could really do with some help on this one.
This is snippet of the code i am using.
if(isset($_GET['add'])){
$trainee = $_POST['txttrainer'];
$trainer = $_POST['txttrainee'];
$sessionSlot = $_POST['txtsession'];
$eventdate = $month."/".$day."/".$year;
$query = mysql_query("SELECT * FROM BOOKING WHERE trainer='$trainer' AND SessionSlot='$sessionslot");
$sqlinsert = "insert into booking (Trainee,Trainer,sessionSlot,eventDate,dateAdded) values ('".$trainee."','".$trainer."','".$sessionSlot."','".$eventdate."',now())";
$resultinsert = mysql_query($sqlinsert);
$numrows = mysql_num_rows($query);
if($numrows == 1) {
echo "this timeslot is booked"
if($resultinsert){
echo "Booking Successful....";
}else{
echo "Booking Failed";
}
}
}
if(isset($_GET['add'])){
$trainee = $_POST['txttrainer'];
$trainer = $_POST['txttrainee'];
$sessionSlot = $_POST['txtsession'];
$eventdate = $month."/".$day."/".$year;
$query = mysql_query("SELECT * FROM BOOKING WHERE trainer='$trainer' AND SessionSlot='$sessionslot");
$sqlinsert = "insert into booking (Trainee,Trainer,sessionSlot,eventDate,dateAdded) values ('".$trainee."','".$trainer."','".$sessionSlot."','".$eventdate."',now())";
$numrows = mysql_num_rows($query);
if($numrows >0) {
echo "this timeslot is booked"
}else{
$resultinsert = mysql_query($sqlinsert);
if(mysql_error()==""){
echo 'time slot booked';
}else{
echo 'error';
}
}
}
Explanation:
if there are rows selected, the timeslot is booked, else execute the query. If there is no error with the query, then print out success.
If you call mysql_query, the query is executed. So you're executing the INSERT before you check whether the SELECT returned a row or not.
That means you should place the INSERT part inside an if($numrows != 1) condition.
Please be aware that using mysql_query is deprecated: http://ch1.php.net/manual/en/function.mysql-query.php and you should use MySQLi or PDO_MySQL. Your code is vulnerable to SQL injections.
*Here is what I am trying to acheive: *
Basically I have a form where people can submit events to our database. In the CMS I have a page which displays a record of the number of events.
*Here is what I have: *
After the button is clicked, this script is called:
if($subject_type == 'Event') {
$query = "SELECT town, update_id, event_validex ";
$query .= "FROM dev_town ";
$query .= "LEFT JOIN updates ON dev_town.town_id = updates.town ";
$query .= " WHERE sitename = '".SITENAME."'";
$query .= " AND month = " .date('m')." AND year =" .date('Y');
$querys = $this->tep_db_query($query);
$rows = $this->tep_db_fetch_array($querys);
extract($rows); //extract rows, so you don't need to use array
$eventid = $event_validex + 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
This works fine, however I cant seem to solve the next bit
This is the Problem
As you can see, it checks the database for the current month and adds it, this is providing that the sitename and that month are there, not a site and another month.
How would I get it to add the row in IF the sitename and month are not there?
I have been manually adding the months in now so that it works, and I am sure you can agree that's a ball ache.
Cheers peeps
if you want to check if site A + Month 11 exists do a select query against it and store the number of rows returned in a variable. ( $exists = mysql_num_rows("your query here"); )
then do an if statement against the $exists variable and proceed as you wish
if($exists) {
// update
} else {
// add
}
$insert = "INSERT INTO updates ('town','month','year','event_validex') VALUES ('".$town."','". date('m')."','". date('Y')."','1')";
$eventid = 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
}
}
this is what I have for the else statement there, however it will add one to the value if its there but will not add a new entry if its isnt.. ?
I don't see exactly how your method "checks the database for the current month and adds it "; I'll just assume that the tep_db_perform() method of your class handles this somehow.
(uhk! n00bed it; rest of the post was somehow chopped off?) Since you're already hitting the database with the select with the intent of using the data if a record is found, then you could use the resultset assigned to $rows as a means of checking if a record exists with SITENAME and Month.
See below:
if($subject_type == 'Event') {
// build query to check the database for sitename, month and year.
$query = "SELECT town, update_id, event_validex ";
$query .= "FROM dev_town ";
$query .= "LEFT JOIN updates ON dev_town.town_id = updates.town ";
$query .= " WHERE sitename = '".SITENAME."'";
$query .= " AND month = " .date('m')." AND year =" .date('Y');
// Execute Query(wrapper for $result = mysql_query I guess?)
$querys = $this->tep_db_query($query);
// Get a resultset from database. --> you could merge this into one method with $this->tep_db_query
$rows = $this->tep_db_fetch_array($querys);
if(count($rows) > 0) {
extract($rows); //extract rows, so you don't need to use array --> I try to stay away from extract() as it makes for random variables being created.
$eventid = $event_validex + 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
} else {
// insert new record into database
// updated with code to execute insert SQL query.
$insert = "INSERT INTO updates ('town','month','year','event_validex') VALUES ('".$town."','". date('m')."','". date('Y')."','1')";
$result = $this->tep_db_query($query);
}
....
}
If I've misunderstood something, please let me know, happy to work through it with you.
Hope this helps. :)