insert error to database from a for loop - php

I tried inserting some license generated kes from a for loop into the database but I was getting Errormessage: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'keys)values('46F2-SH73-2QDD-Z4VH-HV')' at line 1
I have been on it for sometime now trying to fiure it but it gives the same error everytime I run it.
Here is my code:
<?php
//ob_start();
//session_start();
//error_reporting(0);
//ini_set('display_errors', '0');
date_default_timezone_set('Africa/Lagos');
#$db = parse_ini_file("../config/db.ini");
$dbhost = 'localhost'; //$db['host'];
$dbuser = 'root';//$db['user'];
$dbpass = '';//$db['pass'];
$dbname = 'infonetsch_mgmt';//$db['dbname'];
//Connect
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno()) {
printf("MySQLi connection failed: ", mysqli_connect_error());
exit();
}
// Change character set to utf8
if (!$mysqli->set_charset('utf8')) {
printf('Error loading character set utf8: %s\n', $mysqli->error);
}
?>
<html>
<head>
<title>License Key Generator</title>
</head>
<body style="background-color:#F0F0F0">
<h1>License Key generation</h1>
<form method="POST" action="">
<table>
<tr>
<td>Keys to generate</td>
<td><select name="numkeys">
<option value="1">1</option>
<option value="5" selected>5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
<option value="100">100</option>
<option value="500">500</option>
<option value="1000">1000</option>
<option value="5000">5000</option>
<option value="10000">10000</option>
<option value="20000">20000</option>
<option value="50000">50000</option>
</select></td>
</tr>
<tr>
<td>Length of Key</td>
<td><select name="keylen">
<option value="8">8</option>
<option value="10">10</option>
<option value="12">12</option>
<option value="14">14</option>
<option value="16">16</option>
<option value="18">18</option>
<option value="20">20</option>
</select></td>
</tr>
</table>
<input name="validate" type="submit" value="Generate!"/>
</table>
</form>
<?php
if(isset($_POST['validate'])){
$name= 'a';//$_POST['client'];
$software= 'sis';//$_POST['software'];
$numkeys=$_POST['numkeys']; if($numkeys<1)$numkeys=1; if($numkeys>50000)$numkeys=50000;
$keylen=$_POST['keylen'];if($keylen<1)$keylen=1; if($keylen>20)$keylen=20;
include("license_key.class.php");
$pass=new license_key();
echo "<h3>Generating $numkeys Random License Keys </h3>
KeyLenght: $keylen</a><hr/>";
for($i=0;$i<$numkeys;$i++){
$pass->keylen=$keylen;
$key= $pass->codeGenerate($name.$software);
$get = mysqli_query($mysqli, "insert into license_keys(keys)values('".$key."')");//Insert query
$j=$i+1;
echo "$j- $key <br/>";
}
if($get){
echo "Done";
}else{ printf("Errormessage: %s\n", $mysqli->error);; }
echo "<br/><br/>Generate again<br/><br/>";
}
?>
</body>
</html>
Why am I getting such an error?

There could be some special charaters in your license keys. Try using prepare statement with reference from https://www.w3schools.com/php/php_mysql_prepared_statements.asp as
$stmt = $mysqli->prepare("insert into license_keys (`keys`) values(?)");
$stmt->bind_param("s", $key);
$stmt->execute();

run that code and check your keys field varchar limit
<?php
//ob_start();
//session_start();
//error_reporting(0);
//ini_set('display_errors', '0');
date_default_timezone_set('Africa/Lagos');
#$db = parse_ini_file("../config/db.ini");
$dbhost = 'localhost'; //$db['host'];
$dbuser = 'root';//$db['user'];
$dbpass = '';//$db['pass'];
$dbname = 'infonetsch_mgmt';//$db['dbname'];
//Connect
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno()) {
printf("MySQLi connection failed: ", mysqli_connect_error());
exit();
}
// Change character set to utf8
if (!$mysqli->set_charset('utf8')) {
printf('Error loading character set utf8: %s\n', $mysqli->error);
}
?>
<html>
<head>
<title>License Key Generator</title>
</head>
<body style="background-color:#F0F0F0">
<h1>License Key generation</h1>
<form method="POST" action="">
<table>
<tr>
<td>Keys to generate</td>
<td><select name="numkeys">
<option value="1">1</option>
<option value="5" selected>5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
<option value="100">100</option>
<option value="500">500</option>
<option value="1000">1000</option>
<option value="5000">5000</option>
<option value="10000">10000</option>
<option value="20000">20000</option>
<option value="50000">50000</option>
</select></td>
</tr>
<tr>
<td>Length of Key</td>
<td><select name="keylen">
<option value="8">8</option>
<option value="10">10</option>
<option value="12">12</option>
<option value="14">14</option>
<option value="16">16</option>
<option value="18">18</option>
<option value="20">20</option>
</select></td>
</tr>
</table>
<input name="validate" type="submit" value="Generate!"/>
</table>
</form>
<?php
if(isset($_POST['validate'])){
$name= 'a';//$_POST['client'];
$software= 'sis';//$_POST['software'];
$numkeys=$_POST['numkeys']; if($numkeys<1)$numkeys=1; if($numkeys>50000)$numkeys=50000;
$keylen=$_POST['keylen'];if($keylen<1)$keylen=1; if($keylen>20)$keylen=20;
include("license_key.class.php");
$pass=new license_key();
echo "<h3>Generating $numkeys Random License Keys </h3>
KeyLenght: $keylen</a><hr/>";
for($i=0;$i<$numkeys;$i++){
$pass->keylen=$keylen;
$key= $pass->codeGenerate($name.$software);
$get = mysqli_query($mysqli, "INSERT INTO license_keys (keys) VALUES('".$key."')");//Insert query
$j=$i+1;
echo "$j- $key <br/>";
}
if($get){
echo "Done";
}else{ printf("Errormessage: %s\n", $mysqli->error);; }
echo "<br/><br/>Generate again<br/><br/>";
}
?>
</body>
</html>

Please read the SQL error correctly.
MySQL is throwing an SQL syntax error, so your insert query has incorrect syntax.
insert into license_keys(`keys`) values(?)
Put a space between the license_keys(keys) and the 'values'
Also put backticks around the 'keys' column.

Related

Values not being submitted from PHP HTML form [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am trying to take the input from drop down menus that users enter and submit them to a table in my database. I am trying to submit the values into this table:
I use the POST to check that the values are being pulled from the HTML form and they are, but they won't submit into my table. I've made sure that all of the names with the columns and HTML forms are correct, why won't the values post to the table?
<?php
$databaseName = 'pizza_db';
$databaseUser = 'root';
$databasePassword = 'root';
$databaseHost = '127.0.0.1';
$conn = new mysqli($databaseHost, $databaseUser, $databasePassword, $databaseName);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected sucessfully\n";
if(isset($_POST['submit'])){
$value = mysqli_real_escape_string($conn,$_POST['drink']);
$value2 = mysqli_real_escape_string($conn,$_POST['cheese']);
$value3 = mysqli_real_escape_string($conn,$_POST['veggies']);
$value4 = mysqli_real_escape_string($conn,$_POST['meat']);
$value5 = mysqli_real_escape_string($conn,$_POST['sauce']);
$value6 = mysqli_real_escape_string($conn,$_POST['crust']);
$value7 = mysqli_real_escape_string($conn,$_POST['size']);
$sql = "INSERT INTO order_info(drink,cheese,veggies,meat,sauce,crust,size)
VALUES('$value','$value2','$value3','$value4','$value5','$value6','$value7')";
//Here I am posting the values to check that they are being submitted
echo $_POST["size"];
echo "\n";
echo $_POST["sauce"];
echo "\n";
echo $_POST["crust"];
echo "\n";
echo $_POST["cheese"];
echo "\n";
echo $_POST["meat"];
echo "\n";
echo $_POST["veggies"];
echo "\n";
echo $_POST["drink"];
$conn->close();
}
?>
<!DOCTYPE html>
<html>
<body>
<form action='' method='post'>
<p>Choose a size<p>
<select id="size" name="size">
<option value="small">Small</option>
<option value="medium">Medium</option>
<option value="large">Large</option>
<option value="x-large">X-large</option>
</select>
<p> Choose a sauce <p>
<select id="sauce" name="sauce">
<option value="none">None</option>
<option value="marinara">Marinara</option>
<option value="alfredo">Alfredo</option>
<option value="ranch">Ranch</option>
<option value="bbq">BBQ</option>
</select>
<p> Choose a cheese<p>
<select id="cheese" name="cheese">
<option value="none">None</option>
<option value="mozzarelaa">Mozarella</option>
<option value="cheddar">Cheddar</option>
<option value="parmesan">Parmesan</option>
<option value="three cheese">Three-Cheese</option>
</select>
<p> Choose a meat <p>
<select id="meat" name="meat">
<option value="none">None</option>
<option value="Pepperroni">Pepperroni</option>
<option value="sausage">Sausage</option>
<option value="bacon">Bacon</option>
<option value="canadian bacon">Canadian Bacon</option>
<option value="chicken">Chicken</option>
<option value="salami">Beef</option>
<option value="anchovies">Anchovies</option>
</select>
<p> Choose a veggies <p>
<select id="veggies" name="veggies">
<option value="none">None</option>
<option value="onions">Onions</option>
<option value="green peppers">Green Peppers</option>
<option value="Red peppers">Red peppers</option>
<option value="Black olives">Mushrooms</option>
<option value="jalapenos">Jalapenos</option>
<option value="tomatoes">Tomatoes</option>
<option value="pineapple">Pineapple</option>
</select>
<p> Choose a crust <p>
<select id="crust" name="crust">
<option value="regular">Regular</option>
<option value="deep-dish">Deep-dish</option>
<option value="thin-crust">Thin Crust</option>
<option value="stuffed crust">Stuffed Crust</option>
<option value="gluten free">Gluten Free</option>
</select>
<p> Choose a drink <p>
<select id="drink" name="drink">
<option value="none">None</option>
<option value="rootbeer">Root Beer</option>
<option value="coke">Coke</option>
<option value="diet coke">Diet Coke</option>
<option value="dr pepper">Dr Pepper</option>
</select>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
Seems like you are not running the query.
// sql
$sql = "INSERT INTO order_info(drink,cheese,veggies,meat,sauce,crust,size)
VALUES('$value','$value2','$value3','$value4','$value5','$value6','$value7')";
// run query
mysqli_query($conn, $sql);
// or
$conn->query($sql);
You prepared string query but you are not executing it.
$sql = "INSERT INTO order_info(drink,cheese,veggies,meat,sauce,crust,size)
VALUES('$value','$value2','$value3','$value4','$value5','$value6','$value7')";
// run query with below mentioned function
mysqli_query($conn, $sql);
Then check your table. You will see the data saved.

Linking this html to the database

I hope this is what you mean
-- phpMyAdmin SQL Dump
-- version 4.6.6deb5
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Oct 15, 2017 at 12:30 PM
-- Server version: 10.1.26-MariaDB-1
-- PHP Version: 7.0.22-3
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET #OLD_CHARACTER_SET_CLIENT=##CHARACTER_SET_CLIENT */;
/*!40101 SET #OLD_CHARACTER_SET_RESULTS=##CHARACTER_SET_RESULTS */;
/*!40101 SET #OLD_COLLATION_CONNECTION=##COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `Taheal`
--
-- --------------------------------------------------------
--
-- Table structure for table `test`
--
CREATE TABLE `test` (
`ID` int(11) NOT NULL,
`first_name` varchar(255) NOT NULL,
`Price` int(11) NOT NULL,
`last_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
`item_num` int(11) NOT NULL,
`Total` int(11) AS (Price*item_num) PERSISTENT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `test`
--
ALTER TABLE `test`
ADD PRIMARY KEY (`ID`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `test`
--
ALTER TABLE `test`
MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT;
/*!40101 SET CHARACTER_SET_CLIENT=#OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=#OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=#OLD_COLLATION_CONNECTION */;
here is the connect1.php with the right credentials given
and the database named Taheal consists of table named test columns (ID,first_name,Price,last_name,item_num,Total), however it still does nothing when i press submit on the html form
<?php
$servername = "localhost";
$dbusername = "root";
$dbpassword = "Youssef123";
$dbname = "test";
$fname = $_POST['fname']
$lname = $_POST['lname'];
$it_num = $_POST['it_num'];
/** Create connection **/
$conn = new mysqli($servername, $dbusername, $dbpassword, $dbname);
/**
* Use !empty($var) instead of $var, because is fast and return TRUE only if $var not empty
* Use urlencode() to generate correct $_GET string
**/
if (!empty($conn->connect_error)) {
header('location: /form.php?error='.urlencode($conn->connect_error));
exit; /** Prevent the script from running in background **/
}
if( empty($fname) ) {
header('location: /form.php?error='.urlencode('fname is empty'));
exit; /** Prevent the script from running in background **/
}
if( empty($lname) ) {
header('location: /form.php?error='.urlencode('lname is empty'));
exit; /** Prevent the script from running in background **/
}
if( empty($it_num) ) {
header('location: /form.php?error='.urlencode('it_num is empty'));
exit; /** Prevent the script from running in background **/
} else if( !is_numeric($it_num) ) {
header('location: /form.php?error='.urlencode('it_num must be a number'));
exit; /** Prevent the script from running in background **/
}
/**
* Example of db_table_field : first_name
* SQL : INSERT INTO test ('first_name') ...
* Use mysql_escape_string() to prevent Injection of JS code, etc, into DB
**/
$SQL = "INSERT INTO test ('first_name', 'last_name', 'item_num') VALUES ('".mysql_escape_string($fname)."', '".mysql_escape_string($lname)."', '".mysql_escape_string($it_num)."')";
/** Use === instead of ==, because It's more secure **/
if ($conn->query($SQL) === TRUE ) {
header('location: /form.php?success='.urlencode('Thank you for inserting info in the database') );
} else {
header('location: /form.php?error='.urlencode($conn->error));
}
exit; /** Prevent the script from running in background **/
?>
and here is the new form.php that i created
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtm111/DTD/xhtm111.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang=en
<html>
<head> <title>Taheal</title>
</head>
<body bgcolor ="lightyellow">
<?php if(!empty($_GET['success'])) { ?>
<div class="SUCCESS_MESSAGE">
<?php echo $_GET['success']; ?>
</div>
New insert
<?php } else if(!empty($_GET['error'])) { ?>
<div class="SUCCESS_MESSAGE">
<?php echo $_GET['success']; ?>
</div>
Retry
<?php } else { ?>
<form name="consumables" method ="post" action="connect1.php"/>
<table border = "2" align = "center" bgcolor = "lightblue">
<tr>
<td colspan= "2" align = "center">Form</td>
</tr>
<tr>
<td><center><font color = "red" >consumables:</font><center>
<select type = "text" name = "fname" value =""></center>
<option value="1">1</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
</td>
</tr>
<tr>
<td><center><font color="red" >RoomNum:</font><center>
<select type="text" name="lname" value=""/></center>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
</select>
</td>
</tr>
<tr>
<td><center><font color="red" >ItemNum:</font><center>
<select type="text" name="it_num" value=""></center>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="submit" value='submit'> </td>
</tr>
</table>
</form>
<?php } ?>
</body>
</html>
i need help with this code. it should connect to 'connect.php' then appy the code to Insert data in database named 'test' and give feedback to user that his data has been inserted
<?php include('connect.php'); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtm111/DTD/xhtm111.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang=en
<html>
<head> <title>Taheal</title>
</head>
<body bgcolor ="lightyellow">
<form name="consumables" method ="post" action="connect.php"/>
<table border = "2" align = "center" bgcolor = "lightblue">
<tr>
<td colspan= "2" align = "center">Form</td>
</tr>
<tr>
<td><center><font color = "red" >consumables:</font><center>
<select type = "text" name = "fname" value =""></center>
<option value="1">1</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
</td>
</tr>
<tr>
<td><center><font color = "red" >RoomNum:</font><center>
<select type="text" name ="lname" value=""/></center>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
</select>
</td>
</tr>
<tr>
<td><center><font color = "red" >ItemNum:</font><center>
<select type = "text" name = "it_num" value =""></center>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
</td>
</tr>
<tr>
<td colspan = "2" align = "center"><input type="submit" name= "submit" value = 'submit'> </td>
</tr>
</table>
</form>
</body>
</html>
here is the 'connect.php' file
<?php
$servername = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "test";
$fname = $_POST['fname']
$lname = $_POST['lname'];
$it_num = $_POST['it_num'];
// create connection
$conn = new mysqli($servername, $dbusername, $dbpassword, $dbname);
// check connection
if ($conn->connect_error) {
die("connection failed: " . $conn->connect_error);
}
if (empty($fname)){
echo "sometxt"
die();
}
if (empty($lname)){
echo "sometxt"
die();
}
if (empty($it_num)){
echo "sometxt"
die();
}
$sql ="INSERT INTO test ('$first_name', '$last_name', '$item_num')
VALUES {('$fname')}, {('$lname')}, {('$it_num')}";
if ($conn->query($sql) == TRUE) {
echo "thank you for inserting info in the database"
} else {
echo "ERROR: " $sql . "<br>" .$conn->error;
}
$conn->close()
?>
i just need to know if the problem is in syntax of what because after i submit the items it does not do anything. just hangs at 'localhost/db/connect.php'.
and does not give error.
First of all : You don't need to include "connect.php" in "form.php" file, because You call it when submit form
Delete: (leftArrow)? php include('connect.php'); ?>
Fix without jQuery library
ATTENTION : HTML file must have PHP extension (Instead of form.html use form.php)
/** PHP File connect.php **/
<?php
$servername = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "test";
$fname = $_POST['fname']
$lname = $_POST['lname'];
$it_num = $_POST['it_num'];
/** Create connection **/
$conn = new mysqli($servername, $dbusername, $dbpassword, $dbname);
/**
* Use !empty($var) instead of $var, because is fast and return TRUE only if $var not empty
* Use urlencode() to generate correct $_GET string
**/
if (!empty($conn->connect_error)) {
header('location: /form.php?error='.urlencode($conn->connect_error));
exit; /** Prevent the script from running in background **/
}
if( empty($fname) ) {
header('location: /form.php?error='.urlencode('fname is empty'));
exit; /** Prevent the script from running in background **/
}
if( empty($lname) ) {
header('location: /form.php?error='.urlencode('lname is empty'));
exit; /** Prevent the script from running in background **/
}
if( empty($it_num) ) {
header('location: /form.php?error='.urlencode('it_num is empty'));
exit; /** Prevent the script from running in background **/
} else if( !is_numeric($it_num) ) {
header('location: /form.php?error='.urlencode('it_num must be a number'));
exit; /** Prevent the script from running in background **/
}
/**
* Example of db_table_field : first_name
* SQL : INSERT INTO test ('first_name') ...
* Use mysql_escape_string() to prevent Injection of JS code, etc, into DB
**/
$SQL = "INSERT INTO test ('db_table_field_1', 'db_table_field_2', 'db_table_field_3') VALUES ('".mysql_escape_string($fname)."', '".mysql_escape_string($lname)."', '".mysql_escape_string($it_num)."')";
/** Use === instead of ==, because It's more secure **/
if ($conn->query($SQL) === TRUE ) {
header('location: /form.php?success='.urlencode('Thank you for inserting info in the database') );
} else {
header('location: /form.php?error='.urlencode($conn->error));
}
exit; /** Prevent the script from running in background **/
?>
$conn->close() is not necessary if We exit from PHP script =)
/** form.php file **/
<DOCTYPE ...>
...
<body bgcolor ="lightyellow">
<?php if(!empty($_GET['success'])) { ?>
<div class="SUCCESS_MESSAGE">
<?php echo $_GET['success']; ?>
</div>
New insert
<?php } else if(!empty($_GET['error'])) { ?>
<div class="SUCCESS_MESSAGE">
<?php echo $_GET['success']; ?>
</div>
Retry
<?php } else { ?>
<form>
... SHOW FORM HTML HERE ...
</form>
<?php } ?>
</body>
Fix with jQuery library
If You need a more dynamic technique, it's necessary to use jQuery methods (JavaScript)
If You want to try It, I can edit this post =) No problem

html form using PHP_SELF & php validation - after submit, results displayed on new page without displaying form

I am trying to create an html search form using a similar code as posted below.
When I submit the form, I want to submit to PHP_SELF
I want to use php validation code to filter the data.
When I submit the form, I cannot figure out how to get the results to post to a new page without displaying the form.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "xyz_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$showHtml = true;
$month = $day = $year = "";
$monthErr = $dayErr = $yearErr = "";
$errorMessage = "Oops..Please correct the item(s) highlighted in red on the form below and re-submit";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Month error & filter check code....
if (empty($_POST["month"])) {
$month = "";
} else {
$month = test_input($_POST["month"]);
if (!preg_match("/^[a-zA-Z ]*$/",$month)) {
$monthErr = "An invalid entry has been detected. Please reset this form and re-submit.";
}
}
// Day error & filter check code....
if (empty($_POST["day"])) {
$day = "";
} else {
$day = test_input($_POST["day"]);
if (!is_numeric($day)) {
$dayErr = "Day Found - An invalid entry has been detected. Please reset this form and re-submit.";
}
}
// Year error & filter check code....
if (empty($_POST["year"])) {
$year = "";
} else {
$year = test_input($_POST["year"]);
if (!is_numeric($year)) {
$yearErr = "Year Found - An invalid entry has been detected. Please reset this form and re-submit.";
}
}
if (empty($monthErr) and empty($dayErr) and empty($yearErr)) {
$showHtml = false;
$value1 = $_POST['month'];
$value2 = $_POST['day'];
$value3 = $_POST['year'];
$sql = "SELECT * FROM xyz_test_database WHERE month = ('$value1') AND day = ('$value2') AND year = ('$value3')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {echo "<br><br><h2>Search Results</h2>
<table><tr>
<th>ID</th>
<th>Time Stamp</th>
<th>Month</th>
<th>Day</th>
<th>Year</th>
</tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>".$row["id"]."</td>
<td>".$row["time_stamp"]."</td>
<td>".$row["month"]."</td>
<td>".$row["day"]."</td>
<td>".$row["year"]."</td>
</tr>";
}
echo "</table>";
} else {
echo "<p id='no_results'>Sorry - No Results Found :( </p>";
}
}
}
$conn->close();
exit ();
?>
<?php
if ($showHtml)
{
?>
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
</head>
<body>
<form name="form1" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<select id="item_select" name="month">
<option value="">Select Month</option>
<option value="January">January</option>
<option value="February">February</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select>
<select id="item_select" name="day">
<option value="">Day</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<select id="item_select" name="year">
<option value="">Year</option>
<option value="2015">2015</option>
<option value="2014">2014</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
<option value="1975">1975</option>
</select>
<br>
<span class="error"><?php echo $monthErr;?></span>
<span class="error"><?php echo $dayErr;?></span>
<span class="error"><?php echo $yearErr;?></span>
<br>
<input type="Submit" id="submit" name="submit" value="Submit Search" style="width: 120px; color: blue;"/>
</form>
</body>
</html>
<?php
}
?>
There are a number of ways to achieve this. You can put an if statement around your html code so that it only displays if certain conditions (e.g. results aren't returned) are met.
One really simple way of doing this is to set a boolean value if results are returned. For example:
<?php
$showHtml = true;
...
if($result->num_rows > 0)
{
$showHtml = false;
...
}
...
$conn->close();
if($showHtml)
{
?>
<!DOCTYPE html>
...
</html>
<?php
}
?>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "xyz_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$showHtml = true;
$month = $day = $year = "";
$monthErr = $dayErr = $yearErr = "";
$errorMessage = "Oops..Please correct the item(s) highlighted in red on the form below and re-submit";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Month error & filter check code....
if (empty($_POST["month"])) {
$month = "";
} else {
$month = test_input($_POST["month"]);
if (!preg_match("/^[a-zA-Z ]*$/",$month)) {
$monthErr = "An invalid entry has been detected. Please reset this form and re-submit.";
}
}
// Day error & filter check code....
if (empty($_POST["day"])) {
$day = "";
} else {
$day = test_input($_POST["day"]);
if (!is_numeric($day)) {
$dayErr = "Day Found - An invalid entry has been detected. Please reset this form and re-submit.";
}
}
// Year error & filter check code....
if (empty($_POST["year"])) {
$year = "";
} else {
$year = test_input($_POST["year"]);
if (!is_numeric($year)) {
$yearErr = "Year Found - An invalid entry has been detected. Please reset this form and re-submit.";
}
}
if (empty($monthErr) and empty($dayErr) and empty($yearErr)) {
$showHtml = false;
$value1 = $_POST['month'];
$value2 = $_POST['day'];
$value3 = $_POST['year'];
$sql = "SELECT * FROM xyz_test_database WHERE month = ('$value1') AND day = ('$value2') AND year = ('$value3')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {echo "<br><br><h2>Search Results</h2>
<table><tr>
<th>ID</th>
<th>Time Stamp</th>
<th>Month</th>
<th>Day</th>
<th>Year</th>
</tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>".$row["id"]."</td>
<td>".$row["time_stamp"]."</td>
<td>".$row["month"]."</td>
<td>".$row["day"]."</td>
<td>".$row["year"]."</td>
</tr>";
}
echo "</table>";
} else {
echo "<p id='no_results'>Sorry - No Results Found :( </p>";
}
}
}
$conn->close();
exit ();
?>
<?php
if ($showHtml)
{
?>
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
</head>
<body>
<form name="form1" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<select id="item_select" name="month">
<option value="">Select Month</option>
<option value="January">January</option>
<option value="February">February</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select>
<select id="item_select" name="day">
<option value="">Day</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<select id="item_select" name="year">
<option value="">Year</option>
<option value="2015">2015</option>
<option value="2014">2014</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
<option value="1975">1975</option>
</select>
<br>
<span class="error"><?php echo $monthErr;?></span>
<span class="error"><?php echo $dayErr;?></span>
<span class="error"><?php echo $yearErr;?></span>
<br>
<input type="Submit" id="submit" name="submit" value="Submit Search" style="width: 120px; color: blue;"/>
</form>
</body>
</html>
<?php
}
?>

Php form (using PDO) to insert into other tables (foreign keys)

I need some help, I am trying to insert into multiple tables using PDO - Can someone see what I am doing wrong - I am not getting a parse errors (nor did I set up an asset error):
Here is my form:
addcontact.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add New Contact</title>
<link rel="stylesheet" href="css/table.css" type="text/css" />
</head>
<body>
<div class="CSS_Table_Example" style="width:500px;height:350px;">
<center>
<form action="insert.php" method="post">
<p>
<td>
<tr><label for="ContactName">Contact Name:</label>
<input type="text" name="ContactName" id="ContactName">
</tr></p>
<p>
<tr> <label for="ContactTypeId">Contact Type:</label>
<select name="ContactTypeId">
<option value="1">Contact</option>
<option value="2">Organization</option>
</select>
</p>
<p>
<td>
<tr> <label for="AddressTypeId">Address Type:</label>
<select name="AddressTypeId">
<option value="1">Home</option>
<option value="2">Office</option>
<option value="3">Other</option>
</select>
</p>
<p>
<tr><label for="Address1">Address 1:</label>
<input type="text" name="Address1" id="Address1">
</tr></p>
<p>
<tr><label for="Address2">Address 2:</label>
<input type="text" name="Address2" id="Address1">
</tr></p>
<p>
<tr><label for="City">City:</label>
<input type="text" name="City" id="Address1">
</tr></p>
<tr> <label for="StateId">State:</label>
<select name="StateId">
<option value="1">Alabama</option>
<option value="2">Alaska</option>
<option value="3">Arizona</option>
<option value="4">Arkansas</option>
<option value="5">Califorina</option>
<option value="6">Colorado</option>
<option value="7">Connecticut</option>
<option value="8">Delaware</option>
<option value="9">District of Columbia</option>
<option value="10">Florida</option>
<option value="11">Georgia</option>
<option value="12">Hawaii</option>
<option value="13">Idaho</option>
<option value="14">Illinois</option>
<option value="15">Indiana</option>
<option value="16">Iowa</option>
<option value="17">Kansas</option>
<option value="18">Kentucky</option>
<option value="19">Louisana</option>
<option value="20">Maine</option>
<option value="21">Maryland</option>
<option value="22">Massachusetts</option>
<option value="23">Michigan</option>
<option value="24">Minnesota</option>
<option value="25">Mississippi</option>
<option value="26">Missouri</option>
<option value="27">Montana</option>
<option value="28">Nebraska</option>
<option value="29">Nevada</option>
<option value="30">New Hampshire</option>
<option value="31">New Jersey</option>
<option value="32">New Mexico</option>
<option value="33">New York</option>
<option value="34">North Carolina</option>
<option value="35">North Dakota</option>
<option value="36">Ohio</option>
<option value="37">Oklahoma</option>
<option value="38">Oregon</option>
<option value="39">Pennsylvania</option>
<option value="40">Rhode Island</option>
<option value="41">South Carolina</option>
<option value="42">South Dakota</option>
<option value="43">Tennessee</option>
<option value="44">Texas</option>
<option value="45">Utah</option>
<option value="46">Vermont</option>
<option value="47">Virginia</option>
<option value="48">Washington</option>
<option value="49">West Virginia</option>
<option value="50">Wisconsin</option>
<option value="51">Wyoming</option>
</select>
</tr> </p>
<input type="submit" value="Add Record">
</tr></td>
</form>
</table>
</body>
</html>
Here is insert.php
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "crm";
//making an array with the data received, to use as named placeholders for INSERT by PDO.
$data = array('ContactName' => $_POST['ContactName'] , 'ContactTypeId'
=> $_POST['ContactTypeId'],
'ContactId'=> $_POST['ContactId'],'AddressTypeId'=>
$_POST['AddressTypeId'],'Address1'=>$_POST['Address1'],
'Address2'=>$_POST['
Address2'],'City'=>$_POST['City'],'StateId'=>$_POST['StateId']);
try {
// preparing database handle $dbh
$dbh = new PDO("mysql:host=$servername;dbname=$dbname",
$username,$password);
// set the PDO error mode to exception
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$currentID = mysql_inserted_id();
// query with named placeholders to avoid sql injections
$query = "INSERT INTO Contacts (ContactName, ContactTypeId)
VALUES(:ContactName, :ContactTypeId )";
$query2= "INSERT INTO
Addresses(ContactId,AddressTypeId,Address1,Address2,City,StateId)
VALUES(:$currentID,:AddressTypeId,:Address1,:Address2,:City,:StateId)";
//statement handle $sth
$sth = $dbh->prepare($query);
$sth->execute($data);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$dbh = null;
?>
You need to create two arrays $data for $query & $data1 for $query1 and need use $dbh->lastInsertId() for last id. Use the below code. I think it will work:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "crm";
//making an array with the data received, to use as named placeholders for INSERT by PDO.
$data = array('ContactName' => $_POST['ContactName'] , 'ContactTypeId'
=> $_POST['ContactTypeId']);
$data1=array('AddressTypeId'=>$_POST['AddressTypeId'],'Address1'=>$_POST['Address1'],
'Address2'=>$_POST['
Address2'],'City'=>$_POST['City'],'StateId'=>$_POST['StateId']);
try {
// preparing database handle $dbh
$dbh = new PDO("mysql:host=$servername;dbname=$dbname",
$username,$password);
// set the PDO error mode to exception
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// query with named placeholders to avoid sql injections
$query = "INSERT INTO Contacts (ContactName, ContactTypeId)
VALUES(:ContactName, :ContactTypeId )";
$sth = $dbh->prepare($query);
$sth->execute($data);
$currentID = $dbh->lastInsertId();
$query2= "INSERT INTO
Addresses(ContactId,AddressTypeId,Address1,Address2,City,StateId)
VALUES($currentID,:AddressTypeId,:Address1,:Address2,:City,:StateId)";
$sth = $dbh->prepare($query2);
$sth->execute($data1);
//statement handle $sth
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$dbh = null;
?>

php script won't connect MySQL

This is the code. and for some reason I can't find out why it is not working.
As you can see I've added a test query to see if it affects any changes on my db but nope :(
The funny thing is that in another php script I have succeeded to connect the db and even added some records to it thru the php script. Can't find the problem, Thanks from advance.
BTW. as you can see I have already defined the var "month" as string "hey" and echo it in the end of the php script to see if it changes. but nothing is happen!!
<form action="" name="form" id="form">
<label>
Select the month which you want to display its days.
<select name="month" form="form" required>
<option value="january">January</option>
<option value="february">February</option>
<option value="march">March</option>
<option value="april">April</option>
<option value="may">May</option>
<option value="june">June</option>
<option value="july">July</option>
<option value="august">August</option>
<option value="september">September</option>
<option value="october">October</option>
<option value="november">November</option>
<option value="december">December</option>
</select>
</label>
<input type="submit" name="update" value="Display" />
</form>
<?php
$month = "hey";
if(isset($_POST["update"]))
{
$month = $_POST["month"];
$query = "SELECT * FROM `days` WHERE `month`='{$month}';";
$conn = mysqli_connect("localhost","root","","db123");
$result = mysqli_query($conn,$query);
mysqli_query($conn,"INSERT INTO `days`(`month`,`day`) VALUES ('test','10');");
if($result)
{
die("Sorry!");
}
while($row = mysqli_fetch_row($result))
{
echo $month;
print_r($row);
}
mysqli_close($conn);
echo $month;
}
?
You didn't specified the method , its GET by default if.Change this line
if(isset($_POST["update"]))
to this
if(isset($_GET["update"]))
. Or if you want to use method as POST than just specify the method as POST
use the code below
<form action="" name="form" id="form" method="POST">
<label>
Select the month which you want to display its days.
<select name="month" form="form" required>
<option value="january">January</option>
<option value="february">February</option>
<option value="march">March</option>
<option value="april">April</option>
<option value="may">May</option>
<option value="june">June</option>
<option value="july">July</option>
<option value="august">August</option>
<option value="september">September</option>
<option value="october">October</option>
<option value="november">November</option>
<option value="december">December</option>
</select>
</label>
<input type="submit" name="update" value="Display" />
</form>
<?php
$month = "hey";
if(isset($_POST["update"]))
{
$month = $_POST["month"];
$query = "SELECT * FROM `days` WHERE `month`='{$month}';";
$conn = mysqli_connect("localhost","root","","db123");
$result = mysqli_query($conn,$query);
mysqli_query($conn,"INSERT INTO `days`(`month`,`day`) VALUES ('test','10');");
if($result)
{
die("Sorry!");
}
while($row = mysqli_fetch_row($result))
{
echo $month;
print_r($row);
}
mysqli_close($conn);
echo $month;
}
?>
Hope this helps you
<?php
$mysqli = new mysqli("localhost", "root", "", "db123");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$month = "hey";
if(isset($_POST["update"]))
{
$month = $_POST["month"];
$res = $mysqli->query("SELECT * FROM `days` WHERE `month`='{$month}'");
mysqli_query($conn,"INSERT INTO `days`(`month`,`day`) VALUES ('test','10');");
while($row = $res->num_rows)
{
echo $month;
print_r($row);
}
mysqli_close($conn);
echo $month;
}
?>

Categories