Html Form Input Field With Comma Separated
I am trying to figure out how to take multiple word input in a single text box in a form with each word separated by comma(,) and then paring the word based on comma and inserting
Solution 1:
I know a bunch of mysql_* function answers are going to come in, so ill add the prepared query route.
This isn't flawless, but you'll get the idea
// Get the array of words$words = explode( ',', $formname );
// Create an array of :word1, :word2, :word3, etc for use in bindingforeach( range( 1, count( $words ) ) as$wordnumber ) {
$bind[] = ':word'.$wordnumber;
}
// Create the sql query$sql = sprintf( "insert into table ( word ) values ( %s )", implode( '),(', $bind ) );
// Prepare the query$stmnt = $pdo->prepare( $sql );
// Bind each wordforeach( $wordsas$k => $word ) {
$stmnt->bindValue( ":word" . ++$k, $word );
}
// Execute$stmnt->execute();
Solution 2:
You could do it with PDO too:
<?php//Connect safely to your databasetry {
$db = new PDO("mysql:host=localhost;dbname=test", 'root', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
} catch (PDOException $e) {
die('Cannot connect to mySQL server. Details:'.$e->getMessage());
}
if ($_SERVER['REQUEST_METHOD']=='POST' && !empty($_POST['words'])) {
$sql = "INSERT INTO words_table (word) VALUES (:word)";
$stmt = $db->prepare($sql);
$stmt->bindParam(':word', $word);
foreach (explode(',', $_POST['words']) as$word) {
$word = trim($word);
if (empty($word)) {
continue;
}
$stmt->execute();
}
}
//Your form?><h1>Words</h1><formmethod="POST"action=""><inputtype="text"name="words"/><inputtype="submit"name="submit"value="Submit"/></form>
Solution 3:
$str = $_POST['words'];
$piece = explode(',',$str);
foreach($pieceas$substr){
mysql_query("INSERT INTO test (words) VALUES ('".$substr."');";
}
Solution 4:
If you need to encapsulate the words in quotes, this should do the trick:
<?php$myString='sometext,someothertext,and something else';
$query="insert into table1 (columnName) values (('".str_replace(',',"'),('",$myString)."'))";
echo$query;
?>
Output:
insertinto table1 (columnName) values (('sometext'),('someothertext'),('and something else'))
This will insert multiple records in proper accordance with the mysql insert multiple values syntax.
Post a Comment for "Html Form Input Field With Comma Separated"