I have been going over this for a few days now and keep reaching stumbling blocks. I am trying to select a unique id from table2 and match it against an id in table1. If the id is matched, update the row in table1 and remove the record from table2. If there is no match then insert the record into table1.
I have got to a point where I can update the records and insert the new ones but I cannot seem to delete the matched record before the insert therefore creating a duplicate. I have tried a delete join query after the update but because the new logon_id has a character prepended to it, it no longer matches in table2.
I was doing an update join before for updates but I had too many queries going on so trying to keep it simple.
Any advice? Still a newb at this game.
$table2_query = "SELECT * FROM table2";
$table2_result = mysql_query($table2_query);
$table2_count = mysql_num_rows($table2_result);
if($table2_count == 0) {
if(mysql_error()) {
echo 'Error: '.mysql_error();
}
}
while($table2_row = mysql_fetch_array($table2_result, MYSQL_ASSOC)) {
$check_number_length = strlen($table2_row['unique_id']);
if($check_number_length < 7) {
if(substr($table2_row['unique_id'], 0, 2) < 35) {
$logon_id = 'n' . $table2_row['unique_id'];
}else {
$logon_id = 'v' . $table2_row['unique_id'];
}
}else {
$logon_id = $table2_row['unique_id'];
}
// Set variables for insert query for creation of a new user record
$first_name = $table2_row['firstname'];
$last_name = $table2_row['lastname'];
$email_address = $table2_row['email'];
$duplicates_query = "SELECT * FROM table1 WHERE '$logon_id' = logon_id";
$duplicates_result = mysql_query($duplicates_query);
$duplicates_row = mysql_fetch_array($duplicates_result);
$duplicates_count = mysql_num_rows($duplicates_result);
if($duplicates_count == 0) {
if(mysql_error()) {
echo 'Error: '.mysql_error();
}
}else {
$update_records_query = "UPDATE table1 SET first_name='$first_name', last_name='$last_name', email_address='$email_address'";
$update_records_result = mysql_query($update_records_query);
$update_records_count = mysql_affected_rows();
echo $update_records_count;
}
$create_records_query = "INSERT INTO table1 (first_name, last_name, email_address) VALUES ('$first_name', '$last_name', '$email_address')";
$create_records_result = mysql_query($create_records_query);
$create_records_count = mysql_affected_rows();
if($create_records_count == 0){
if(mysql_error()){
echo 'Error: '.mysql_error();
}
}
echo $create_records_count . ' record(s) created.';
}
$res = mysql_query ("SELECT count(table1.login_id) AS count FROM table2 LEFT JOIN table1 ON table2.login_id = table1.login_id WHERE table2.login_id = \"".$login_id."\";") or die ("Error joining tables");
/*joins both tables together and selects both id's from tables */
$row = mysql_fetch_assoc($res); // should only return one row so grab first
if ($row['count'] > 0) { // check if id exists in both tables (duplicates)
// updates rows from one table into another
mysql_query('UPDATE table1,table2 SET table1.username = table2.username, table1.password = table2.password, table1.email = table2.email WHERE table1.login_id = "'.$login_id.'" AND table2.login_id = "'.$login_id.'";') or die ("error updating table1");
//delete old row
mysql_query('DELETE FROM table2 WHERE login_id = "'.$login_id.'";') or die("error deleting from table2");
}else { // if id doesn't exist in table1
mysql_query ("INSERT INTO table1(username,password,email) SELECT username,password,email FROM table2 where login_id = '".$login_id."';") or die ("error inserting into table1");
}
remove the n at the beginning of login_id on table1
UPDATE table1 set login_id = replace(login_id,"n","");
new update query if remove n at begin of login_id
mysql_query ('UPDATE table1,table2 SET table1.username = table2.username, table1.password = table2.password, table1.email = table2.email WHERE table1.login_id = table2.login_id AND table1.login_id = "'.$login_id.'";');
Related
I have this code below;
$sql = "SELECT * FROM tbl1 where id_no = '$id_no'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$new = $row['full_name'];
header("location:new.php?msg=ID Number $id is already
Registered");
}
} else {
$created = date('jS \ F Y h:i:s A');
$tr_no = 'TR_'.rand(10000,99999).'/'.date(Y).'';
include '../db_config/connection.php';
//update tables
$sql = "INSERT INTO tbl2 (id,vehicle_id,policy_id,insured_by,insurance_co,value_insured,start_date,end_date,created)VALUES ('$tr_no','$reg_no','$p_id','$user_index','$co_id','$value_insured','$start_date','$end_date','$created')" ;
$sql = "UPDATE tbl1 SET updated='1' WHERE item_id = '$reg_no'";
$sql = "INSERT INTO tbl3 (doc_number,value,date,reg_no) VALUES('$tr_no','-$value_insured','$created','$reg_no'";
if ($conn->query($sql) === TRUE) {
header("location:new_insurance.php?message=ENTRIES SUCCESSFULLY POSTED");
} else {
$error = $conn->error;
header("location:new_client.php?err=$error");
}
$conn->close();
}
$conn->close();
?>
The last bit that contains the insert and update queries is where am having the problem. Rather than executing all the three queries, only the last one is executed. What modifications should i include?
First Change these statements (concatenates the $sql variable and add semicolon ';' at end of each statements.)
$sql = "INSERT INTO tbl2 (id,vehicle_id,policy_id,insured_by,insurance_co,value_insured,start_date,end_date,created) VALUES ('$tr_no','$reg_no','$p_id','$user_index','$co_id','$value_insured','$start_date','$end_date','$created');" ;
$sql .= "UPDATE tbl1 SET updated='1' WHERE item_id = '$reg_no';";
$sql .= "INSERT INTO tbl3 (doc_number,value,date,reg_no) VALUES('$tr_no','-$value_insured','$created','$reg_no');";
Now finally execute multiple queries by mysqli_multi_query()
if (mysqli_multi_query($con,$sql)) { //con is your connection
header("location:new_insurance.......
How could I update row of many if the values changed?
I export the data from XML file which contain more than 130 rows and the same number on my MYSQL database, I want to compare it and insert if there's a new row and update the changed row.
Note: Inserting new rows working fine, but updating doesn't work!
$query = "SELECT positionid FROM vacant WHERE positionid = '".$position."' and ptitle = '".$ptitle."' and location = '".$location."' and vacantd = '".$vdate."' and candidate = '".$resultcandidate."' and cv = '".$cvtorsaf."'";
$sql = mysql_query($query);
if (!$sql) { // add this check.
die('Invalid query: ' . mysql_error());
}
$recResult = mysql_fetch_array($sql);
$existName = $recResult["positionid"];
if($existName=="") {
$insertTable= mysql_query("insert into vacant (positionid, ptitle, location, vacantd, candidate, cv) values('".$position."', '".$ptitle."', '".$location."', '".$vdate."', '".$resultcandidate."', '".$cvtorsaf."');");
} else {
$insertTable= mysql_query("UPDATE vacant SET ptitle = '".$ptitle."', location = '".$location."', vacantd = '".$vdate."', candidate = '".$resultcandidate."', cv = '".$cvtorsaf."' WHERE positionid = '".$position."'");
}
Hi Your code looking right still if you have error in updating field
then just try to print your error. use mysql_error();
$insertTable= mysql_query("UPDATE vacant SET ptitle = '".$ptitle."', location = '".$location."', vacantd = '".$vdate."', candidate = '".$resultcandidate."', cv = '".$cvtorsaf."' WHERE positionid = '".$position."'") or print_r(mysql_error());die;
I am looking to count the number of times 'yes' in present for a user in a table, then post the result into anther table for that same user. Both tables have the username. I would like this done for each user. I have the following but it is not working.
$sql = $item_count = "SELECT SUM(if(strike='yes',1,0)) AS strike_total FROM weekpicks WHERE username = 'username'";
// execute SQL query and get result
$sql_result = mysql_query($sql) or die (mysql_error());
if (!$sql_result) {
echo "Something has gone wrong!";
}
else {
//loop through record and get values
while ($row = mysql_fetch_array($sql_result)) {
$item_result = ($row = #mysql_query($item_count)) or die(mysql_error());
$strike_total = ($row = #mysql_result($item_result,"strike_total"));
$strikes = ($row = $strike_total ['strike_total']);
$username = $row["username"];
// the following will insert number of strikes into table for each user.
$sql = "UPDATE authorize SET strikes = '($strikes)' WHERE username='$username'";
//mysql_query(" UPDATE authorize SET " . "strikes = '" . ($strikes) . "' WHERE username='$username' ");
$result = mysql_query($sql) or die (mysql_error());
Just one query should be enough
Update for single user..
UPDATE authorize SET strikes = (select count(*) from weekpicks WHERE username = '$username' and strike='yes') WHERE username='$username';
For bulk update all users
UPDATE authorize as A SET strikes = (select count(*) from weekpicks B WHERE strike='yes' and A.username=B.username group by B.username)
Isn't that simple.
Hello I have a Database named as "admin" in which i have two tables
Table 1 Name = "register"
Table 2 Name = "noti"
In Register Table i've approx more than 10+ User entries which comes through Registration Page
In Noti Table, its empty at this time (Column Name is also "noti")
I want to perform this thing
First I want to count the total no. of records in "register" table
and it checks, if the records are greater than ZERO then it runs the INSERT query otherwise it runs the UPDATE Query
And i want to INSERT and UPDATE that count value into "noti" table
Here's my code
<?php
include('config.php');
$sql2 = "SELECT count(*) as count FROM register";
$result2 = mysqli_query($con, $sql2);
if($result2->num_rows>0)
{
while($rw1=$result2->fetch_array())
{
$value1 = $rw1['count'];
$result = mysqli_query($con, "SELECT count(*) as count FROM register ");
if(!empty($value1)) {
mysqli_query($con, "UPDATE noti SET noti = '$value1' ");
}
else
{
mysqli_query($con, "INSERT INTO noti(noti) VALUES ('$value1') ");
}
}
}
?>
Use this:
include('config.php');
$sql2 = "SELECT count(*) as count FROM register";
$result2 = mysqli_query($con, $sql2);
$count = $result->num_rows;
if($count != 0)
{
mysqli_query($con, "UPDATE noti SET noti = '$count' ");
}
else
{
mysqli_query($con, "INSERT INTO noti(noti) VALUES ('$value1') ");
}
I have Table1 and Table2 in a MySQL database. I want to select animals and gardens data from Table1, then I would like to select new_animals and new_gardens from Table2 which datetime is within the last week. Then, while calling the mysql_fetch_array ($row1) data from Table1, if both of animals and gardens fields are not previously recorded in Table2, insert date, animals and gardens into new_date, new_animals and new_gardens in Table2.
Please take a look at the schematic picture of tables and review the code in below. Note that Table1 returns 4 rows from $select_query1, and since data is not recorded in Table2; it should be inserted into the Table2. The below code works fine without the if condition, but not working with the if condition. Could you please let me know your corrected version of the if condition in this problem?
$select_query1 = mysql_query("SELECT date, animals, gardens FROM Table1");
$select_query2 = mysql_query("SELECT new_animals, new_gardens FROM Table2
WHERE new_date between date_sub(now(),INTERVAL 1 WEEK) and now()");
$row1 = mysql_fetch_array($select_query1); // This returns 4 rows
$row2 = mysql_fetch_array($select_query2); // This returs 4 rows
while ($row1) {
if ($row2['new_animals'] !== $row1['animals'] && $row2['new_gardens'] !== $row1['gardens']) {
$animals = $row1['animals'];
$gardens = $row1['gardens'];
$date = $row1['date'];
$insert_query = mysql_query("INSERT INTO Table2 (new_date, new_animals, new_gardens)
VALUES ('$date', '$animals', '$gardens')");
}
}
Your if statement is incorrect. You compare rows from table1 with only the first row from table2 . What you have to do is compare the the rows from table1 with all the rows of table2.
Try this
$select_query1 = mysql_query("SELECT date, animals, gardens FROM Table1");
while ($row1 = mysql_fetch_array($select_query1)) {
$select_query2 = mysql_query("SELECT new_animals, new_gardens FROM Table2WHERE new_date between date_sub(now(),INTERVAL 1 WEEK) and now()");
$count=0;
while($row2 = mysql_fetch_array($select_query2))
{
if ($row2['new_animals'] == $row1['animals'] && $row2['new_gardens'] == $row1['gardens']) {$count=1;}
}
if($count==0)
{
$animals = $row1['animals'];
$gardens = $row1['gardens'];
$date = $row1['date'];
$insert_query = mysql_query("INSERT INTO Table2 (new_date, new_animals, new_gardens)
VALUES ('$date', '$animals', '$gardens')");
}
}
$select_query1 = mysql_query("SELECT date, animals, gardens FROM Table1");
$select_query2 = mysql_query("SELECT new_animals, new_gardens FROM Table2
WHERE new_date between date_sub(now(),INTERVAL 1 WEEK) and now()");
$row1 = mysql_fetch_array($select_query1); // This returns 4 rows
$row2 = mysql_fetch_array($select_query2); // This returs 4 rows
$animalsArray = array();
while ($row2) {
$animalsArray[ $row2['new_animals']."_".$row2['new_gardens'] ]=$row2["new_animals"];
}
$insertValues = "";
while($row1){
if( $animalsArray[ $row1['animals']."_".$row1['gardens'] ] == "" ){
$animals = $row1['animals'];
$gardens = $row1['gardens'];
$date = $row1['date'];
$insertValues .= "('$date', '$animals', '$gardens'),";
}
}
$insertValues = substring( insertValues,0,-1); //delete last comma
$insert_query = "INSERT INTO Table2 (new_date, new_animals, new_gardens)VALUES ".$insertValues." ;
mysql_query($insert_query);
this line
$animalsArray[ $row2['new_animals']."_".$row2['new_gardens'] ] = $row2["new_animals"];
Create a position en array like that = $animalsArray[donkey_alabama] = 'donkey';
and this line
if( $animalsArray[ $row1['animals']."_".$row1['gardens'] ] == "" ) {}
Validate if exist that animal and garden , if not then insert
insertValues is to insert all values in one statement ( faster)
PD: Use mysqli_