Input values become number automatically when insert to MySQL
I'm trying to insert into my table in database. I'm doing it with ajax.
Here is my code:
$(document).on('click','.add', function(){
var id = $(this).attr("id");
var DT = $('#DT'+id).val();
var SV = $('.search_text').val(); // store input value
var action = "add";
$.ajax({
url:"action.php",
method:"POST",
data:{DT:DT, SV:SV,action:action,id:id},
success: function(data){
alert("success");
},
error: function(){
alert("error action");
}
});
});
Data will point to action.php. Here is the code of action.php:
if (isset($_POST['action'])) {
if($_POST["action"] == "add") {
$insert_dtb = mysqli_query($con, "INSERT INTO table_dtb(SV, DT, DK, NH, ttDK, ngTT)
value($_POST[SV],$_POST[DT],now(),$_POST[SV],'1',now());");
}
}
But my input value in SV variable become number when insert to table.
Example: if I enter 0153222, then in column SV of table table_dtb it only be 153222 and I can't input character into the column SV.
Although I set column SV in table_dtb is varchar(9), It's not working as I expected.
php jquery mysql sql ajax
|
show 2 more comments
I'm trying to insert into my table in database. I'm doing it with ajax.
Here is my code:
$(document).on('click','.add', function(){
var id = $(this).attr("id");
var DT = $('#DT'+id).val();
var SV = $('.search_text').val(); // store input value
var action = "add";
$.ajax({
url:"action.php",
method:"POST",
data:{DT:DT, SV:SV,action:action,id:id},
success: function(data){
alert("success");
},
error: function(){
alert("error action");
}
});
});
Data will point to action.php. Here is the code of action.php:
if (isset($_POST['action'])) {
if($_POST["action"] == "add") {
$insert_dtb = mysqli_query($con, "INSERT INTO table_dtb(SV, DT, DK, NH, ttDK, ngTT)
value($_POST[SV],$_POST[DT],now(),$_POST[SV],'1',now());");
}
}
But my input value in SV variable become number when insert to table.
Example: if I enter 0153222, then in column SV of table table_dtb it only be 153222 and I can't input character into the column SV.
Although I set column SV in table_dtb is varchar(9), It's not working as I expected.
php jquery mysql sql ajax
4
holy mother of sql injection.
– Chad
Jan 3 at 16:56
2
Kit Harrington: Sql Injection is coming!!!
– Kebab Programmer
Jan 3 at 16:57
1
Use parameterized queries and the problem will vanish (and will also fix the sql injection vulnerability)
– Andreas
Jan 3 at 16:59
1
Since you're not using prepared statements (you really ought to, by the way), try echoing out your insert query to make sure it's inserting what you think it is. Something else might be dropping the beginning 0. Otherwise, I'm going to guess it's because the variables are not quoted, so MySQL is treating the values as a number instead of a string, and dropping the 0. Using prepared statements and parameter binding would solve it.
– aynber
Jan 3 at 17:00
Note that there exists mysqli/PDO wrappers which can handle prerpared statements for you automatically. For example, my class GrumpyPDO, your code would become$db->run("INSERT INTO table_dtb (SV, DT, DK, NH, ttDK, ngTT) VALUES (?, ?, now(), ?, '1', now())", [$_POST['sv'], $_POST['dt'], $_POST['sv']]);, and it would be safe from SQL injection.
– GrumpyCrouton
Jan 3 at 17:03
|
show 2 more comments
I'm trying to insert into my table in database. I'm doing it with ajax.
Here is my code:
$(document).on('click','.add', function(){
var id = $(this).attr("id");
var DT = $('#DT'+id).val();
var SV = $('.search_text').val(); // store input value
var action = "add";
$.ajax({
url:"action.php",
method:"POST",
data:{DT:DT, SV:SV,action:action,id:id},
success: function(data){
alert("success");
},
error: function(){
alert("error action");
}
});
});
Data will point to action.php. Here is the code of action.php:
if (isset($_POST['action'])) {
if($_POST["action"] == "add") {
$insert_dtb = mysqli_query($con, "INSERT INTO table_dtb(SV, DT, DK, NH, ttDK, ngTT)
value($_POST[SV],$_POST[DT],now(),$_POST[SV],'1',now());");
}
}
But my input value in SV variable become number when insert to table.
Example: if I enter 0153222, then in column SV of table table_dtb it only be 153222 and I can't input character into the column SV.
Although I set column SV in table_dtb is varchar(9), It's not working as I expected.
php jquery mysql sql ajax
I'm trying to insert into my table in database. I'm doing it with ajax.
Here is my code:
$(document).on('click','.add', function(){
var id = $(this).attr("id");
var DT = $('#DT'+id).val();
var SV = $('.search_text').val(); // store input value
var action = "add";
$.ajax({
url:"action.php",
method:"POST",
data:{DT:DT, SV:SV,action:action,id:id},
success: function(data){
alert("success");
},
error: function(){
alert("error action");
}
});
});
Data will point to action.php. Here is the code of action.php:
if (isset($_POST['action'])) {
if($_POST["action"] == "add") {
$insert_dtb = mysqli_query($con, "INSERT INTO table_dtb(SV, DT, DK, NH, ttDK, ngTT)
value($_POST[SV],$_POST[DT],now(),$_POST[SV],'1',now());");
}
}
But my input value in SV variable become number when insert to table.
Example: if I enter 0153222, then in column SV of table table_dtb it only be 153222 and I can't input character into the column SV.
Although I set column SV in table_dtb is varchar(9), It's not working as I expected.
php jquery mysql sql ajax
php jquery mysql sql ajax
edited Jan 4 at 2:38
Funk Forty Niner
1
1
asked Jan 3 at 16:56
JonJon
64
64
4
holy mother of sql injection.
– Chad
Jan 3 at 16:56
2
Kit Harrington: Sql Injection is coming!!!
– Kebab Programmer
Jan 3 at 16:57
1
Use parameterized queries and the problem will vanish (and will also fix the sql injection vulnerability)
– Andreas
Jan 3 at 16:59
1
Since you're not using prepared statements (you really ought to, by the way), try echoing out your insert query to make sure it's inserting what you think it is. Something else might be dropping the beginning 0. Otherwise, I'm going to guess it's because the variables are not quoted, so MySQL is treating the values as a number instead of a string, and dropping the 0. Using prepared statements and parameter binding would solve it.
– aynber
Jan 3 at 17:00
Note that there exists mysqli/PDO wrappers which can handle prerpared statements for you automatically. For example, my class GrumpyPDO, your code would become$db->run("INSERT INTO table_dtb (SV, DT, DK, NH, ttDK, ngTT) VALUES (?, ?, now(), ?, '1', now())", [$_POST['sv'], $_POST['dt'], $_POST['sv']]);, and it would be safe from SQL injection.
– GrumpyCrouton
Jan 3 at 17:03
|
show 2 more comments
4
holy mother of sql injection.
– Chad
Jan 3 at 16:56
2
Kit Harrington: Sql Injection is coming!!!
– Kebab Programmer
Jan 3 at 16:57
1
Use parameterized queries and the problem will vanish (and will also fix the sql injection vulnerability)
– Andreas
Jan 3 at 16:59
1
Since you're not using prepared statements (you really ought to, by the way), try echoing out your insert query to make sure it's inserting what you think it is. Something else might be dropping the beginning 0. Otherwise, I'm going to guess it's because the variables are not quoted, so MySQL is treating the values as a number instead of a string, and dropping the 0. Using prepared statements and parameter binding would solve it.
– aynber
Jan 3 at 17:00
Note that there exists mysqli/PDO wrappers which can handle prerpared statements for you automatically. For example, my class GrumpyPDO, your code would become$db->run("INSERT INTO table_dtb (SV, DT, DK, NH, ttDK, ngTT) VALUES (?, ?, now(), ?, '1', now())", [$_POST['sv'], $_POST['dt'], $_POST['sv']]);, and it would be safe from SQL injection.
– GrumpyCrouton
Jan 3 at 17:03
4
4
holy mother of sql injection.
– Chad
Jan 3 at 16:56
holy mother of sql injection.
– Chad
Jan 3 at 16:56
2
2
Kit Harrington: Sql Injection is coming!!!
– Kebab Programmer
Jan 3 at 16:57
Kit Harrington: Sql Injection is coming!!!
– Kebab Programmer
Jan 3 at 16:57
1
1
Use parameterized queries and the problem will vanish (and will also fix the sql injection vulnerability)
– Andreas
Jan 3 at 16:59
Use parameterized queries and the problem will vanish (and will also fix the sql injection vulnerability)
– Andreas
Jan 3 at 16:59
1
1
Since you're not using prepared statements (you really ought to, by the way), try echoing out your insert query to make sure it's inserting what you think it is. Something else might be dropping the beginning 0. Otherwise, I'm going to guess it's because the variables are not quoted, so MySQL is treating the values as a number instead of a string, and dropping the 0. Using prepared statements and parameter binding would solve it.
– aynber
Jan 3 at 17:00
Since you're not using prepared statements (you really ought to, by the way), try echoing out your insert query to make sure it's inserting what you think it is. Something else might be dropping the beginning 0. Otherwise, I'm going to guess it's because the variables are not quoted, so MySQL is treating the values as a number instead of a string, and dropping the 0. Using prepared statements and parameter binding would solve it.
– aynber
Jan 3 at 17:00
Note that there exists mysqli/PDO wrappers which can handle prerpared statements for you automatically. For example, my class GrumpyPDO, your code would become
$db->run("INSERT INTO table_dtb (SV, DT, DK, NH, ttDK, ngTT) VALUES (?, ?, now(), ?, '1', now())", [$_POST['sv'], $_POST['dt'], $_POST['sv']]);, and it would be safe from SQL injection.– GrumpyCrouton
Jan 3 at 17:03
Note that there exists mysqli/PDO wrappers which can handle prerpared statements for you automatically. For example, my class GrumpyPDO, your code would become
$db->run("INSERT INTO table_dtb (SV, DT, DK, NH, ttDK, ngTT) VALUES (?, ?, now(), ?, '1', now())", [$_POST['sv'], $_POST['dt'], $_POST['sv']]);, and it would be safe from SQL injection.– GrumpyCrouton
Jan 3 at 17:03
|
show 2 more comments
1 Answer
1
active
oldest
votes
You're passing the value of $_POST[SV] twice when presumably it should be whatever value you wanted for NH. Still, not only would you have caught this using prepared statements, but you're just setting yourself up for SQL injection with your current code.
Take a look at this example:
<?php
try {
/* setup your database configuration */
$config = array(
"host" => "127.0.0.1",
"username" => "root",
"password" => "",
"name" => "db_name"
);
$dsn = "mysql:dbname=$config[name];host=$config[host];charset=utf8mb4";
$db = new PDO($dsn, $config["username"], $config["password"]);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
/* prepare the SQL statement */
$stmt = $db->prepare("
INSERT INTO `table_dtb` (
`SV`, `DT`, `DK`, `NH`, `ttDK`, `ngTT`
) VALUES (
:sv, :dt, NOW(), :nh, '1', NOW()
);
");
/* execute the statement passing the parameterized values */
$stmt->execute(array(
":sv" => $_POST["SV"],
":dt" => $_POST["DT"],
":nh" => $_POST["NH"]
));
} catch(PDOException $ex) {
/* pdo exception */
} catch (Exception $e) {
/* php exception */
}
?>
To explain what the code does, you can break it down into 4 distinct sections. The first section is the Try/Catch exception handler. Anytime that you have a piece of code that has the ability to fail you should wrap it in Try/Catch handlers, what this does is say "I will try to execute this code, but if it fails then I want to take care of the error that ensues." The reason there are two separate catch blocks is that you have one to take care of database errors and another to take care of your normal PHP errors. If all you wanted to do with errors is tell the user that an error happened, simply use an echo statement. However, if you are debugging and the error message is relevant then you can get the execption's message by calling the getMessage function.
The second section is the database configuration. Starting in PHP 5, PHP Data Objects are used to handle your database operations. The reason I personally setup a configuration array is because to me it is simpler to debug and read, though it is not entirely necessary. The important part is that you create a new PDO object.
The third section is preparing the SQL statement using parameterized values. Because whitespace is ignored in SQL statements and PHP allows for line continuations in String literals, you are able to format your SQL statement for better readability by using separate lines for different segments of your SQL statement. The basic idea of the values that have the : prefix before them is that they represent a value not stored directly in the SQL String.
The fourth section is executing the parameterized query. Calling the execute function on its own would run the SQL statement, but because you've passed parameters in the SQL query you also need to pass the values that are to be sent. In this case we have named parameters, so in an associative array we specify the name of the parameter as the key and then assign the value to be passed as the value.
Hopefully this clears up the code for you and if you have any questions feel free to ask.
This hasn't really said anything more than the comments on the question have, because even though you show proper code for doing this, you do not explain how the code works, or why you are doing what you are doing. Edit: not my DV
– GrumpyCrouton
Jan 3 at 17:22
@GrumpyCrouton - I try to explain the code via comments in the code.
– David
Jan 3 at 21:30
Perhaps, very vaguely. You don't explain why you are setting those specific attributes, or how the placeholders work for the variables, or howtry -> catchworks, or why you have multiple catches. Your code and OP's code is light-years apart. If OP already used these things, that would be one thing, but they don't. This is an example of an answer that was probably copied + pasted into the OP's code, which works, but they haven't actually gained any knowledge about the proper way to do these things. And that, in my opinion, makes this answer "not useful".
– GrumpyCrouton
Jan 3 at 21:36
@GrumpyCrouton - Fair enough, I've elaborated on my answer.
– David
Jan 4 at 2:38
I think you should read their question again; something that I've commented about under their (unclear) question, something nobody caught. Note: Not my downvote.
– Funk Forty Niner
Jan 4 at 2:42
add a comment |
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54026587%2finput-values-become-number-automatically-when-insert-to-mysql%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
You're passing the value of $_POST[SV] twice when presumably it should be whatever value you wanted for NH. Still, not only would you have caught this using prepared statements, but you're just setting yourself up for SQL injection with your current code.
Take a look at this example:
<?php
try {
/* setup your database configuration */
$config = array(
"host" => "127.0.0.1",
"username" => "root",
"password" => "",
"name" => "db_name"
);
$dsn = "mysql:dbname=$config[name];host=$config[host];charset=utf8mb4";
$db = new PDO($dsn, $config["username"], $config["password"]);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
/* prepare the SQL statement */
$stmt = $db->prepare("
INSERT INTO `table_dtb` (
`SV`, `DT`, `DK`, `NH`, `ttDK`, `ngTT`
) VALUES (
:sv, :dt, NOW(), :nh, '1', NOW()
);
");
/* execute the statement passing the parameterized values */
$stmt->execute(array(
":sv" => $_POST["SV"],
":dt" => $_POST["DT"],
":nh" => $_POST["NH"]
));
} catch(PDOException $ex) {
/* pdo exception */
} catch (Exception $e) {
/* php exception */
}
?>
To explain what the code does, you can break it down into 4 distinct sections. The first section is the Try/Catch exception handler. Anytime that you have a piece of code that has the ability to fail you should wrap it in Try/Catch handlers, what this does is say "I will try to execute this code, but if it fails then I want to take care of the error that ensues." The reason there are two separate catch blocks is that you have one to take care of database errors and another to take care of your normal PHP errors. If all you wanted to do with errors is tell the user that an error happened, simply use an echo statement. However, if you are debugging and the error message is relevant then you can get the execption's message by calling the getMessage function.
The second section is the database configuration. Starting in PHP 5, PHP Data Objects are used to handle your database operations. The reason I personally setup a configuration array is because to me it is simpler to debug and read, though it is not entirely necessary. The important part is that you create a new PDO object.
The third section is preparing the SQL statement using parameterized values. Because whitespace is ignored in SQL statements and PHP allows for line continuations in String literals, you are able to format your SQL statement for better readability by using separate lines for different segments of your SQL statement. The basic idea of the values that have the : prefix before them is that they represent a value not stored directly in the SQL String.
The fourth section is executing the parameterized query. Calling the execute function on its own would run the SQL statement, but because you've passed parameters in the SQL query you also need to pass the values that are to be sent. In this case we have named parameters, so in an associative array we specify the name of the parameter as the key and then assign the value to be passed as the value.
Hopefully this clears up the code for you and if you have any questions feel free to ask.
This hasn't really said anything more than the comments on the question have, because even though you show proper code for doing this, you do not explain how the code works, or why you are doing what you are doing. Edit: not my DV
– GrumpyCrouton
Jan 3 at 17:22
@GrumpyCrouton - I try to explain the code via comments in the code.
– David
Jan 3 at 21:30
Perhaps, very vaguely. You don't explain why you are setting those specific attributes, or how the placeholders work for the variables, or howtry -> catchworks, or why you have multiple catches. Your code and OP's code is light-years apart. If OP already used these things, that would be one thing, but they don't. This is an example of an answer that was probably copied + pasted into the OP's code, which works, but they haven't actually gained any knowledge about the proper way to do these things. And that, in my opinion, makes this answer "not useful".
– GrumpyCrouton
Jan 3 at 21:36
@GrumpyCrouton - Fair enough, I've elaborated on my answer.
– David
Jan 4 at 2:38
I think you should read their question again; something that I've commented about under their (unclear) question, something nobody caught. Note: Not my downvote.
– Funk Forty Niner
Jan 4 at 2:42
add a comment |
You're passing the value of $_POST[SV] twice when presumably it should be whatever value you wanted for NH. Still, not only would you have caught this using prepared statements, but you're just setting yourself up for SQL injection with your current code.
Take a look at this example:
<?php
try {
/* setup your database configuration */
$config = array(
"host" => "127.0.0.1",
"username" => "root",
"password" => "",
"name" => "db_name"
);
$dsn = "mysql:dbname=$config[name];host=$config[host];charset=utf8mb4";
$db = new PDO($dsn, $config["username"], $config["password"]);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
/* prepare the SQL statement */
$stmt = $db->prepare("
INSERT INTO `table_dtb` (
`SV`, `DT`, `DK`, `NH`, `ttDK`, `ngTT`
) VALUES (
:sv, :dt, NOW(), :nh, '1', NOW()
);
");
/* execute the statement passing the parameterized values */
$stmt->execute(array(
":sv" => $_POST["SV"],
":dt" => $_POST["DT"],
":nh" => $_POST["NH"]
));
} catch(PDOException $ex) {
/* pdo exception */
} catch (Exception $e) {
/* php exception */
}
?>
To explain what the code does, you can break it down into 4 distinct sections. The first section is the Try/Catch exception handler. Anytime that you have a piece of code that has the ability to fail you should wrap it in Try/Catch handlers, what this does is say "I will try to execute this code, but if it fails then I want to take care of the error that ensues." The reason there are two separate catch blocks is that you have one to take care of database errors and another to take care of your normal PHP errors. If all you wanted to do with errors is tell the user that an error happened, simply use an echo statement. However, if you are debugging and the error message is relevant then you can get the execption's message by calling the getMessage function.
The second section is the database configuration. Starting in PHP 5, PHP Data Objects are used to handle your database operations. The reason I personally setup a configuration array is because to me it is simpler to debug and read, though it is not entirely necessary. The important part is that you create a new PDO object.
The third section is preparing the SQL statement using parameterized values. Because whitespace is ignored in SQL statements and PHP allows for line continuations in String literals, you are able to format your SQL statement for better readability by using separate lines for different segments of your SQL statement. The basic idea of the values that have the : prefix before them is that they represent a value not stored directly in the SQL String.
The fourth section is executing the parameterized query. Calling the execute function on its own would run the SQL statement, but because you've passed parameters in the SQL query you also need to pass the values that are to be sent. In this case we have named parameters, so in an associative array we specify the name of the parameter as the key and then assign the value to be passed as the value.
Hopefully this clears up the code for you and if you have any questions feel free to ask.
This hasn't really said anything more than the comments on the question have, because even though you show proper code for doing this, you do not explain how the code works, or why you are doing what you are doing. Edit: not my DV
– GrumpyCrouton
Jan 3 at 17:22
@GrumpyCrouton - I try to explain the code via comments in the code.
– David
Jan 3 at 21:30
Perhaps, very vaguely. You don't explain why you are setting those specific attributes, or how the placeholders work for the variables, or howtry -> catchworks, or why you have multiple catches. Your code and OP's code is light-years apart. If OP already used these things, that would be one thing, but they don't. This is an example of an answer that was probably copied + pasted into the OP's code, which works, but they haven't actually gained any knowledge about the proper way to do these things. And that, in my opinion, makes this answer "not useful".
– GrumpyCrouton
Jan 3 at 21:36
@GrumpyCrouton - Fair enough, I've elaborated on my answer.
– David
Jan 4 at 2:38
I think you should read their question again; something that I've commented about under their (unclear) question, something nobody caught. Note: Not my downvote.
– Funk Forty Niner
Jan 4 at 2:42
add a comment |
You're passing the value of $_POST[SV] twice when presumably it should be whatever value you wanted for NH. Still, not only would you have caught this using prepared statements, but you're just setting yourself up for SQL injection with your current code.
Take a look at this example:
<?php
try {
/* setup your database configuration */
$config = array(
"host" => "127.0.0.1",
"username" => "root",
"password" => "",
"name" => "db_name"
);
$dsn = "mysql:dbname=$config[name];host=$config[host];charset=utf8mb4";
$db = new PDO($dsn, $config["username"], $config["password"]);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
/* prepare the SQL statement */
$stmt = $db->prepare("
INSERT INTO `table_dtb` (
`SV`, `DT`, `DK`, `NH`, `ttDK`, `ngTT`
) VALUES (
:sv, :dt, NOW(), :nh, '1', NOW()
);
");
/* execute the statement passing the parameterized values */
$stmt->execute(array(
":sv" => $_POST["SV"],
":dt" => $_POST["DT"],
":nh" => $_POST["NH"]
));
} catch(PDOException $ex) {
/* pdo exception */
} catch (Exception $e) {
/* php exception */
}
?>
To explain what the code does, you can break it down into 4 distinct sections. The first section is the Try/Catch exception handler. Anytime that you have a piece of code that has the ability to fail you should wrap it in Try/Catch handlers, what this does is say "I will try to execute this code, but if it fails then I want to take care of the error that ensues." The reason there are two separate catch blocks is that you have one to take care of database errors and another to take care of your normal PHP errors. If all you wanted to do with errors is tell the user that an error happened, simply use an echo statement. However, if you are debugging and the error message is relevant then you can get the execption's message by calling the getMessage function.
The second section is the database configuration. Starting in PHP 5, PHP Data Objects are used to handle your database operations. The reason I personally setup a configuration array is because to me it is simpler to debug and read, though it is not entirely necessary. The important part is that you create a new PDO object.
The third section is preparing the SQL statement using parameterized values. Because whitespace is ignored in SQL statements and PHP allows for line continuations in String literals, you are able to format your SQL statement for better readability by using separate lines for different segments of your SQL statement. The basic idea of the values that have the : prefix before them is that they represent a value not stored directly in the SQL String.
The fourth section is executing the parameterized query. Calling the execute function on its own would run the SQL statement, but because you've passed parameters in the SQL query you also need to pass the values that are to be sent. In this case we have named parameters, so in an associative array we specify the name of the parameter as the key and then assign the value to be passed as the value.
Hopefully this clears up the code for you and if you have any questions feel free to ask.
You're passing the value of $_POST[SV] twice when presumably it should be whatever value you wanted for NH. Still, not only would you have caught this using prepared statements, but you're just setting yourself up for SQL injection with your current code.
Take a look at this example:
<?php
try {
/* setup your database configuration */
$config = array(
"host" => "127.0.0.1",
"username" => "root",
"password" => "",
"name" => "db_name"
);
$dsn = "mysql:dbname=$config[name];host=$config[host];charset=utf8mb4";
$db = new PDO($dsn, $config["username"], $config["password"]);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
/* prepare the SQL statement */
$stmt = $db->prepare("
INSERT INTO `table_dtb` (
`SV`, `DT`, `DK`, `NH`, `ttDK`, `ngTT`
) VALUES (
:sv, :dt, NOW(), :nh, '1', NOW()
);
");
/* execute the statement passing the parameterized values */
$stmt->execute(array(
":sv" => $_POST["SV"],
":dt" => $_POST["DT"],
":nh" => $_POST["NH"]
));
} catch(PDOException $ex) {
/* pdo exception */
} catch (Exception $e) {
/* php exception */
}
?>
To explain what the code does, you can break it down into 4 distinct sections. The first section is the Try/Catch exception handler. Anytime that you have a piece of code that has the ability to fail you should wrap it in Try/Catch handlers, what this does is say "I will try to execute this code, but if it fails then I want to take care of the error that ensues." The reason there are two separate catch blocks is that you have one to take care of database errors and another to take care of your normal PHP errors. If all you wanted to do with errors is tell the user that an error happened, simply use an echo statement. However, if you are debugging and the error message is relevant then you can get the execption's message by calling the getMessage function.
The second section is the database configuration. Starting in PHP 5, PHP Data Objects are used to handle your database operations. The reason I personally setup a configuration array is because to me it is simpler to debug and read, though it is not entirely necessary. The important part is that you create a new PDO object.
The third section is preparing the SQL statement using parameterized values. Because whitespace is ignored in SQL statements and PHP allows for line continuations in String literals, you are able to format your SQL statement for better readability by using separate lines for different segments of your SQL statement. The basic idea of the values that have the : prefix before them is that they represent a value not stored directly in the SQL String.
The fourth section is executing the parameterized query. Calling the execute function on its own would run the SQL statement, but because you've passed parameters in the SQL query you also need to pass the values that are to be sent. In this case we have named parameters, so in an associative array we specify the name of the parameter as the key and then assign the value to be passed as the value.
Hopefully this clears up the code for you and if you have any questions feel free to ask.
edited Jan 4 at 2:37
answered Jan 3 at 17:07
DavidDavid
1,095714
1,095714
This hasn't really said anything more than the comments on the question have, because even though you show proper code for doing this, you do not explain how the code works, or why you are doing what you are doing. Edit: not my DV
– GrumpyCrouton
Jan 3 at 17:22
@GrumpyCrouton - I try to explain the code via comments in the code.
– David
Jan 3 at 21:30
Perhaps, very vaguely. You don't explain why you are setting those specific attributes, or how the placeholders work for the variables, or howtry -> catchworks, or why you have multiple catches. Your code and OP's code is light-years apart. If OP already used these things, that would be one thing, but they don't. This is an example of an answer that was probably copied + pasted into the OP's code, which works, but they haven't actually gained any knowledge about the proper way to do these things. And that, in my opinion, makes this answer "not useful".
– GrumpyCrouton
Jan 3 at 21:36
@GrumpyCrouton - Fair enough, I've elaborated on my answer.
– David
Jan 4 at 2:38
I think you should read their question again; something that I've commented about under their (unclear) question, something nobody caught. Note: Not my downvote.
– Funk Forty Niner
Jan 4 at 2:42
add a comment |
This hasn't really said anything more than the comments on the question have, because even though you show proper code for doing this, you do not explain how the code works, or why you are doing what you are doing. Edit: not my DV
– GrumpyCrouton
Jan 3 at 17:22
@GrumpyCrouton - I try to explain the code via comments in the code.
– David
Jan 3 at 21:30
Perhaps, very vaguely. You don't explain why you are setting those specific attributes, or how the placeholders work for the variables, or howtry -> catchworks, or why you have multiple catches. Your code and OP's code is light-years apart. If OP already used these things, that would be one thing, but they don't. This is an example of an answer that was probably copied + pasted into the OP's code, which works, but they haven't actually gained any knowledge about the proper way to do these things. And that, in my opinion, makes this answer "not useful".
– GrumpyCrouton
Jan 3 at 21:36
@GrumpyCrouton - Fair enough, I've elaborated on my answer.
– David
Jan 4 at 2:38
I think you should read their question again; something that I've commented about under their (unclear) question, something nobody caught. Note: Not my downvote.
– Funk Forty Niner
Jan 4 at 2:42
This hasn't really said anything more than the comments on the question have, because even though you show proper code for doing this, you do not explain how the code works, or why you are doing what you are doing. Edit: not my DV
– GrumpyCrouton
Jan 3 at 17:22
This hasn't really said anything more than the comments on the question have, because even though you show proper code for doing this, you do not explain how the code works, or why you are doing what you are doing. Edit: not my DV
– GrumpyCrouton
Jan 3 at 17:22
@GrumpyCrouton - I try to explain the code via comments in the code.
– David
Jan 3 at 21:30
@GrumpyCrouton - I try to explain the code via comments in the code.
– David
Jan 3 at 21:30
Perhaps, very vaguely. You don't explain why you are setting those specific attributes, or how the placeholders work for the variables, or how
try -> catch works, or why you have multiple catches. Your code and OP's code is light-years apart. If OP already used these things, that would be one thing, but they don't. This is an example of an answer that was probably copied + pasted into the OP's code, which works, but they haven't actually gained any knowledge about the proper way to do these things. And that, in my opinion, makes this answer "not useful".– GrumpyCrouton
Jan 3 at 21:36
Perhaps, very vaguely. You don't explain why you are setting those specific attributes, or how the placeholders work for the variables, or how
try -> catch works, or why you have multiple catches. Your code and OP's code is light-years apart. If OP already used these things, that would be one thing, but they don't. This is an example of an answer that was probably copied + pasted into the OP's code, which works, but they haven't actually gained any knowledge about the proper way to do these things. And that, in my opinion, makes this answer "not useful".– GrumpyCrouton
Jan 3 at 21:36
@GrumpyCrouton - Fair enough, I've elaborated on my answer.
– David
Jan 4 at 2:38
@GrumpyCrouton - Fair enough, I've elaborated on my answer.
– David
Jan 4 at 2:38
I think you should read their question again; something that I've commented about under their (unclear) question, something nobody caught. Note: Not my downvote.
– Funk Forty Niner
Jan 4 at 2:42
I think you should read their question again; something that I've commented about under their (unclear) question, something nobody caught. Note: Not my downvote.
– Funk Forty Niner
Jan 4 at 2:42
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54026587%2finput-values-become-number-automatically-when-insert-to-mysql%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown

4
holy mother of sql injection.
– Chad
Jan 3 at 16:56
2
Kit Harrington: Sql Injection is coming!!!
– Kebab Programmer
Jan 3 at 16:57
1
Use parameterized queries and the problem will vanish (and will also fix the sql injection vulnerability)
– Andreas
Jan 3 at 16:59
1
Since you're not using prepared statements (you really ought to, by the way), try echoing out your insert query to make sure it's inserting what you think it is. Something else might be dropping the beginning 0. Otherwise, I'm going to guess it's because the variables are not quoted, so MySQL is treating the values as a number instead of a string, and dropping the 0. Using prepared statements and parameter binding would solve it.
– aynber
Jan 3 at 17:00
Note that there exists mysqli/PDO wrappers which can handle prerpared statements for you automatically. For example, my class GrumpyPDO, your code would become
$db->run("INSERT INTO table_dtb (SV, DT, DK, NH, ttDK, ngTT) VALUES (?, ?, now(), ?, '1', now())", [$_POST['sv'], $_POST['dt'], $_POST['sv']]);, and it would be safe from SQL injection.– GrumpyCrouton
Jan 3 at 17:03