/    Sign up×
Community /Pin to ProfileBookmark

trying to use $_POST[‘var’] in a query, as text

i’m having trouble with the code below. it’s been simplified to show the problem. i use a loop because the input names are identical and need to create multiple new rows in a mysql table. the problem is i’m using $_POST[‘name’][$i] and the table won’t accept because it doesn’t see it as ‘text?, …i think.
like i said, code’s been greatly simplified.

for($i=0;$i<count($_POST[‘url’]); $i++) {
$sql = ‘INSERT INTO urls (url) VALUES (‘. $_POST[‘url’][$i].’)’;
if(!mysql_query($sql)) {
echo “error ” . mysql_error();
}
}

i tried to rememdy with this –
$sql = ‘INSERT INTO urls (url) VALUES (‘. ‘”‘. $_POST[‘url’][$i].'”‘. ‘)’;

if i do this it works, there is no error
$sql = ‘INSERT INTO urls (url) VALUES (‘ ” hello ” ‘)’;

this is probably a newbie type mistake, right? thanks for any help with this.

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@TecBratDec 17.2011 — I changed the $sql assignment to use double quotes so that I could more easily include single quotes inside it and used a temp variable to make the SQL statment a little easier to read. I have not tested this, but I think it might work. ?
[code=php]
<?
$max=count($_POST['url']); //moved this out of the for loop so you don't have to constanly re-count the size of the array.
for($i=0;$i<$max; $i++) {
$temp=$_POST['url'][$i]; // I put this here to simplify the next line
$sql = "INSERT INTO urls (url) VALUES ('$temp')";
/*
once $temp is evaluated, the actual query sent to mysql will be like:
INSERT INTO urls (url) VALUES ('www.myawesomesite.com')
*/
if(!mysql_query($sql)) {
echo "error " . mysql_error();
}
}
?>
[/code]


You could change the for loop into foreach like [code=php]
foreach($_POST['url'] as $url)
{
$sql = "INSERT INTO urls (url) VALUES ('$url')";
if(!mysql_query($sql))
{
echo "error " . mysql_error();
}
}
[/code]
Copy linkTweet thisAlerts:
@toptomatoauthorDec 17.2011 — thank-you!, i will try it
Copy linkTweet thisAlerts:
@toptomatoauthorDec 17.2011 — TecBrat, thanks again, that was just so helpful. i learned a lot from that.
×

Success!

Help @toptomato spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...