php with mysql, the code is not inserting into my table - php

Big edit:
New script:
<?php
error_reporting(E_ALL|E_NOTICE);
$nazwabazydanych = "projekt";
$pesel = mysql_real_escape_string($_POST['pesel']);
$imie = mysql_real_escape_string($_POST['imie']);
$nazwisko = mysql_real_escape_string($_POST['nazwisko']);
$telefon = mysql_real_escape_string($_POST['telefon']);
$adres = mysql_real_escape_string($_POST['adres']);
$nr_konta = mysql_real_escape_string($_POST['nr_konta']);
$zarobek = mysql_real_escape_string($_POST['zarobek']);
if (!$pesel || !$imie || !$nazwisko || !$telefon || !$adres || !$nr_konta || !$zarobek)
{
print "Nie zostały wypełnione wszystkie pola";
exit;
}
$db = mysql_pconnect("localhost", "root", "");
if (!$db)
{
print "Nie można nawiązać połączenia z bazą danych";
exit;
}
mysql_select_db("$nazwabazydanych");
$query = mysql_query("CALL dodaj_osobe ('$pesel','$imie','$nazwisko','$telefon','$adres','$nr_konta','$zarobek')");
?>
Action:
<form action="lool.php" method="post">
PESEL: <input type="text" name="pesel" maxlength=11 size=12><br><br>
Imię: <input type="text" name="imie" maxlength=45 size=46><br><br>
Nazwisko: <input type="text" name="nazwisko" maxlength=45 size=46><br><br>
Telefon: <input type="text" name="telefon" maxlength=9 size=10><br><br>
Adres: <input type="text" name="adres" maxlength=45 size=46><br><br>
Numer konta: <input type="text" name="nr_konta" maxlength=20 size=21><br><br>
Zarobek: <input type="text" name="zarobek" maxlength=8 size=9><br><br>
<input type="submit" value="Dodaj klienta">
</form>
And the updated error:
NONE!
Thanks guys, but I got a question:
How can I send an error if for example "nr_konta" or "pesel" or "telefon" are too low digits?

Use print_r($_POST) you should see if you get values. In your code the problem seems to be that you are not using the correct indexes. Note Pesel doesn't have a notice but imie does.
Your code for the two:
$pesel = mysql_real_escape_string($_POST['pesel']);
$imie = mysql_real_escape_string($_POST['$imie']);
Note you have '$imie' as the index. I'm guessing copy and paste error here. From the html it seems the element is named imie.
Try this:
$imie = mysql_real_escape_string($_POST['imie']);

You need to get POST variables using the $_POST array, unless you have register_globals on.
$pesel = mysql_real_escape_string($_POST['pesel']);
$imie = mysql_real_escape_string($_POST['imie']);
$nazwisko = mysql_real_escape_string($_POST['nazwisko']);
$telefon = mysql_real_escape_string($_POST['telefon']);
$adres = mysql_real_escape_string($_POST['adres']);
$nr_konta = mysql_real_escape_string($_POST['nr_konta']);
$zarobek = mysql_real_escape_string($_POST['zarobek']);
// Put this after so you don't have to restate the $_POST vars
if (!$pesel || !$imie || !$nazwisko || !$telefon || !$adres || !$nr_konta || !$zarobek)
{
print "Nie zostały wypełnione wszystkie pola";
exit;
}

You're not actually getting the $_POST values.
Should be
$pesel = mysql_real_escape_string($_POST['pesel']);
$imie = mysql_real_escape_string($_POST['imie']);
$nazwisko = mysql_real_escape_string($_POST['nazwisko']);
$telefon = mysql_real_escape_string($_POST['telefon']);
$adres = mysql_real_escape_string($_POST['adres']);
$nr_konta = mysql_real_escape_string($_POST['nr_konta']);
$zarobek = mysql_real_escape_string($_POST['zarobek']);
And those should go before your
if (!$pesel || !$imie || !$nazwisko || !$telefon || !$adres || !$nr_konta || !$zarobek)
Also, you need to remove the $ from your $_POST values.
$_POST['$imie']
Should be:
$_POST['imie']

Related

Form inserting empty data to database

Whenever I submit the form with empty input, it sends the empty input to my database. The form was working fine until after I used the htmlentities() for its functionality.
I used the gettype() function to return what's in the inserted variable and it returns "string", but when I checked the code from the browser, I could not see anything in the table.
This is the code snippet and the form processing code
<?php
$errors = [];
$missing = [];
if(isset($_POST['sendFirm']) ){
$expected = array('firmName','country','state','email','phoneNumber');
$required = array('firmName','country','state','phoneNumber');
<?php
foreach ($_POST as $key => $value) {
if(is_array($value)){
$value = $value;
}else{
$value = trim($value);
}
if(empty($value) && in_array($key, $required)){
$missing[] = $key;
$$key = '';
}elseif(in_array($key, $expected)){
$$key = "$value";
}
}
?>
}
?>
<?php
if($errors || $missing){
?>
<p>Please fix the following items</p>
<?php } ?>
<form method="post" action="<?php $_SERVER['PHP_SELF'] ?>">
<div class="form-group">
<label>Compnay Name
<?php if($missing && in_array('firmName', $missing)) { ?>
<span class="text-danger">Please enter firm name</span>
<?php } ?>
</label>
<input class="form-control" type="text" name="firmName" id="firmName" placeholder="Company Name"
<?php
if($errors || $missing){
print 'value="' . htmlentities($firmName) . '"';
}
>
<button class="btn btn-primary" type="submit"
name="sendFirm">Submit</button>
</form>
?>
>
<?php
if(isset($_POST['sendFirm'])){
try {
$connectToFirms = new
PDO('mysql:host=localhost;dbname=firms','root','2332');
$connectToFirms->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$prepInsertion = $connectToFirms->prepare('INSERT INTO contractors
VALUES (null,?,?,?,?,?)');
$prepInsertion->execute(array($firmName, $country, $state, $email,
$phoneNumber));
}catch (PDOException $e) {
print "An error occure: " . $e->getMessage();
}
}
?>
The form is expected to insert inputs into the database only if the input is not empty and is also in the $expected[];
Don't insert data
I would stop the whole data insertion, if the expected input is not given. I would also send the input data one by one to PHP, so you have a better overview over your code. Good overview = less errors ;)
Try it this way:
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$firmname = htmlentities($_POST["firmName"], ENT_QUOTES);
$country = htmlentities($_POST["country"], ENT_QUOTES);
$state = htmlentities($_POST["state"], ENT_QUOTES);
$pn = htmlentities($_POST["phoneNumber"], ENT_QUOTES);
// LET'S START THE VALIDATION
// if the required fields are not empty, insert data
if (!empty($firmname) && !empty($country) && !empty(state) && !empty($pn)) {
// insert data
} else { // else stop insertion and return error message
// return error message
}
} else {
// redirect...
}
I hope, i understood your question correctly and could help.

Regex for checking price format

I have this long validation going on with my form, everything seems to be getting checked except for the validation on the price to ensure it's the correct format which is basically a series of numbers followed by a decimal point and 2 more numbers i.e. 12.00 or 112.00 or 124.53, etc.
Here's my code which also checks to see if field is set and isn't empty as well as if the product name already exists.
<?php
if(isset($_POST['submit']) && isset($_POST['product-name']) && !empty($_POST['product-name']) && isset($_POST['description']) && !empty(trim($_POST['description'])) && isset($_POST['price']) && !empty($_POST['price']) && isset($_POST['category']) && !empty($_POST['category']) && isset($_POST['spice']) && !empty($_POST['category']) && isset($_POST['date-added']) && !empty($_POST['date-added'])){
$product_name = trim($_POST['product-name']);
$description = trim($_POST['description']);
$price = $_POST['price'];
$category = $_POST['category'];
$spice = $_POST['spice'];
$date_added = $_POST['date-added'];
$pattern = '/^\d+(?:\.\d{2})?$/';
$pattern1 = '/^([1-9][0-9]*|0)(\.[0-9]{2})?$/';
if(preg_match($pattern, $price)){
$error = "<script language='javascript'>
window.onload = function(){
var divs = document.getElementById('error');
divs.innerHTML = '<p style = \"color:#FF0000\">Price is in the wrong format, correct format e.g. 10.00</p>';
}
</script>";
}
if(!isset($error)){
$rows = getProductName($product_name);
if($rows > 0){
echo "<script language='javascript'>
window.onload = function(){
var divs = document.getElementById('error');
divs.innerHTML = '<p style = \"color:#FF0000\">Product name already exists!</p>';
}
</script>";
} else{
insertProduct($product_name, $description, $price, $category, $spice, $date_added) ;
echo "<script language='javascript'>
window.onload = function(){
var divs = document.getElementById('error');
divs.innerHTML = '<p style = \"color:#FF0000\">Record Inserted Successfully!</p>';
}
</script>";
}
} else{
echo $error;
}
} else{ echo "<script language='javascript'>
window.onload = function(){
var divs = document.getElementById('error');
divs.innerHTML = '<p style = \"color:#FF0000\">Please fill out all required (*) fields!</p>';
}
</script>";
}
?>
It's most likely something simple but I can't seem to see where the issue is.
Update:
The form is too long but this is a condensed version containing the field: †
<form method="post" action="addProduct.php">
<ul class="form-style-1">
<div id="error"></div>
<h2>Add Product</h2>
<li> <label>Price: <span class="required">*</span></label> <input type="text" name="price" class="field-long" placeholder="Enter Price" /> </li>
</form>
†
†Added per comment on answer by Hydra at 2017-03-10 03:06:52Z
I think you forgot !exclamation mark since you want to make sure if your value doesn't match a specific pattern:
if(!preg_match($pattern, $price))
you could also use is_float() function that returns true if the value is float otherwise it will return false

Cannot get simple PHP function to execute

I've written the function as such and now it returns "You are running a comprehensive ad campaign" even if I select no boxes or just one or two. I'm assuming the problem is in the if statement, do I need to run isset twice?
function adMix () {
$tv = (isset($_POST['TV']));
$radio = (isset($_POST['Radio']));
$search = (isset($_POST['Search']));
$mobile = (isset($_POST['Mobile']));
$mail = (isset($_POST['Mail']));
if ($tv || $radio || $search || $mobile || $mail) {
echo "You are running a comprehensive ad campaign.";
} else {
echo "You can do more to market your dealership.";
}
}
function adMix () {
if (isset($_POST['Tv']) || isset($_POST['Radio']) || isset($_POST['Search']) || isset($_POST['Mobile']) || isset($_POST['Mail'])) {
$tv = isset($_POST['Tv'])?$_POST['Tv']:""; //You can access the index only if it's set, else you will be shown a notice
$radio = isset($_POST['Radio'])?$_POST['Radio']:"";
$search = isset($_POST['Search'])?$_POST['Search']:"";
$mobile = isset($_POST['Mobile'])?$_POST['Mobile']:"";
$mail = isset($_POST['Mail'])?$_POST['Mail']:"";
echo "You are running a comprehensive ad campaign.";
} else {
echo "You can do more to market your dealership.";
}
}
Try making the checkboxes behave as an array, renaming them all to mktg[], per example:
<p>Marketing Mix:</p>
<input type="checkbox" name="mktg[]" value="TV">TV<br>
<input type="checkbox" name="mktg[]" value="Radio">Radio<br>
<input type="checkbox" name="mktg[]" value="Search">Search<br>
<input type="checkbox" name="mktg[]" value="Mobile">Mobile<br>
<input type="checkbox" name="mktg[]" value="Mail">Direct Mail<br>
<br>
And the function:
function adMix(){
if($_POST){
if(!empty($_POST['mktg'])){
if(count($_POST['mktg'])) echo "You are running a comprehensive ad campaign.";
}else echo "You can do more to market your dealership.";
}
}
This way, if(count($_POST['mktg'])) verifies if any option was checked and returns true. If you need to define how many options must be selected to the campaing be true, let's say 3, just do this:
if(count($_POST['mktg']) >= 3)
try with this:
function adMix () {
#$tv = $_POST['TV'];
#$radio = $_POST['Radio'];
#$search = $_POST['Search'];
#$mobile = $_POST['Mobile'];
#$mail = $_POST['Mail'];
if (isset($tv) || isset($radio) || isset($search) || isset($mobile) || isset($mail)) {
echo "You are running a comprehensive ad campaign.";
} else {
echo "You can do more to market your dealership.";
}
}

dom cant use variables to store data in xml

I got an error when trying to post user input data from html to php and saved into xml file. It gives me this error Catchable fatal error: Argument 1 passed to DOMNode::appendChild() must be an instance of DOMNode, null given. Here is the code
register.htm
<!DOCTYPE html>
<html lang="en">
<head>
<title>test</title>
</head>
<body>
<form id="regform" method="post" action="register.php">
<fieldset id="person">
<legend>Your details:</legend>
<p><label for="fname">First Name:</label><input type="text" name="fname"/></p>
<p><label for="lname">Last Name:</label><input type="text" name="lname"/></p>
<p><label for="password">Password:</label><input type="password" name="password"/></p>
<p><label for="cpassword">Confirm Password:</label><input type="password" name="cpassword"/></p>
<p><label for="email">Email:</label><input type="email" id="email" name="email"/></p>
<p><label for="phone">Phone:</label><input type="text" name="phone"/></p>
<input type="submit" value="Register"/>
</fieldset>
</form>
</body>
</html>
relevant parts of register.php (whole code is too long)
$fname = #trim($_POST["fname"]);
$lname = #trim($_POST["lname"]);
$password = #trim($_POST["password"]);
$cpassword = #trim($_POST["cpassword"]);
$phone = #trim($_POST["phone"]);
$email = #trim($_POST["email"]);
if(file_exists('../../customer.xml'))
{
$xml2 = file_get_contents('../../data/customer.xml');
}
if(!file_exists('../../customer.xml'))
{
$dir = "../../data";
$f = fopen("$dir/customer.xml", "w");
$doc = new DOMDocument('1.0');
$doc->formatOutput = true;
$root = $doc->createElement('customer');
$doc->appendChild($root);
$user = $doc->createElement('user');
$root->appendChild($user);
$fname = $doc->createElement('fname');
#override - if I change this to 'brian' then it works, doesnt work with $variable
$fnameValue = $doc->createTextNode($fname);
$fname->appendChild($fnameValue);
$user->appendChild($fname);
$lname = $doc->createElement('lname');
$lnameValue = $doc->createTextNode($lname);
$lname->appendChild($lnameValue);
$user->appendChild($lname);
echo $doc->save('../../data/customer.xml');
//$doc->load('customer.xml');
echo ' Registration Successful!';
}
Just like the error suggests, appendChild needs a DOMNode. Just create that element, then use the second paramter from the user input. Example:
$fname = #trim($_POST["fname"]);
$lname = #trim($_POST["lname"]);
$password = #trim($_POST["password"]);
$cpassword = #trim($_POST["cpassword"]);
$phone = #trim($_POST["phone"]);
$email = #trim($_POST["email"]);
if(file_exists('../../customer.xml')) {
$xml2 = file_get_contents('../../data/customer.xml');
}
if(!file_exists('../../customer.xml')) {
$dir = "../../data";
$f = fopen("$dir/customer.xml", "w");
$doc = new DOMDocument('1.0');
$doc->formatOutput = true;
$root = $doc->createElement('customer');
$doc->appendChild($root);
$user = $doc->createElement('user');
$root->appendChild($user);
$fname_node = $doc->createElement('fname', $fname);
$user->appendChild($fname_node);
$lname_node = $doc->createElement('lname', $lname);
$user->appendChild($lname_node);
echo $doc->save('../../data/customer.xml');
//$doc->load('customer.xml');
echo ' Registration Successful!';
}
You are re-using the $fname variable. That's why you get the error. It's a simple, typographical mistake. One thing you can do is to prefix the input variables with input, e.g. $input_fname so it's clear that you obtain them from there. Or even create a stdclass like $input = new stdClass; and then assign the $_POST variables to it: $input->fname = #trim($_POST["fname"]); - that way it's clear what it stands for and you can pass the input around more easily, too.
Example:
$input = new stdClass;
$input->fname = #trim($_POST["fname"]);
$input->lname = #trim($_POST["lname"]);
$input->password = #trim($_POST["password"]);
$input->cpassword = #trim($_POST["cpassword"]);
$input->phone = #trim($_POST["phone"]);
$input->email = #trim($_POST["email"]);
$doc = new DOMDocument('1.0');
$doc->formatOutput = true;
$root = $doc->createElement('customer');
$root = $doc->appendChild($root);
foreach ($input as $key => $value) {
$element = $doc->createElement($key, $value);
$root->appendChild($element);
}
$doc->save('php://output');
Exemplary output:
<?xml version="1.0"?>
<customer>
<fname>Waltraud</fname>
<lname>Van Hömpenstetten</lname>
<password></password>
<cpassword></cpassword>
<phone></phone>
<email></email>
</customer>
Online Demo: https://eval.in/private/29c08d9fafec22

Search engine issue

I need your help. When user enter plural word or adjective to find singular word in my native language: czech. For example: when user enters motorový, it should return motor (now return motorov) without ový, same when i enter motorce (return motorc). It seems like 2letter and 3letter check doesn't work for me, 1letter check works. U can try my code on webiste . Thank you for you effort, time and good advices.
My Code:
<!DOCTYPE html>
<html lang="cs">
<meta charset="utf-8" />
<head>
<title>Vyhledavac</title>
</head>
<body>
<form method="get" action="index.php">
<input type="text" name="s_word" value="<?php $_GET['s_word'] ?>" /> <input type="submit" value="Hledat" />
</form>
<hr />
<?php
if(isset($_GET['s_word'])){
$s = $_GET['s_word'];
$s_word = $s;
$l_word = substr($s_word,-3);
if($l_word == "ovi" or $l_word == "ovy" or $_l_word == "ový" ){
$s_word = rtrim($s_word,$l_word);
}
$l_word = substr($s_word,-2);
if($l_word == "ce" or $l_word == "ku" or $l_word == "em"){
$s_word = rtrim($s_word,$l_word);
}
$l_word = substr($s_word,-1);
if($l_word == 'y' or $l_word == 'i' or $l_word == 'u' or $l_word == 'e' or $l_word == 'ů' or $l_word == 'ý'){
$s_word = rtrim($s_word,$l_word);
}
$query = "SELECT * FROM search_test WHERE title LIKE '%$s_word%' OR message LIKE '%$s_word%'";
echo "$query";
mysql_connect("localhost","user","passwd") or die('spatne pripojeni');
mysql_select_db("search") or die('nelze najit databazi');
mysql_query("SET NAMES 'utf8'");
mysql_query("SET CHARACTER SET utf8");
mysql_query("SET COLLATION_CONNECTION = 'utf8_general_ci'");
$query = mysql_query($query) or die('spatny dotaz');
$numrows = mysql_num_rows($query);
if($numrows > 0){
while($row = mysql_fetch_assoc($query)){
$id = $row['id'];
$title = $row['title'];
$message = $row['message'];
$website = $row['website'];
echo "<h2><a href='$website'>$title</a></h2><br /><p>$message</p>";
}
}else{
echo "Žádné výsledky pro dotaz: ".$s_word."<br />";
}
}
?>
</body>
</html>
Shouldn't this:
$l_word = $s_word[strlen($s_word)-3];
Be something like:
$l_word = substr($s_word,-3);
The way you currently have it, it will only give you 1 character into $l_word and not the amount you think you're subtracting. Which means $l_word == "ovi" will never match.
For example:
<?php
$s_word = 'motorce';
$l_word = $s_word[strlen($s_word)-3];
echo $l_word;
Will return:
r
Live DEMO and what you actually want is:
<?php
$s_word = 'motorce';
$l_word = substr($s_word,-3);
echo $l_word;
Which returns:
rce
Live DEMO.
It gives you only one character:
$l_word = $s_word[strlen($s_word)-3];
Try with substr().
$l_word = substr($s_word, -3);
Not a fully working solution but the road i would have taken (assuming a UTF-8 encoded file):
$word = $_GET["s_word"];
$removelist = array("ový","ce");
foreach($removelist as $entry) {
if ((pos = mb_stripos($word,$entry)) !== FALSE) {
$word = mb_substr($word,$pos);
break;
}
}
Now $word should be trimmed and ready for searching, otherwise you should add more to the list.

Categories