Jump to content

Looping through INSERT


billy_111

Recommended Posts

Hi,

 

I was wondering why this won't work, i am INSERTING an array of authors like so in a table, see insertAuthor() method below:

 

<?php
class People {

    public function insertAuthor(){

        $authArray = array();
        array_push($authArray, mysql_real_escape_string($_POST['author']));
        
        //Check if Pname exists
        foreach($authArray as $author):
            $query = "SELECT * FROM People WHERE Pname = '".$author."'";
            $result = mysql_query($query);

            if(mysql_num_rows($result) > 0):
                $row = mysql_fetch_array($result);
                $Pid = $row['Pid'];

                //If exists Get their Pid and insert into PeopleCon
                $sql = "INSERT INTO PeopleCon(Pid, PCorder, PCdateadded, PCdeleted) VALUES (".$Pid.", (select MAX(PCorder) + 1), now(), 0)";
                $result = mysql_query($sql);
            else:
                //Else Get MAX Pid
                $query = "SELECT MAX(Pid) as max FROM People";
                $result = mysql_query($query);
                $max = mysql_fetch_array($result);
                $Pid = $max['max'];

                //Insert into People
                $sql = "INSERT INTO People (Pname, Pdateadded, Pdeleted) VALUES ('".$author."', now(), 0)";
                $result = mysql_query($sql);

                //Insert into PeopleCon
                $sql = "INSERT INTO PeopleCon(Pid, PCorder, PCdateadded, PCdeleted) VALUES (".$Pid.", (select MAX(PCorder) + 1), now(),0)";
                $result = mysql_query($sql);
            endif;
        endforeach;
    }
}
?>

 

However what i need to do is, check to see if an Author exists, if so INSERT into a table called PeopleCon, if the Author does NOT exist i need to INSERT into 2 different tables, People  and PeopleCon...

 

The reason i have the 2 tables is because People simply holds the persons personal details, but PeopleCon holds details linking to different tables.

 

But this query does not work, i know there are better methods of getting this to work..

 

I do this in the front end:

 

if(isset($_POST['add_author'])):

        People::insertAuthor();

endif; 

 

Is this possible?

 

I would appreciate any help. Just want to get this working  :confused:

 

Thanks

 

Kind regards

Billy

Link to comment
https://forums.phpfreaks.com/topic/209902-looping-through-insert/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.