/    Sign up×
Community /Pin to ProfileBookmark

Inserting Data Into MySQL

What would be the correct way to write a line of PHP code that inserts data into your MySQL database?

to post a comment
PHP

24 Comments(s)

Copy linkTweet thisAlerts:
@NogDogJun 19.2008 — Depends on which database interface you want to use. If done correctly (e.g.: making sure there is no SQL injection problems and sufficient error-trapping), it will take more than a line of code (unless it's a fairly long line ? ).

For instance:
[code=php]
$db = new mysqli('localhost', 'user', 'pwd', 'db_name') or die('DB connection error');
$stmt = $db->prepare('INSERT INTO table (col1, col2, col3) VALUES (?, ?, ?)';
$stmt->bind_param('ssi', $var1, $var2, $var3);
if(!$stmt->execute())
{
error_log($stmt->error);
echo "Insert failed, error logged";
}
else
{
echo $stmt->affected_rows . " rows inserted.";
}
[/code]
Copy linkTweet thisAlerts:
@Joseph_WitchardauthorJun 19.2008 — Think you could explain to me what each bit of that script does?:o I'm not even familiar with that first function (prepare).

Thanks!
Copy linkTweet thisAlerts:
@NogDogJun 19.2008 — Check these manual pages first, then get back to us with any still unresolved questions:

http://www.php.net/manual/en/mysqli-stmt.prepare.php

http://www.php.net/manual/en/mysqli-stmt.bind-param.php
Copy linkTweet thisAlerts:
@Joseph_WitchardauthorJun 19.2008 — I'm using the original MySQL methods, not MySQLI. Will it work the same?
Copy linkTweet thisAlerts:
@Joseph_WitchardauthorJun 19.2008 — ((Sorry for the double post))

Okay, I've been experimenting with it myself, since NogDog is probably in bed right now (no hard feelings, NogDog? ). My code doesn't work, and I need to know why.

My code:
[code=php]<?php /* Check to see if the session is set.
If it is empty, or if it is not equal
to true, redirect the user to the homepage.
*/

session_start();


if (empty($_SESSION['wiggles']) || $_SESSION['wiggles'] != true) {

header('Location:http://www.uhrebirth.com/index.php');

}


// something to use to destroy the session

if (array_key_exists('log_out', $_POST) && !empty($_POST['log_out'])) {

sesstion_destroy();

exit;

}

$username = 'myusername';
$password = 'mypassword';

if (array_key_exists('submit', $_POST) && !empty($_POST['submit'])) {

// assign the form elements to variables

$userid = $_POST['userid'];
$username = $_POST['username'];
$userpwd = $_POST['password'];
$useremail = $_POST['useremail'];

// connect to MySQL

$conn = mysql_connect('news.uhrebirth.com', $username, $password);

// select the correct database

$selected_db = 'news_test_1';

$query = "INSERT INTO users WHERE (user_id, user_name, user_pwd, user_email) VALUES ('$userid', '$username', '$userpwd', '$useremail')";

$result = mysql_query($query);

if (!$result) {

die ('Sorry, but there was a problem with your request : ' . mysql_error());

}

mysql_close($conn);


}







?>[/code]


My form:
[code=html]<html>
<head>
<title>Test</title>
<LINK href="css/general.css" rel="stylesheet" type="text/css">
</head>
<body>

<div align="center">

<?php if (!$result) { echo 'Sorry, but there was a problem with your request'; } ?>

<form id="news_test" name="news_test" action="<?php echo $_SERVER['PHP_SELF']; ?>">

<label for="username">Username</label>
<input type="text" id="username" name="username" maxlength="30"> <br> <br>

<label for="useremail">Email</label>
<input type="text" id="useremail" name="useremail"> <br> <br>

<label for="userid">User ID</label>
<input type="text" id="userid" name="userid"> <br> <br>

<label for="password">Password</label>
<input type="text" id="password" name="password"> <br> <br>

<input type="submit" id="submit" name="submit" alt="Submit" value="Submit">
<input type="reset" alt="Reset" value="Reset">

</form>

<br> <br>

<form id="logout" name="logout" action="<?php echo $_SERVER['PHP_SELF']; ?>">

<input type="submit" id="log_out" name="log_out" value="Logout">

</body>
</html>
[/code]
Copy linkTweet thisAlerts:
@rootJun 19.2008 — I would first off look at the syntax and especially looking at some of the tests your performing.

I have no idea what your trying to do and I am no expert myself but in the reason and logic of things, this sticks out.

[CODE]if (empty($_SESSION['wiggles']) || $_SESSION['wiggles'] != true)[/CODE]

which I believe what your trying to say is

[CODE]if (empty($_SESSION['wiggles']) or !isset($_SESSION['wiggles']) )[/CODE]

I also think that you should test for the submit button being present with the 'isset' rather than 'empty'
Copy linkTweet thisAlerts:
@NogDogJun 19.2008 — The "WHERE" does not belong in your query where you have it.

You will want to use the mysql_real_escape_string() function to prevent SQL injection. (See http://www.php.net/mysql_real_escape_string for an explanation, as well as http://xkcd.com/327/.)

Also, there's no real need to copy the values from $_POST into new variables if you are not going to change the data in any manner. You could therefore simply construct your query as:

[code=php]
$query = "INSERT INTO users (user_id, user_name, user_pwd, user_email) VALUES ('" .
mysql_real_escape_string($_POST['userid']) . "', '" .
mysql_real_escape_string($_POST['username']) . "', '" .
mysql_real_escape_string($_POST['password']) . "', '" .
mysql_real_escape_string($_POST['useremail']) . "')";
[/code]
Copy linkTweet thisAlerts:
@Joseph_WitchardauthorJun 19.2008 — Well, I just realized that I need to parse the userid form field into an integer, since that's what that field in the database is set to. However, I've never done that in PHP, so could someone help me out?

Also, what are all the extra quote after the mysql_real_escape_string for?
Copy linkTweet thisAlerts:
@NogDogJun 19.2008 — Well, I just realized that I need to parse the userid form field into an integer, since that's what that field in the database is set to. However, I've never done that in PHP, so could someone help me out?[/quote]
As PHP is loosely typed, you normally do not need to worry about such conversions. If you want to validate that the user entered an integer, you can use the ctype_digit() function to check it. If you just want to quietly convert whatever they entered to an integer, you can cast it either via the [b](int)[/b] [url=http://www.php.net/manual/en/language.types.type-juggling.php]type-casting[/url] mechanism, or you could use the [url=http://www.php.net/settype]settype() function[/url].
Also, what are all the extra quote after the mysql_real_escape_string for?[/QUOTE]
Unless I made a typo somewhere (always a possibility), there should be no "extra" quotes. However, in order to use the mysql_real_escape_string() function I used concatenation while building the query string, so had to "interrupt" the string by closing it with a quote, add a concatenation operator (the dot), do the function call, another dot, then a quote to get back into the string. An alternative method would be to use sprintf():
[code=php]
$query = sprintf(
"INSERT INTO users (user_id, user_name, user_pwd, user_email) VALUES ('%s', %s', '%s', '%s')",
mysql_real_escape_string($_POST['userid']),
mysql_real_escape_string($_POST['username']),
mysql_real_escape_string($_POST['password']),
mysql_real_escape_string($_POST['useremail'])
);
[/code]
Copy linkTweet thisAlerts:
@Joseph_WitchardauthorJun 19.2008 — What are all of the '%s' in the query values?
Copy linkTweet thisAlerts:
@NogDogJun 19.2008 — It's in the manual: www.php.net/sprintf
Copy linkTweet thisAlerts:
@Joseph_WitchardauthorJun 19.2008 — So, with the userid field, would

[code=php]%c[/code]

turn it into an integer?

Sorry for my slowness; this is all very new to me.
Copy linkTweet thisAlerts:
@NogDogJun 19.2008 — %d (think of "[b]d[/b]igit" to remember it)

PS: and in this case you won't need to quote it in the query, nor filter it through mysql_real_escape_string() (but always filter any such inputs that are not explicitly converted to integers or floats).
Copy linkTweet thisAlerts:
@Joseph_WitchardauthorJun 20.2008 — How does sprintf() know to take my form fields with those arguments (%s)?

Also, is MySQL on its way out real soon? Is it all right if I use the original MySQL functions, or is it imperative that I learn how to use MySQLI or PDO?
Copy linkTweet thisAlerts:
@NogDogJun 20.2008 — Each argument supplied to sprintf() after the first one (the pattern string) is correlated to each successive %<char> place-holder. So in the following, $string is applied to %s, $integer to %d, and $float to %f:
[code=php]
$string = sprintf("The string: '%s', the integer: %d, the float: %f", $string, $integer, $float);
[/code]

I doubt that the mysql functions will go away any time in the foreseeable future, as they are so widely used. But if creating new applications that do not need to be PHP4-compatible; then mysqli gives you more functionality, support of more of the newer MySQL 4.1/5.x features, and can be used in an object-oriented manner.
Copy linkTweet thisAlerts:
@Joseph_WitchardauthorJun 20.2008 — Each argument supplied to sprintf() after the first one (the pattern string) is correlated to each successive %<char> place-holder. So in the following, $string is applied to %s, $integer to %d, and $float to %f:[/QUOTE]

I'm not quite sure what you meant by that:o Could you explain it a bit more slowly? I can see how those variables would be applied to it, I just don't understand how my form fields are able to get there using that function.
Copy linkTweet thisAlerts:
@NogDogJun 20.2008 — Each place-holder -- the "%s", "%d", etc. -- in the string that is the first argument to the sprintf() function requires an additional parameter in the sprintf() parameter list. The first such parameter's value is used for the first place-holder, the second for the second one, etc. (There is a special exception to this rule if you use numbered place-holders, but let's pretend that does not exist for now.) The following would therefore echo [b]<p>Hello, World!</p>[/b].
[code=php]
$var1 = 'Hello';
$var2 = 'World';
echo sprintf("<p>%s, %s!</p>", $var1, $var2);
[/code]

If we reversed the 2nd and 3rd arguments, it would instead print [b]<p>World, Hello!</p>[/b]:
[code=php]
echo sprintf("</p>%s, %s!</p>", $var2, $var1);
[/code]

(Note that we could just do [b]printf()[/b] instead of [b]echo sprintf()[/b], but I didn't want to change functions here.)
Copy linkTweet thisAlerts:
@Joseph_WitchardauthorJun 20.2008 — One of your earlier posts:
$query = sprintf(

"INSERT INTO users (user_id, user_name, user_pwd, user_email) VALUES ('%s', %s', '%s', '%s')",

mysql_real_escape_string($_POST['userid']),

mysql_real_escape_string($_
POST['username']),

mysql_real_escape_string($_POST['password']),

mysql_real_escape_string($_
POST['useremail'])

); [/QUOTE]


You didn't pass any variables to it that time like you did in your last example, though. Is this what you mean? My form fields get into values because the $_POST fields are inside the sprintf() function?
Copy linkTweet thisAlerts:
@NogDogJun 21.2008 — The values do not have to be variables, just any valid expression. They could be a variable, a string literal, a number, or (as in this case) the return value from a function call (the mysql_real_escape_string() function).
Copy linkTweet thisAlerts:
@Joseph_WitchardauthorJun 21.2008 — I think I get it now. Thanks? What qualifies as a PHP expression?
Copy linkTweet thisAlerts:
@Joseph_WitchardauthorJun 21.2008 — Thanks? And while I'm here, I noticed you used a certain operator (->) in your MySQLI functions. Could you explain that operator to me?
Copy linkTweet thisAlerts:
@NogDogJun 21.2008 — [url=http://www-128.ibm.com/developerworks/opensource/library/os-phpobj/]An introductory PHP5 OOP tutorial[/url]
×

Success!

Help @Joseph_Witchard 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 6.2,
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: @meenaratha,
tipped: article
amount: 1000 SATS,

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

tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,
)...