Firefog Firefog - 5 months ago 17
SQL Question

MySQL Insert on first table and update on 2nd table

I am trying to insert data into table_1 and then insert on second table if the new inserted ID not available on 2nd table if available then update it. Bellow is my code please tell me what I'm doing wrong.

<?php
$name='Name';
$pass='Passsword';
$rid='FR200000';


$sql = "INSERT INTO table_1 (id,name,pass) VALUES('".$rid."','".$name."','".$pass."')";
$res = mysql_query($sql);
if(!$res){
echo'Failed to insert';

}else{
$sql = "SELECT id FROM site_settings WHERE id = '".$rid."'";
$res = mysql_query($sql);
$get_id = mysql_fetch_assoc($res);

if (!$get_id==$rid){
$site_url = 'www.example.com';
$site_email ='example@mysite.com';

$sql = "INSERT INTO site_settings (id,site_url,site_email) VALUES('".$rid."','".$site_url."','".$site_email."')";
$res = mysql_query($sql);
if(!$res) return 1;
return 99;
}
if ($get_id==$rid){

$sql = "UPDATE site_settings SET site_url = '" . $site_url . "', site_email = '" . $site_email . "' WHERE ID = '".$rid."'";
$res = mysql_query($sql);
if(!$res) return 1;
return 99;
}
?>

Answer

mysql_query()

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset

$sql = "SELECT id FROM site_settings WHERE id = '".$rid."'";
        $get_id = mysql_query($sql);

You will not compare directly result set with $rid

if (!$get_id==$rid){

You need to fetch data first

$row = mysql_fetch_assoc($res);
$get_id=$row['id'];// fetch data

Then compare

if (!$get_id==$rid){
// YOUR code

NOTE:- mysql is deprecated instead use mysqli OR PDO

Comments