Help with logic - php

I have created one field unique in my database. Consider the album name is unique. I have successfully added constraints that if user try to add other album with that name he will get error message that record already present. So user may not add any other record with the same name.
But now I have problem that if their are 3 records exists in database with name a,b,c. and user is updating any of field than he can update record b as name of a so their would be two records in database with a. & I want to create it unique. For that I am using script..
if($name!="") {
$sql = "select a_name from t_a_list where a_name = '$name'";
$result = mysql_query($sql);
if(mysql_num_rows($result) != 0) {
$msg = "<font color=red>Record Not Saved. Album already Exist!</font>";
}
} else {
$msg = "<font color=red>Enter Name of Album!</font>";
}
if($msg=="") {
//Update Query
}
But I have problem that with each pageload for updation I need to choose different name for album. because it will show album exist msg. Sometimes it might be possible that I want to change rest of information other than name of album like its year of release, total track. but with this script If I want to update rst of field I need to change album name first. Please help with this problem. So that album name may not repeat in DB and I can update other information also other than name.

You could save the oldname in a variable and when updating first check for if($name!=$oldname) { ... .
this way you won't update the name unless it changed and the updates for the other fields will be made
$oldname = THE NAME OF THE ALBUM BEING EDITED
....
if($name!=$oldname) {
if($name!="") {
$sql = "select a_name from t_a_list where a_name = '$name'";
$result = mysql_query($sql);
if(mysql_num_rows($result) != 0) {
$msg = "Record Not Saved. Album already Exist!";
}
} else {
$msg = "Enter Name of Album!";
}
if($msg=="") {
//Update Query
}
}
if($description!="") {
....
}
if($location!="") {
...
}
...

You need to enforce the uniqueness constraint at the database level. This way, the database will reject any operation that will create records with identical keys.
One way to do this for an existing table is using the ALTER TABLE command:
ALTER TABLE myalbums ADD UNIQUE (albumname);

Related

php-sql delete value if exists in one of my two tables

I have created a chat system where students and academic staff can communicate between them. I have developed a form were I can get the name of the club were the conversation exists, and the value of the staff_id for another reason.
The problem is that I can not delete the records from 3 tables. I know that first I have to check if a specific id exists in staff_table or stu_table but I cannot figure out the query that I have to use.
The first table is the staff_message (columns: staff_id, m_id), the second is the stu_message (columns: stu_id, mid) and the third is the message table (columns: id, text, date, type).
Here you can see my code:
<?php
include_once('connect.php');
$name=mysqli_real_escape_string($con,$_POST['clubname']);
$staff_id=mysqli_real_escape_string($con,$_POST['staff_id']);
if(empty($name)) {
header("Location: ../options.php?index==empty");
exit();
}
else {
$quer = mysqli_query($con,"SELECT id FROM message WHERE type='$name'");
while($row = mysqli_fetch_array($quer)) {
$message_id = $row['id'];
}
$query4 = mysqli_query($con,"SELECT * FROM staff_message WHERE m_id='$message_id'");
if(mysqli_num_rows($query4) >= 1)
{
$query5 = mysqli_query($con,"DELETE FROM staff_message WHERE m_id='$message_id'");
} else {
echo "not here staff"; //see if finds the value
}
$query8 = mysqli_query($con,"SELECT * FROM stu_message WHERE mid='$message_id'");
if(mysqli_num_rows($query8) >= 1)
{
$query5 = mysqli_query($con,"DELETE FROM stu_message WHERE mid='$message_id'");
} else {
echo "not here stu";//see if finds the value
}
$query= mysqli_query($con,"DELETE FROM message WHERE type = '$name'");
header("Location: ../options.php?delete==success");
}
?>
Thank you in advance!
EDIT: I tested each code separately and I saw that they both work. What I mean is that when there is only one row of student message then the message is deleted as well as the row in reference table (stu_message). That also applies for the academic staff table.
May Be
You Have 3 Tables
1.Staff_Message
2.Stu_Message
3.Message
can you tell me which is the main id and which id refrence in tables then i can make query according your requirement
According To Your Image Your Base Table Is Message Then Mid Refer In Two Table(stu_message and staff_message)--- Right?

How do I ensure the value only gets saved once into the table, when checked?

With my code here, if the user checks a check box beside one of the names
the name gets saved into my review_shared table, when the user clicks 'Save'.
But I want a checked value to be only saved
once into the table, the way it is now it gets saved multiple times - I mean if the user comes back to this page and the name is checked and the user clicks 'Save' again.
What can I add to the code for this to happen, so it will only be saved once in my review_shared table ? At present it looks like this, which saves it multiple times :
if(!empty($_POST['check_contacts'])) {
foreach($_POST['check_contacts'] as $check) {
//$_GET['id'] is the current review for which contacts are being edited, we are checking a contact to share that review with
$insert_review_shared_command = "INSERT INTO review_shared VALUES(NULL," .$_GET['id']. ", '$user_id','$check')";
//we want to save the checked contacts into the review_shared table
$insert_into_review_shared_table = mysqli_query($con,$insert_review_shared_command);
}
//go to the main page when changes have been saved
header('Location:volleyLogin.php');
}
$con->close();
I thought adding code like this into the above would help, but it doesn't, really :
if(!empty($_POST['check_contacts'])) {
//************************* added this in **************
$check="";
//if the contact in review_shared is already checked, we don't want to save it multiple times
$already_checked = "SELECT * from review_shared WHERE user_id = '$user_id' AND contact_id = '$check' AND review_id = " .$_GET['id'];
$already_checked_result=mysqli_query($con,$already_checked);
$num_rows = mysqli_num_rows($already_checked_result);
if($num_rows >= 1) {
echo "This is already a contact";
break;
}
//*******************************************************
foreach($_POST['check_contacts'] as $check) {
//$_GET['id'] is the current review for which contacts are being edited, we are checking a contact to share that review with
$insert_review_shared_command = "INSERT INTO review_shared VALUES(NULL," .$_GET['id']. ", '$user_id','$check')";
//we want to save the checked contacts into the review_shared table
$insert_into_review_shared_table = mysqli_query($con,$insert_review_shared_command);
}
//go to the main page when changes have been saved
header('Location:volleyLogin.php');
}
$con->close();
break; is used to come out of a loop(for, foreach,while and do-while) and switch structure, not from if block. You have to create an else block corresponding to that if block, and put your entire foreach loop there.
// your code
if($num_rows) {
echo "This is already a contact";
}else{
foreach($_POST['check_contacts'] as $check) {
//$_GET['id'] is the current review for which contacts are being edited, we are checking a contact to share that review with
$insert_review_shared_command = "INSERT INTO review_shared VALUES(NULL," .$_GET['id']. ", '$user_id','$check')";
//we want to save the checked contacts into the review_shared table
$insert_into_review_shared_table = mysqli_query($con,$insert_review_shared_command);
}
}
// your code
Here's the relevant reference:
http://php.net/manual/en/control-structures.break.php

PHP compare value from database

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>";
}

mysqli_fetch_array() doesnot grasp the first row of the table from database

i am trying to learn PHP and MYSQL. I have created a database in phpmyadmin which has the following attributes:
database name = my_database
table name = users
The table has:
attributes (id,Name, Password, Phone Number)
A pictorial example of what I have looks like:
The problem is I wrote a query in php that would select all the data from the table and display it using a loop. For some reason no matter how much data I add in my users table, the code always omits the first row of data and displays the rest of the users data.According to my code, the output should be each user name displayed with their id number, but the information of the first user is never shown, and the rest of the users are shown perfectly.Can someone please help me regarding this.
my code:
<?php
$counter=0;
$mysqli=mysqli_connect('localhost', 'root','','my_database');
if(mysqli_connect_errno())
{
echo'connection failed'; echo"<br>";
}
else{
echo"connection SUCCESSFUL";echo"<br>";
}
$sq1="select * from users";
//$sq1="SELECT `Name`, `Password` FROM `users` ORDER BY `id`";
$res= mysqli_query($mysqli,$sq1);
if($res)
{
echo"Database Query Successful";echo"<br>";
$user_array= mysqli_fetch_array($res);
//print_r($user_array);
while($user_array=mysqli_fetch_assoc($res))
{
$user_id=$user_array["id"];
$user_name=$user_array["Name"];
//$user_phonenumber=$user_array["Phone Number"];
echo'The user name is '.$user_name.' The id is '.$user_id;
}
}
else
{
echo"Databse unsuccessful";
}
?>
That's because you called mysqli_fetch_array before entering the loop , remove the following line:
$user_array= mysqli_fetch_array($res);

PHP/Mysql - Check for existing entry in DB

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.

Categories