I have a form with more then 4 fields and all data inserted into those fields are related, so i want to achieve something different.
For example - I have 4 fields with names class class_time class_teacher & batch_name and each time i fill and submit the form the data will be submitted into database, basically it's a time-table script.
So if first time i added maths 12-01 ashok IAS these values and submitted the form and it got saved, now if second time i add same time and teacher name with different batch then it should show an error and form should not submit, because same teacher can not appear at two different classes at the same time. How could i achieve this with PHP.
Here are some code which i tried.
$sql2 = "SELECT * FROM `s_timetable`";
$res = mysql_query($sql2) or die(mysql_error());
$fetch_data = mysql_fetch_array($res);
if ($fetch_data['class_info'] && $fetch_data['teacher_info']) == $_POST['class'] && $_POST['teacher']
{
}
before inserting new data you can check the things by below given query and if that query return more than 0 rows you can show an error message
select * from `tablename` where `class_time` = '".$class_time."' and `class_teacher`='".$class_teacher."'
You shouldn't use any mysql_*-functions. They have been deprecated since php 5.5 and completely removed in latest php versions
Instead of doing this in PHP you could just add a composite unique key that would not allow having the same teacher at the same time in the database.
ALTER TABLE s_timetable ADD CONSTRAINT myUniqueConstraint UNIQUE(class_time, class_teacher);
Now everytime you would try to insert new data it would return an SQL error if the same teacher is there at the same time.
Multiple column index documentation
You need to check first that user is already in the table or not.
$sql = mysql_query("select * from table_name where class_time ='" . $_REQUEST['class_time'] . "' AND class_teacher ='" . $_REQUEST['class_teacher'] . "'");
$record = mysql_num_row($sql);
if ($record) {
echo "Record already exits";
exit();
} else {
//insert query
}
Note : Stop using mysql it is deprecated.
Simply add a query that will select class_time and class_teacher so that if it already exist you can produce an error msg.
$checksched = mysqli_query($con,"SELECT * FROM s_timetable WHERE class_time = '".$inputted_time."' and class_teacher = 'inputted_teacher' ")
$match = mysqli_num_rows($checksched);
if ($match > 0){
echo "<script>
alert('Teacher already exist!');
</script>";
}
Related
On my XAMPP server I have a database table on phpMyAdmin. In that table, I have a few columns, and one of them is id column (Integer).
I want to get the latest added item's ID, increment it by one and then assign it to a new item that the function adds to the table.
The problem is that whenever there is a new item, it is automatically assigned with 1 as id, nothing above 1.
$sql = "SELECT * FROM items";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
if( $_SESSION["increment"] == "yes"){
$_SESSION["id"] = $row["id"];
}else
$_SESSION["id"]=$_SESSION["id"]+1;
}
} else {
$_SESSION["id"] = 1;
}
This will give you last increment Id.
$sql = "SELECT id FROM items order by id DESC LIMIT 0,1";
Then you dont want have a while loop to find last increment Id.
error reporting said what? and mysqli_error($conn)?
-- Fred-ii-
The above request by Fred -ii- sums it up, if your ->num_rows is returning zero or not a number (false) then you have an SQL error, so you need to check your error logs, and check your database connection.
Have you started your session with session_start?
Do you intend that the first else calls without brackets, only executing the single following line, $_SESSION["id"]=$_SESSION["id"]+1; ?
It seems to me that you need well known AUTO_INCREMENT functionality built inside MySQL database. Just define in your database schema for your table that column is AUTO_INCREMENT column type, and it will be automatically incremented by 1 upon each new insert into table.
I have a php script that displays records from a database. It's probably not the best script, as I'm very new to php.
I've added an additional column in my table and would like to keep a count in that column to show me how many times each of the records have been viewed.
Heres the part of the code I think i need to add the code to... if i need to post the entire page i will, but i just figured i could add the line to this part.
//Get the details from previous page
$SelectedCounty = $_POST["result"];
//set variable for next SEARCH
$option = '';
// Get the county names from database - no duplicates - Order A-Z
$query = "SELECT DISTINCT tradingCounty FROM offers ORDER BY tradingCounty ASC";
// execute the query, $result will hold all of the Counties in an array
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)) {
$option .="<option>" . $row['tradingCounty'] . "</option>";
}
}
the new column name is 'views' and i just want to add 1 to it each time a record from the database is viewed.
any help greatly appreciated.
Add a new field views to the table.
When, user views the page, fire the SQL.
$query = "UPDATE offers SET views = views + 1";
mysqli_query($con,"update offers set views = views + 1");
If you have added the column, it probably has a NULL value. Either set the value to 0, by doing:
update offers
set views = 0;
Or use:
update offers
set views = coalesce(views, 0) + 1;
You can change your code with this rewritten code assuming that your Table has a column views (datatype int).
//Get the details from previous page
$SelectedCounty = $_POST["result"];
//set variable for next SEARCH
$option = '';
// Get the county names from database - no duplicates - Order A-Z
$query = "SELECT DISTINCT tradingCounty FROM offers ORDER BY tradingCounty ASC";
// execute the query, $result will hold all of the Counties in an array
$result = mysqli_query($con,$query);
if($result){
$query2 = "UPDATE offers SET views=views+1;
mysqli_query($con,$query2);
}
while($row = mysqli_fetch_array($result)) {
$option .="<option>" . $row['tradingCounty'] . "</option>";
}
Or if you need to track the view counts for individual records, you need to modify your code a bit. And probably you need to add one more field in the database for eg. id (datatype int) which can distinguish between different records.
Please clear your problem properly.
As far as i have analysed your code it brings out the following case.
There are different records for tradingConty, and whenever a user views that particular record(one of the tradingCounty record) by clicking that or any other action specified, the php script is set to increament the view count for that particular entry(we can get that by id) in the database.
If thats the scenario, we can easily generate a code accordingly.
How do I echo the latest values in column1? The below code echos the values before the update.
while($line = mysql_fetch_array($result)) {
$Student = $line["calss8"];
$querySf = "SELECT SUM(ABC) AS val1 FROM tbl1 WHERE student = '$Student'";
$resultSf = mysql_query($querySf);
$rSf = mysql_fetch_array($resultSf);
$totalSf = $rSf['val1'];
$totTMonth = $totalSf;
mysql_query("UPDATE tbl4 SET column1 = $totTMonth WHERE student = '$Student' LIMIT 1");
}
echo $line["column1"].",,";
As far as I know, you'll have to make a separate query to see what was just updated. I mean, run your select, perform your update, then do another select. You can get general information like how many rows were updated, but I don't think you can get specific information like the changed values in a column. Phil was right in suggesting that you should just print out the '$totTMonth' value since that is what you are updating your column with. That would be less overhead than doing another query to the database.
I think that problem starts before the code above. This code line will display the select results :echo $line["column1"].",,";. The variable $line is set before the code above. My solution is to do the following:
$result1 = mysql_query("SELECT column1 FROM student ..."); /* I insert the select query here */
While($row= mysql_fetch_array($result)) {
echo $row['column1'].",,";
}
I need to verify that a user registering for a website enters a unique 16 digit number that no one else prior to him/her has entered.
The relevant database information is that the 16 digit numbers are stored in a column called card1, the name of the entire table is users, and the user-entered number is stored in $card1.
Here is what I have so far...
$query2 = "SELECT card1 FROM users WHERE card1='$card1' LIMIT 1";
$result2 = smart_mysql_query($query2);
if (mysql_num_rows($result2) != 0)
{
header ("Location: register.php?msg=exists");
exit();
}
The idea is that it will find any examples already in the database and if it finds a duplicate, it will display and error message.
The problem is that it is continuing to allow users to register(submit their registration form to the db) even when there is a duplicate. Immediately after this block of code is the insertion call to the db with all of the user information collected from the form.
NOTE: I'm not very familiar with handling PHP error messages and what I've used is just an example that I found in another instance in the example code.
Make the if statement like this:
$query2 = "SELECT * FROM users WHERE card1='$card1'";
$result2 = mysql_query($query2);
if ($result2 !== false)
{
header ("Location: register.php?msg=exists");
exit();
}
Should fix the problem:)
The correct way to do this is to add a unique index on the field that holds the number that the use has entered (card1).
You will then try and INSERT the new row without trying to SELECT it first, and if this operation fails you redirect the user to the msg=exists page. This lets the database handle the duplicate detection and removes the problem inherent in your method - if two users submit the same number at the same time, there is no guarantee that SELECT -> INSERT will detect it. A unique index will detect and prevent this.
This will also have the advantage of reducing database traffic, since only one query is executed in order to get this happen.
First of all, create unique index in DB on this column.
This is best practice:
ALTER TABLE `users`
ADD UNIQUE INDEX `card1` (`card1`);
I should modify your SQL as follows:
$query2 = "SELECT COUNT(1) FROM users WHERE card1='$card1'";
$res = mysql_query($query2);
$data = mysql_fetch_array($res);
if ($data == 1)
{
header ("Location: register.php?msg=exists");
exit();
}
It will check for existence of row within table and return 0 or 1.
If exists (1) then it will redirect you.
try this one
$query2 = "SELECT card1 FROM users WHERE card1='".$card1."' LIMIT 1";
$result2 = mysql_query($query2);
if (mysql_num_rows($result2) > 0)
{
header ("Location: register.php?msg=exists");
exit();
}
Im using PHP to parse some XML, I take 3 details from each entry in the XML - Title, Description and ID.
The ID is unique and I store the ID along with title and description in a database. Im running the parse script via CRON so to prevent duplicates I want to first check the database to see if the ID of the entry already exists in the database.
How can I do this?
This will get my all the ID's right?
$id = mysql_query("SELECT id FROM updates");
$row = mysql_fetch_assoc($id);
if ($entry->id != $row) {
Insert
} else {
echo 'Duplicate';
}
Open to ideas?
Does that give me an array that I can compare the ID in the XML to?
$id = mysql_query("SELECT id FROM updates");
$row = mysql_fetch_assoc($id);
if ($entry->id != $row['id']) {
Insert
} else {
echo 'Duplicate';
}
it returns array form, so you have to give it column index or name to match
Try using INSERT ... ON DUPLICATE KEY UPDATE.
I would suggest that you have your DBMS handle conflicting ids.
you can use the ON DUPLICATE option of INSERT to handle that event let your DB automatically choose another ID.
$id = mysql_query("SELECT 1 FROM updates where id = " . $entry->id);
$row = mysql_fetch_assoc($id);
if ($row[0]) {
insert
}
else {
}
if uoy are makes the field unique then if you simply try to insert row - db rise an error "unique constraint". in this case you just have not to check if the record is unique. it will not be inserted anyway.