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
Related
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.
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
}
?>
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;
?>
i'm working on a php script wherein i must add certain score value at each row. I was able to display all the rows but i'm not sure on how would I able to store each of the given score in a variable and what query should I make to add all of them.
Here's my code
<?php
echo '<html>';
?>
<body>
<table border=0 cellspacing=0 cellpadding=0>
<?php
$connect = mysql_connect('localhost', 'root', '');
$db = 'labs';
$tb = 'comments';
$seldb = mysql_select_db($db, $connect);
echo '<form method="POST" action="..'.$_SERVER["PHP_SELF"].'">';
$query = mysql_query('SELECT com_id, comments FROM comments ORDER BY com_id ASC');
while($i = mysql_fetch_assoc($query)) {
echo'<tr><td>'.$i['comments'].'</td>';
echo'<td><select name="score" id="score" size="1">
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="20">20</option>
<option value="25">25</option>
<option value="30">30</option>
<option value="35">35</option>
<option value="40">40</option>
<option value="45">45</option>
<option value="50">50</option>
</select></td></tr>';
echo'<br>';
}
echo'<input type="submit" name="submit" value="submit">';
echo'</form>';
if(isset($_POST['submit'])) {
//not sure if all the scores will be stored in here.
$id = $_POST['id'];
$query = mysql_query('insert query here');
}
?>
</table>
</body>
</html>
any suggestions are appreciated. Thanks in advance.:D
I think you need the id of each changed row (maybe as a hidden field for each row. Then just do a loop through all received rows and UPDATE each one.
You might also want to change all of your form field names to use the array format. This way it's easier to make your PHP loop throught them.
Sample row:
echo'<tr><td>'.$i['comments'].'</td>';
echo'<td><select name="score['.$i["id"].']" id="score" size="1">
<option value="5">5</option>
<option value="5">10</option>
<option value="5">15</option>
<option value="5">20</option>
<option value="5">25</option>
<option value="5">30</option>
<option value="5">35</option>
<option value="5">40</option>
<option value="5">45</option>
<option value="5">50</option>
</select></td></tr>';
Now just loop through the $_POST["score"] array and use the appropriate ID for your update.
foreach($_POST["score"] as $id => $value{
// ESCAPE your db values!!!!!
// query stuff with $value and $id
}
Also keep in Mind
mysql is deprecated! Use mysqli
Escape anything from outside sources like $_POST before use in SQL
You just needs to make an array of your drop down box like below,
while($i = mysql_fetch_assoc($query)) {
echo'<tr><td>'.$i['comments'].'</td>';
echo'<td><select name="score[".$i['com_id']."]" id="score" size="1">
<option valyue="5">5</option>
<option valyue="5">10</option>
<option valyue="5">15</option>
<option valyue="5">20</option>
<option valyue="5">25</option>
<option valyue="5">30</option>
<option valyue="5">35</option>
<option valyue="5">40</option>
<option valyue="5">45</option>
<option valyue="5">50</option>
</select></td></tr>';
echo'<br>';
}
and you can access it for all of your comments
<option valyue="5">50</option>
should be
<option value="5">50</option>
To send the value of a comment to database you need to add a ID of the comment
you should loop something like this.
$query = mysql_query('SELECT com_id, comments FROM comments ORDER BY com_id ASC');
while($i = mysql_fetch_assoc($query)) {
echo '<form method="POST" action="..'.$_SERVER["PHP_SELF"].'">';
echo '<input type="hidden" name="id" value="'.$i['com_id'].'">';
echo'<tr><td>'.$i['comments'].'</td>';
echo'<td><select name="score" id="score" size="1">
<option value="5">5</option>
<option value="5">10</option>
<option value="5">15</option>
<option value="5">20</option>
<option value="5">25</option>
<option value="5">30</option>
<option value="5">35</option>
<option value="5">40</option>
<option value="5">45</option>
<option value="5">50</option>
</select></td></tr>';
echo'<br>';
echo'<input type="submit" name="submit" value="submit">';
echo'</form>';
}
I guess the easiest way for you is the following (a mix of the other solutions and comments):
<?php
echo '<html>';
?>
<body>
<table border=0 cellspacing=0 cellpadding=0>
<?php
$x = 0;
$connect = mysql_connect('localhost', 'root', '');
$db = 'labs';
$tb = 'comments';
$seldb = mysql_select_db($db, $connect);
echo '<form method="POST" action="..'.$_SERVER["PHP_SELF"].'">';
$query = mysql_query('SELECT com_id, comments FROM comments ORDER BY com_id ASC');
while($i = mysql_fetch_assoc($query)) {
$x++;
echo'<tr><td>'.$i['comments'].'</td>';
echo'<td><select name="score_'.$x.'" id="score" size="1">
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="20">20</option>
<option value="25">25</option>
<option value="30">30</option>
<option value="35">35</option>
<option value="40">40</option>
<option value="45">45</option>
<option value="50">50</option>
</select></td></tr>';
echo'<br>';
}
echo'<input type="submit" name="submit" value="submit">';
echo'</form>';
if(isset($_POST['submit'])) {
//not sure if all the scores will be stored in here.
$id = $_POST['id'];
for($y = 0;$y <= $x; $y++)
{
//This query is no sql injection save. Please add filters for productive uses!!
$query = mysql_query('UPDATE table_name SET score = '.$_POST["score_".$y].' WHERE id='.$id);
}
?>
</table>
</body>
</html>
Code is no tested!
Actually i am performing a search in my database, there are two tables, rent and sale. When user selects parameter for rent with the help of radio button and other parameters, it should search the data in rent table and return the result if it all matches. and same for second table.
But after executing my query i am getting error. Please help me in this.
I am posting all my codes here.
User selection page.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>real estate</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$("input#tblsection").val('sale_table');
$('input:radio[name=rbtn]').attr('checked',true);
$("#rent").click(function() {
$("#rentselect").attr('style', 'display:block;margin-top:20px;');
$("#saleselect").attr('style', 'display:none;');
$("input#tblsection").val('rent_table');
});
$("#sale").click(function() {
$("#saleselect").attr('style', 'display:block;margin-top:20px;');
$("#rentselect").attr('style', 'display:none;');
$("input#tblsection").val('sale_table');
});
$("#srajax").click(function(){
var rentvalue = $('select#rentselect').val();
var salevalue = $('select#saleselect').val();
var location = $('select#location').val();
var area = $('select#Area').val();
var bedroom = $('select#bedroom').val();
var table = $('input#tblsection').val();
$.post(" testajax.php",
{
rentvalue: rentvalue,
salevalue: salevalue,
location: location,
area: area,
bedroom: bedroom,
table: table
},
function(data) {
alert("Data Loaded: "+data);
});
});
});
</script>
</head>
<body>
<form name="srajax" method="post">
<input type="radio" name="rbtn" value="rent" id="rent" /> <b>Rent</b>
<input type="radio" name="rbtn" value="sale" id="sale" /> <b>Sale</b>
<input type="hidden" name="tablenmae" id="tblsection" value="tablesale">
<br>
<select id="rentselect" style='display:none;'>
<option value="">----Select Budget For Rent----</option>
<option value="5000">5000</option>
<option value="5000_10000">5000 to 10000</option>
<option value="11000_20000">11000 to 20000</option>
<option value="above_20000">Above 20000</option>
</select>
<select id="saleselect" style='margin-top:20px;margin-bottom:20px;'>
<option value="">----Select Budget For Sale----</option>
<option value="5000">100000</option>
<option value="5000_10000">500000</option>
<option value="11000_20000">1000000</option>
<option value="above_20000">2500000</option>
</select>
<br>
<select id="location" name="Location">
<option>----Select Location---</option> <option value="All_Location">All Location</option>
<option value="Central_Mumbai">Central Mumbai</option>
<option value="Mumbai_Harbour">Mumbai Harbour</option>
<option value="Mumbai_Navi">Mumbai Navi</option>
<option value="Mumbai_South">Mumbai South</option>
<option value="Mumbai_Thane">Mumbai Thane</option> </select>
<br>
<br>
<select id="Area" name="Area">
<option value="">-----Select Area---</option>
<option value="All Area">All Area</option>
<option value="Bhandup">Bhandup</option>
<option value="Chembur">Chembur</option>
<option value="Kurla">Kurla</option>
<option value="Mulund">Mulund</option>
<option value="All Area">All Area</option>
<option value="Byculla">Byculla</option>
<option value="Chembur">Chembur</option>
<option value="Govandi">Govandi</option>
<option value="Sewri">Sewri</option>
<option value="Wadala">Wadala</option>
<option value="All Area">All Area</option>
<option value="Airoli">Airoli</option>
<option value="Belapur">Belapur</option>
<option value="Ghansoli">Ghansoli</option>
<option value="Mahape">Mahape</option>
<option value="Nerul">Nerula</option>
<option value="All Area">All Area</option>
<option value="Churchgate">Churchgate</option>
<option value="CST">CST</option>
<option value="Dadar">Dadar</option>
<option value="Fort">Fort</option>
<option value="All Area">All Area</option>
<option value="Brindavan">Brindavan</option>
<option value="Kalothe">Kalothe</option>
<option value="Kapur">Kapur</option>
<option value="Kalwa">Kalwa</option>
<option value="Kopat">Kopat</option> </select><br /><br>
<select id="bedroom" name="bedroom">
<option>---Select Bedroom---</option>
<option value="1BHK">1 BHK</option>
<option value="2BHK">2 BHK</option>
<option value="3BHK">3 BHK</option>
<option value="4BHK">3 BHK</option>
</select>
<br><br><br>
<input type="button" name="search" id="srajax" value="Search"/>
</form>
</body>
</html>
My search page
<?php
$host="localhost"; // Host name
$db_name="netelmbn_realestate"; // Database name
$tbl1_name="rent_table"; // Table1 name
$tbl2_name="sale_table"; //Table2 name
mysql_connect("localhost","netelmbn","password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
echo "<pre>";
print_r($_POST);
if($_POST['table'] == 'rent_table')
{
$result=mysql_query("select * from rent_table where location='$location' AND area='$area' AND bedroom='$bedroom' AND $budget='budget' ");
echo "<table cellpadding='20'>";
echo '<tr>';
while ($row = mysql_fetch_assoc($result)) {
echo "<td width='300'><strong>Budget:</strong> ".$row['budget']."<br><strong>Location</strong>: ".$row['location']."<br><strong>Area:</strong> ".$row['area']."<br><strong>BHK:</strong> ".$row['bhk']."<br></td>";
}
echo "</tr></table>";
}
if($_POST['table'] == 'sale_table')
{
$result=mysql_query("select * from sale_table where location='$location' AND area='$area' AND bedroom='$bedroom' AND $budget='budget' ");
echo "<table cellpadding='20'>";
echo '<tr>';
while ($row = mysql_fetch_assoc($result)) {
echo "<td width='300'><strong>Budget:</strong> ".$row['budget']."<br><strong>Location</strong>: ".$row['location']."<br><strong>Area:</strong> ".$row['area']."<br><strong>BHK:</strong> ".$row['bhk']."<br></td>";
}
echo "</tr></table>";
}
while ($row = mysql_fetch_assoc($result)) {
echo "<td width='300'><strong>Budget:</strong> ".$row['budget']."<br><strong>Location</strong>: ".$row['location']."<br><strong>Area:</strong> ".$row['area']."<br><strong>BHK:</strong> ".$row['bhk']."<br></td>";
}
echo "</tr></table>";
exit;
and i have rent_table
CREATE TABLE `rent_table` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`location` varchar(40) NOT NULL,
`area` varchar(40) NOT NULL,
`bedroom` varchar(20) NOT NULL,
`budget` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=58 ;
samething for sale_table
please help me where i am going wrong. Here is the error image i am getting this error:
error http://netelity.com/realestate/error.png
After any and all database queries, check if the query was actually successful and use the appropriate debugging functions to find why it wasn't. Don't just assume that it worked.
$result = mysql_query(...);
if (!$result) {
echo mysql_error();
die;
}
ok here you go:
1) add this before if($_POST['table'] == 'rent_table') :
$location = $_POST['location'];
$area = $_POST['area'];
$bedroom = $_POST['bedroom'];
$budget = $_POST['budget'];
2) you have a mistake in your query : AND $budget='budget' should be AND budget='$budget'
That error indicates an error in the queries and therefore the MySQL resultset is invalid. The error seems to be in the check "$budget = 'budget'" that $budget should be enclosed in quotes. Try these versions:
Query1: $result=mysql_query("select * from rent_table where location='$location' AND area='$area' AND bedroom='$bedroom' AND '$budget'='budget' ");
Query2: $result=mysql_query("select * from sale_table where location='$location' AND area='$area' AND bedroom='$bedroom' AND '$budget'='budget' ");
Hope it helps!