I have a newsletter for one of my sites and I can't the email posted to the mysql database.
Here is the html form code:
subscribe
<h2>newsletter</h2>
<br /><input type="text" name="email" value="" id="email" />
<input type="button" name="submit" onclick="submit_it()" value="OK" />
<script type="text/javascript" charset="utf-8">
function submit_it() {
var cate_value = $('#cate').val();
var email_value = $('#email').val();
$.post("subscribe.php", { email: email_value , cate: category_value }, function(response) {
if (response!='') {alert(response)};
alert('ok');
});
}
</script>
</body>
And here is the php processing code:
$host = "localhost";
$user = "some_user";
$password = "some_pass";
$database = "news";
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
function sql_quote($value) {
$value = str_replace('<?','',$value);
$value = str_replace('script','',$value);
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value) . "'";
} else {
if ((string)$value[0] == '0') {
$value = "'" . mysql_real_escape_string($value) . "'";
}}
return $value;
}
$q = "INSERT INTO emails (email,cate) VALUES (".sql_quote($_POST['email']).",".$_POST['cate'].")";
mysql_query($q);
?>
Any help would be much appreciated because I've been fooling with this for the last 5hrs trying to make it work and I just can't figure it out plus I can't look at it anymore. My eyes hurt now. lol Thanks again.
You should definitely rewrite your code as hobodave suggests. I think something is wrong with your db configuration, though. Try this in the meantime, to execute your query:
$result = mysql_query($q);
if( $result ){
echo( 'OK' );
} else {
echo( 'Invalid query: ' . mysql_error() );
}
Your PHP sql_quote function is very naive with it's str_replace() filtering. It is trivial to bypass this and insert unwanted data in your database.
I suggest the following rewrite of your code:
<?php
$host = "localhost";
$user = "some_user";
$password = "some_pass";
$database = "newsletter";
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
function sql_quote($value)
{
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
return mysql_real_escape_string($value);
}
$email = $_POST['email'];
$category = $_POST['category'];
if (filter_var($email, FILTER_VALIDATE_EMAIL)
&& FALSE !== filter_var($category, FILTER_VALIDATE_INT)
) {
$q = sprintf("INSERT INTO emails (email, category) VALUES ('%s', '%s')",
sql_quote($email),
sql_quote($category)
);
// execute query
} else {
// Do what you want with invalid data
}
I'd also suggest the following changes:
Disable magic_quotes_runtime so you don't need to check, thus you can do away with sql_quote entirely
Use mysqli
Edit:
Why are you even using AJAX to process this form submission? I don't see any benefit in it. You're not doing anything special, just submitting a form.
I'd suggest removing the AJAX altogether and just using the submit button as it's intended.
If you insist though, you can at least temporarily remove it to simplify your testing.
You have a syntax error in your query try this
$email = sql_quote($_POST['email']);
$category = $_POST['category'];
$q = "INSERT INTO emails (email,category) VALUES ('$email','$category')";
You have to use data as key for your data.
$.ajax(url: "ajax_subscribe.php",
method : 'POST',
data: { email: email_value , category: category_value },
success: function(response) {
if (response!='') {alert(response)};
alert('Thank You !');
});
Related
I have this problem where if I leave my input for 'Title' blank, then it won't set the default value: "Untitled" when sent to the database. I've looked online and have made sure that my settings were correct in phpmyadmin but it still won't set the default value. Any piece of advice is appreciated!
Here are my PHPmyadmin settings for the "Title" column:
These are my files:
addart.php
<form method="post" action="addtodb.php">
<label for="Title">
<h4>Title</h4>
</label>
<input class="u-full-width"
type="text"
placeholder="Title of art"
id="Title"
name="Title">
</form>
addtodb.php
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'testdb';
$dbConnection = new mysqli($host, $user, $pass, $db);
if (mysqli_connect_errno()) {
printf("Could not connect to the mySQL database: %s\n", mysqli_connect_error());
exit();
}
if($_POST) {
$artwork = $_POST["Artwork"];
$medium = $_POST["Medium"];
$artist = $_POST["Artist"];
$title = $_POST["Title"];
$results = $dbConnection->query("INSERT INTO art
(Artwork, Title, Artist, Medium) VALUES
('$artwork','$title','$artist','$medium');");
if (!$results) {
echo 'Unable to insert into database.';
exit();
} else {
echo 'Successfully added!';
}
mysqli_close($dbConnection);
header("Location: galleryonly.php"); /* Redirect browser */
exit();
}
?>
$artwork = $_POST["Artwork"];
$medium = $_POST["Medium"];
$artist = $_POST["Artist"];
$title = $_POST["Title"];
if(!empty($title)) {
$sql = "INSERT INTO art (Artwork, Title, Artist, Medium) VALUES ('$artwork', '$title', '$artist', '$medium')";
} else {
$sql = "INSERT INTO art (Artwork, Artist, Medium) VALUES ('$artwork', '$artist', '$medium')";
}
$results = $dbConnection->query($sql);
You can try out this code.
If you're omitting the column, the default value will be set.
Because you have only one column with default value, you can stick with this code.
If you have more than one column with default value, you will need to make changes according to your requirements.
You have a bit of trick ahead of you, because you won't be able to use the Title column if you need the Default value.
// assuming use of proper method of sanitizing
// these values so we don't get SQL INJECTED!!
$artwork = 'artwork';
$title = 'title';
$artist = 'artist';
$medium = 'medium';
// make an array with the columns
$cols = explode(',', 'Artwork,Title,Artist,Medium');
// make an array with the values (that you sanitized properly!)
$vars = explode(',', 'artwork,title,artist,medium');
foreach ($cols as $i=>&$col) {
$var = ${$vars[$i]};
if ($col == 'Title') {
if (empty($var)) {
// don't add this column if empty
continue;
}
}
// otherwise (if not Title)
// add it to a column = "value" insert string
$pcs[] = "`$col` = '$var'";
}
// fortunately, we can insert with update syntax, too!
$query = 'insert into art set ';
$query .= implode(', ', $pcs);
use always small letters in
<input class="u-full-width"
type="text"
placeholder="Title of art"
id="Title"
name="title">
<script>
function testinput(value) {
value = trim(value);
value = stripslashes(value);
value = htmlspecialchars(value);
}
</script>
<?php
$servername ="localhost";
$username = "k";
$password = "password";
$dbname = "password";
$connect1 = new mysqli($servername, $username, $password, $dbname);
if($connect1->connect_error) {
die("Connection failed: " . $connnect1->connect_error);
}
if (isset($_POST['btnreg'])) {
$klantVoornaam = $_POST["txtVoornaam"];
$klantAchternaam = $_POST["txtAchternaam"];
$klantMail = $_POST["txtEmail"];
$klantWachtwoord = $_POST["txtWw"];
(line48)$klantVoornaam = testinput($klantVoornaam);
$klantAchternaam = testinput($klantAchternaam);
$klantMail = testinput($klantMail);
$klantWachtwoord = testinput($klantWachtwoord);
$sql = "INSERT INTO `klanten` (KlantID, Voornaam, Achternaam, Wachtwoord, Email, Klantreg, KlantActief)
VALUES(NULL,'".$klantVoornaam."','".$klantAchternaam."', '".md5($klantWachtwoord)."','".$klantMail."',". regCode() ."','0')";
$qresult = mysql_query($sql);
if($connect1 ->query($qresult)){
echo "Registered successfully!";
echo "Voornaam: " . $klantVoornaam;
echo "Achternaam" . $klantAchternaam;
echo "E-mail" . $klantMail;
echo "Wachtwoord" . $klantWachtwoord;
}
}
?>
Basically says the function testinput() I made above is undefined but I doesn't seem to see the mistake in that.
The script is set in my body as is the rest, using testinput() to strip of any strange characters since it's a username.
You're defining testinput in javascript, you can't call it from PHP. Instead, you should define it in PHP:
<?php
function testinput($value) {
$value = trim($value);
$value = stripslashes($value);
$value = htmlspecialchars($value);
return $value;
}
// Rest of your PHP code
BTW: This function doesn't really test your input, it sanitizes it. You should probably give it a different name to better describe what it does.
Thx alot! Stupid mistake by me, the teacher told me to use these trim/strips so I thought I'd stick with it
I am trying to update my database using ajax, but I cannot seem to understand why the php code does not update the database. The script:
function Insert () {
if (XMLHttpRequestObject) {
XMLHttpRequestObject.open("POST","list_insert.php");
XMLHttpRequestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
var returnedData = XMLHttpRequestObject.responseText;
var messageDiv = document.getElementById('messageDiv');
messageDiv.innerHTML = returnedData;
}
}
var item = document.getElementById('items').value;
var desc = document.getElementById('description').value;
var data = item + '|' + desc + '|';
XMLHttpRequestObject.send("data=" + data);
}
return false;
}
This is the php code for list_insert:
<?php
include "function_list.php";
$myData = $_POST['data'];
$datetime = date('Y-m-d H:i:s');
list($items,$description) = explode ('|',$myData);
$statement = "INSERT INTO record ";
$statement .= "(items,description) ";
$statement .= "VALUES (";
$statement .= "'".$items."', '".$description."')";
print $statement;
insert($statement);
print "done";
?>
My php function to insert into the db (function_list):
<?php
$con=mysqli_connect("localhost","shop");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
function insert($statement) {
global $con;
mysqli_query($con,$statement);
}
?>
When I print the statement out, the query is correct (I have verified this by manually copy pasting it in mysql). I think the issue is with my insert function.
Any help is appreciated,
thank you.
Firstly, all mysql statements must end in a semicolon.
Secondly, have you made sure $items and $description are the values you expect them to have? Do they have any unescaped quotes?
Also, typically you would send each of the fields as a separate value like so:
var item = document.getElementById('items').value;
var desc = document.getElementById('description').value;
XMLHttpRequestObject.send("items=" + item + "&desc=" + desc);
$$items = $_POST['items'];
$description = $_POST['desc'];
By default, the username for mysql is root, and the password is blank, even though you aren't prompted for these, they are set by default.
I think this might be the issue
in ur global variable $con letz say you put this
$con = new mysqli("host", "user", "pwd", "dbname");
then
function insert($statement) {
$con->query($statement);
$con->close();
}
I'm trying to process a large form and hit a bit of a stumbling block. I've tried google for the answer, but I'm not quite sure I'm wording what I need right. My code looks like this.
<?PHP
$exchange = $_POST['exchange'];
$estimate = $_POST['estimate'];
$wp = $_POST['wp'];
$label1 = $_POST['name3'];
$result1 = $_POST['fb1'];
$result2 = $_POST['fb2'];
$username = "-----";
$password = "-----";
$hostname = "-----";
$con = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
$selected = mysql_select_db("-----", $con) or die("Could not select examples");
$query = "UPDATE btsec SET Status='$result1', TM='result2' WHERE Exchange='$exchange' AND Estimate='$estimate' AND WP='$label1' AND SectionID='$label1'";
if (!mysql_query($query,$con))
{
die('Error: ' . mysql_error($con));
}
}
echo "Sections updated for WP's $wp on $estimate on the $exchange Exchange!";
mysql_close($con);
?>
What I need to do is loop through the query, but each time change the contents of the variable.
$label1 = $_POST['name3']; needs to become $label1 = $_POST['name6'];
$result1 = $_POST['fb1']; needs to become $result1 = $_POST['fb10'];
$result1 = $_POST['fb2']; needs to become $result1 = $_POST['fb11'];
As I say google isn't able to compensate for my bad wording.
The best solution would be to change the form inputs so that they work as arrays:
<input type="text" name="name[3]">
<input type="text" name="name[6]">
<input type="text" name="name[9]">
<input type="text" name="fb[1]">
<input type="text" name="fb[10]">
<input type="text" name="fb[19]">
Then when you submit the form you can iterate over the data:
foreach ($_POST['name'] as $index => $name)
{
}
foreach ($_POST['fb'] as $index => $fb)
{
}
As a side note, you also should look into using prepared statements, or at the very least escaping the data -- you're at risk of SQL injection.
I am trying create an email subscription input box using JQuery, but for some reason, the inputted email addresses are not inserting into the MySql database, can anyone help me?
Here is the code I have in my newsletter.js file:
jQuery(function($){
var validateRegexps = {
email: /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/,
"default": /.{4}/
}
if ($("#newsletter form").length == 0) return
var defaultMessage = $("#newsletter").attr("data-default")
var subscribedMessage = $("#newsletter").attr("data-subscribed")
var newsletterForm = $("#newsletter form")
/* newsletter code */
function newsletter(send) {
var subscribe = true
newsletterForm.find('input[type="submit"]').val(subscribe ? "Sign Up" : "Unsubscribe")
var email = newsletterForm.find('input[name="email"]')
var check = true
if (email.val() == defaultMessage || email.val() == subscribedMessage) {
email.val("")
if (!send) check = false
}
if (check) {
if(validateRegexps["email"].test(email.val())) {
// valid mail
email.removeClass("error")
if (send) {
$.post("php/newsletter.php",{add: email.val()}, function(data) {
email.val(subscribedMessage)
});
email.val("sending")
}
} else {
// invalid mail
email.addClass("error")
}
}
return false
}
function restore(e) {
var jqEl = $(e.currentTarget)
if (jqEl.val() == "") {
jqEl.val(defaultMessage)
}
return true
}
function signUp() {
return newsletter(false)
}
function signUpAndSend() {
return newsletter(true)
}
newsletterForm.find('input[name="email"]').focus(signUp).focusout(restore)
newsletterForm.change(signUp)
newsletterForm.submit(signUpAndSend)
});
Here is the code in my newsletter.php file:
require("config.php");
$db = mysql_connect($dbhost, $dbuser, $dbpassword);
mysql_select_db($dbdatabase, $db);
$subsql = "INSERT INTO subscribe(email) VALUES(".$_POST['add'].");";
mysql_query($subsql);
And here is the code in my other php page to display the input box:
<div id="newsletter" data-default="youremail#yourdomain.com" data-subscribed="Thank you for subscribing.">
<form action="#" method="POST">
<input type="text" name="email" value="youremail#yourdomain.com" />
<input type="submit" value="submit" />
</form>
<h2>Sign Up to Our Newsletter!</h2>
</div>
Any help is greatly appreciated. Thank you very much in advance!!!
Hmm! Looking at your code does not directly point to any errors but the most obvious issue seems to be in the INSERT query that the email address isn't enclosed in single-quotes. Please draft your query like:
$subsql = "INSERT INTO subscribe(email) VALUES('" . $_POST['add'] . "');";
Hopefully the above INSERT should work fine. If the issue still exists though, try finding out if the query might be generating any errors:
$subsql = "INSERT INTO subscribe(email) VALUES('" . $_POST['add'] . "');";
mysql_query($subsql);
if (mysql_error()) {
echo mysql_error();
}
If no errors are found and the issue still exists, it might make sense to look into other basics, like:
Is $_POST['add'] available in "newsletter.php"?
Is MySQL connection correctly established in "newsletter.php"?
Is there any JavaScript issue that the POST request isn't send at all or perhaps send with an empty email address?
Hope this helps!