PHP/Mysql - Check for existing entry in DB - php

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.

Related

PHP function doesn't increment int as it should

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.

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

How in MySQL are records added without causing duplicates?

I'm working in MySQL and PHP. How in MySQL do you do an update to an existing table with additional records, without causing duplicates? The records are customers and the key to each record is the customer account number such as "1234".
I need to do basically three things. Add a new customer record if their customer account doesn't exist, update an existing customer's information such as their phone number or e-mail address has changed, or delete the customer record if they are no longer a customer.
The data comes in as a feed daily, and marketing wants to have their own data base of customers with their own fields added, which is why I don't simply re-create the database from the daily feed. The goal is to keep it up to date with the feed. Thanks!
I would suggest that you do all of the processing using PHP.
When you're looping through your customer records, first check if the record exists:
$query = "SELECT customer_account_number FROM table WHERE customer_account_number = 1234";
$result= $mysql -> query($query);
$num = $result -> num_rows;
if($num == 1){
// The record already exists so you update.
$update_query = "UPDATE table SET some_field = 'Some Value' WHERE customer_account_number = 1234";
$update_result= $mysqli -> query($update_query);
}else{
// The record doesn't exist so create a record.
$insert_query = "INSERT INTO table (customer_account_number) VALUES (1234)";
$insert_result= $mysqli -> query($insert_query);
}
Alternatively, you could do one select query to get the customer account numbers and pop them in an Array.
$query = "SELECT customer_account_number FROM table";
$result= $mysql -> query($query);
$num = $result -> num_rows;
while($row = $result -> fetch_array(MYSQLI_ASSOC)){
$cust_records[] = $row['customer_account_number'];
}
// Then for each customer record your looping through.
if(in_array($customer_record_id, $cust_records)){
// It exists - so just update
$update_query = "UPDATE table SET some_field = 'Some Value' WHERE customer_account_number = 1234";
$update_result= $mysqli -> query($update_query);
}else{
// Doesn't exist - insert
$insert_query = "INSERT INTO table (customer_account_number) VALUES (1234)";
$insert_result= $mysqli -> query($insert_query);
}
Also, as suggested by Tadman, if you make sure the customer account number is a UNIQUE column then that will add extra protection to make sure duplicates can't be added.
use the insert on duplicate update query. It does the inserting and updating part of your question. For deletion you could have another query i suppose.
refer: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
MySQL supports "on duplicate key update" syntax.
This basically allows you to specify which fields to update if the Primary Key (your account number) already exists, all in one SQL statement.
mysql syntax
You'd have to handle deletion with a separate SQL statement, since this logic would almost certainly come from your customer feed.
Run a SELECT id FROM table before inserting and save the ids as keys in an associative array. By simply going if a key is set, you can check if the id exists in the database and do processing based on that.
If you remove each customer process, in the end you'll be left with an array of customers no longer existing.
Executing this one time saves some SQL load.
$result = mysql_query('SELECT id FROM table');
$ids = array();
while($row = mysql_fetch_assoc($result)){
$ids[$row['id']] = true;
}
foreach($objects as $key => $obj) {
if($ids[$obj['id']]) {
// exists, update!
unset($ids[$obj['id']]);
} else {
// new, insert!
}
}
// go through the remaining people not added
for($ids as $deleted_id) {
// delete this guy
}

Help with logic

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);

mySQL fetch column based on another column in PHP

I'm trying to write my first PHP script with mySQL and I desperately need some help. I'm sure this is relatively simple, but if I have one field in my table (username, for example), and I want to fetch another field (name, for example), that is in the same row as the given username, how do I do that?
Again, I'm sure this is easy, but I'm lost, so I'd really appreciate any help. Thanks!
$sql = "SELECT username, name FROM table";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
echo "This {$row['username']} has the name {$row['name']}\n";
}
halfdan's answer sort of works, but it fetches all rows and displays them. What you want is a WHERE clause, which lets you filter the contents of the table so the query only returns the row(s) you want:
SELECT username, name
FROM sometable
WHERE (username = 'johndoe');
This will return only the rows where the username field is equal to 'johndoe'. Conceptually, it's equivalent to:
$results = mysql_query("SELECT username, name FROM table");
while($row = mysql_fetch_assoc($results)) {
if ($row['username'] == 'johndoe') {
// do something, this is a row you want
} else {
// not a row you want. ignore it, or deal with it some other way
}
}
the main difference is that for large data sets in the database, doing client-side filtering like this is expensive, as the entire contents of the table has to be transferred over. Using a WHERE clause to limit things to just what you want is far more efficient in the long run.

Categories