0

I have four texts fields in my form that i need them to be inserted into my database,but the four fields are optional to either they should all be filled or just part of them,my problem is that in case the user just fills the two fields and leaves the other two empty,then the filled data should be inserted into mysql and the other blank fields should not be inserted.

This is what i have.

Artist:<input type="text" name="artist" />

Artist:<input type="text" name="artist1" />

Artist:<input type="text" name="artist2" />

Artist:<input type="text" name="artist3" />

//my php code

$sql="INSERT INTO artists (name) VALUES ('$artist'),('$artist1'),('$artist2'),('$artist3')";
mysql_query($sql);

but whenever i run this query it inserts all the four fields.Any help please. And is it relevant to use artist,artist1,artist2,artist3 in the four artist fields or i can just use maybe artist[] for the name part of all the four artist's fields i have?

0

4 Answers 4

1

Rename your inputs to have name="artist[]". Not strictly necessary, but much easier.

Artist:<input type="text" name="artist[]" />
Artist:<input type="text" name="artist[]" />
Artist:<input type="text" name="artist[]" />
Artist:<input type="text" name="artist[]" />

Then process them and build your query as necessary:

$rawArtists = (isset($_POST['artist']) && is_array($_POST['artist'])) ? $_POST['artist'] : array();

$artists = array();

foreach ($rawArtists as $artist) {
    if (is_string($artist) && strlen($artist)) {
        $artists[] = $artist;
    }
}

if (count($artists)) {

    //This could easily be a loop...  
    //I just enjoy abusing lambdas from time to time :)
    $artistVals = array_map(function ($art) {
        return "('" . mysql_real_escape_string($art) . "')";
    }, $artists);

    $vals = implode(',', $artistVals);

    $query = "INSERT INTO artists (name) VALUES $vals";

}
Sign up to request clarification or add additional context in comments.

1 Comment

+1 this deserves an upvote. Also nice example of lambda - personally I would throw in a loop there though. The lambda is only for PHP 5.3.0+.
1

You could configure your input-fields to return an array, iterate over that array and create the query dynamically.

$values = array();
foreach($artists AS $artist) {
    if(!empty($artist)) {
        $values[] = "('".mysqli_real_escape_string($artist)."')";
    }
}
if(count($values) > 0) {
    $sql = 'INSERT INTO artists (name) VALUES ' . implode(',', $values);
}

Should work. But please note that the mysql_* functions are deprecated and you are encouraged to use either the mysqli_* or the PDO functions.

6 Comments

I believe line 4 should be $values[] = :).
Please don't forget to escape the input data with mysqli_real_escape_string or something similar. I just edited the post above to do that.
@Corbin Of course it should, thanks. It's really early in the morning, so I'm still a tad slow.
You haven't quoted the values so this will fail. It will produce INSERT INTO artists (name) VALUES (metallica).
Also, on a super picky note, empty will consider the artist name 0 empty. Likely not a major issue, but I've seen more obscure things get people before.
|
0

This isn't a good idealogy. You can create a table with two columns for it. you table can be like

Create table Table_name(
Uid int(5) Auto_increment,
artistName varchar(20) NOT NULL
)

Primary key(Uid)

Now, you can use the query as:

<?php    
foreach($_GET as $name)
    mysql_query(insert into Table_Name(ArtistName) values('$name'));
?>

declaring the column as NOT NULL willnot allow to insert NULL values.

4 Comments

I had my name field in my database as NOT NULL but with my code i still got the NULL values inserted but thank you for your advice i will try to change it.
On some systems, table names are case sensitive. Also, Uid should probably be a primary key. And your PHP snippet is missing quotes... And $name should be escaped. And a form inserting into a database should probably be using $_POST. And, you should do some at least mild sanity checking on the value being inserted. I understand that answers aren't expected to be completely best practices following, pedantically perfect, but there's a lot of things wrong with this.
@Corbin Thanx for ur sug. But, I've done just a sample to show how that can be solved. I'vent given him direct ans so that he can use it directly. well as far as I know escaping. I recommend to use ADDSLASHES() instead of mysqli_real_escape_string() coz execution time increases when we use mysqli_real_escape_string(). As far as I know addslashes() method should be sufficient.
addslashes is faster only because it's not aware of character sets. That's also why it's not safe to use addslashes.
0

make your input field to have same name as array :

Artist:<input type="text" name="artist[]" />
Artist:<input type="text" name="artist[]" />
Artist:<input type="text" name="artist[]" />
Artist:<input type="text" name="artist[]" />

loop your artist

foreach($_POST['artist'] as $artist){
    //insert to db if not null
    if(trim($artist) != null){
        $sql="INSERT INTO artists (name) VALUES ('$artist')";
        mysql_query($sql);
    }
}

2 Comments

@RickyNkonya if you use this code, you should consider securing it for SQL Injection.
am sorry am not that good,help me what does that mean securing SQL Injection? @MrCode

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.