i have created a page to insert element into a database in php.
At the beggining i start use with mySQL, and it works perfectly. Then I'm migrate to Postgres and so i had some problems.
I change my code and i don't receive erros,but when i'm trying to insert my elements into the db, this remains empty.
this the structure of my table Prenotazione
CREATE TABLE public."Prenotazione"
(
id integer NOT NULL DEFAULT nextval('"Prenotazione_id_seq"'::regclass),
nominativo character(20),
email character(20),
oggetto character(200),
nominativoi character(200),
nominativoe character(200),
emaili character(200),
emaile character(200),
data date,
orario_inizio time without time zone,
orario_fine time without time zone,
stanza integer
)
this is my index.php
<form method="post" action="input.php">
<b> Richiedente Conferenza:</b><br><br>
Nominativo:<br> <input type="text" name="nominativo" placeholder="Nome Cognome" size="20"><br>
Email: <br> <input type="email" name="email" size="20" placeholder="email"><br>
Oggetto Conferenza:<br> <textarea name="oggetto" rows="5" cols="40" placeholder="Specificare oggetto Videoconferenza"></textarea><br>
Data: <br> <input type="date" name="data" ><br>
Orario Inizio: <br> <input type="time" name="orario_inizio" min="09:30:00" max="16:30:00" ><br>
Orario Fine: <br> <input type="time" name="orario_fine" min="10:00:00" max="18:30:00"><br>
<br>
<b> Partecipanti Interni </b>
<br>
<br>
<div id="interni">
<div id="first">
Nominativo:<br> <textarea name="nominativoi" rows="5" cols="30" placeholder="Nome Cognome;" ></textarea><br>
Email:<br> <textarea name="emaili" rows="5" cols="30" placeholder="Inserire Email"></textarea><br>
<br>
<br>
</div>
</div>
<b> Partecipanti Esterni </b>
<div id="esterni">
<div id="first">
Nominativo:<br> <textarea name="nominativoe" rows="5" cols="30" placeholder="Nome Cognome;" ></textarea><br>
Email:<br> <textarea name="emaile" rows="5" cols="30" placeholder="Inserire Email"></textarea><br>
<br>
<input type="submit" value="Invia" >
</form>
And finally the input.php
$checkdata = "SELECT count(*) as prenotato
FROM Prenotazione
WHERE data='$data'
AND NOT ('$newTimeEnd' < orario_inizio OR orario_fine < '$orario_inizio')";
$querycheck = $dbh->prepare($checkdata);
$querycheck->execute();
$prenotato = $querycheck->fetch()[0];
var_dump($prenotato);
if ($prenotato == 0 AND $stanza == 0 ) {
$query1 = "INSERT INTO Prenotazione (nominativo,email,data,orario_inizio,orario_fine,oggetto,nominativoi,emaili,nominativoe,emaile,stanza) VALUES ('$nominativo','$email','$data','$orario_inizio','$newTimeEnd','$oggetto','$nominativoi','$emaili','$nominativoe','$emaile',1)";
var_dump($query1);
$result1 = $dbh->prepare($query1);
$result1->execute();
$rex = 1;
}
else if ($prenotato == 1){
$query1 = "INSERT INTO Prenotazione (nominativo,email,data,orario_inizio,orario_fine,oggetto,nominativoi,emaili,nominativoe,emaile,stanza) VALUES ('$nominativo','$email','$data','$orario_inizio','$orario_fine','$oggetto','$nominativoi','$emaili','$nominativoe','$emaile',2)";
$result1 = $dbh->prepare($query1);
$result1->execute();
$rex = 1;
}
I posted the part that are interesting to the problem.
Thanks
The result of var_dump is :
NULL string(269) "INSERT INTO Prenotazione
(nominativo,email,data,orario_inizio,orario_fine,oggetto,nominativoi,emaili,nominativoe,emaile,stanza)
VALUES
('username','email#email.com','2018-10-03','09:30','12:30','object','username1','email1#email1.com','username2','email2#email2.com',1)"
The problem is with your table name in double quotes. Don't use double quotes, or use them in every request.
You can verify your code here:
http://rextester.com/VIEH75483
Also, see more: Omitting the double quote to do query on PostgreSQL
Related
i have a simple form and i need that some fields are required.
I do not understand why they do not work. In fact, if I click on the Send button, it takes me to an error page.
I have tried inserting both the required = "required" and only required.
How can I do according to you?
Thank you for your time and availability.
<h3> Dati Prenotazione</h3>
Inserire i dati richiesti:<br><br>
<form method="post" action="input.php">
<b> Richiedente Conferenza:</b><br><br>
Nominativo:<br> <input type="text" name="nominativo" placeholder="Nome Cognome" size="20" required="required"><br>
Email: <br> <input type="email" name="email" size="20" placeholder="email" required><br>
Oggetto Conferenza:<br> <textarea name="oggetto" rows="5" cols="40" placeholder="Specificare oggetto Videoconferenza" required></textarea><br>
Data: <br> <input type="date" name="data" required ><br>
Orario Inizio: <br> <input type="time" name="orario_inizio" min="09:30:00" max="16:30:00" required ><br>
Orario Fine: <br> <input type="time" name="orario_fine" min="10:00:00" max="18:30:00" required><br>
<br>
<b> Partecipanti Interni </b>
<br>
<br>
<div id="interni">
<div id="first">
Nominativo:<br> <textarea name="nominativoi" rows="5" cols="30" placeholder="Nome Cognome;" required ></textarea><br>
Email:<br> <textarea name="emaili" rows="5" cols="30" placeholder="Inserire Email" required></textarea><br>
input.php
require ('config.php');
// Richiedente
$nominativo = $_POST['nominativo'];
$email = $_POST['email'];
$oggetto = $_POST['oggetto'];
$data = $_POST['data'];
$orario_inizio = $_POST['orario_inizio'];
$orario_fine = $_POST['orario_fine'];
$stanza = 0;
// Personale Interno
$nominativoi = $_POST['nominativoi'];
$emaili = $_POST['emaili'];
// Persona Esterno
$nominativoe = $_POST['nominativoe'];
$emaile = $_POST['emaile'];
//aggiunta di un'ora ( per tornare indietro cambiare $newTimeEnd con $orario_fine
$dateTime = DateTime::createFromFormat('H:i', $orario_fine);
$dateInterval = DateInterval::createFromDateString('1 hour');
$dateTime->add($dateInterval);
$query1 = "INSERT INTO prenotazione (nominativo,email,data,orario_inizio,orario_fine,oggetto,nominativoi,emaili,nominativoe,emaile,stanza) VALUES ('$nominativo','$email','$data','$orario_inizio','$newTimeEnd','$oggetto','$nominativoi','$emaili','$nominativoe','$emaile',1)";
$result1 = $dbh->prepare($query1);
$result1->execute();
$rex = 1;
}
else if ($prenotato == 1 AND $prenotatoaccettato == 0 ){
$query1 = "INSERT INTO prenotazione (nominativo,email,data,orario_inizio,orario_fine,oggetto,nominativoi,emaili,nominativoe,emaile,stanza) VALUES ('$nominativo','$email','$data','$orario_inizio','$newTimeEnd','$oggetto','$nominativoi','$emaili','$nominativoe','$emaile',2)";
$result1 = $dbh->prepare($query1);
$result1->execute();
$rex = 1;
}
EDIT.
When i click submit the error is
Fatal error: Uncaught Error: Call to a member function add() on boolean
( about $dateTime->add($dateInterval); )
check required fields in your code
if (empty($_POST["nominativo"])) {
addError('nominativo','nominativo error text');
} else {
$nominativo = $_POST["nominativo"];
}
Nome Cognome : <input type="text" name="nominativo">
<span class="error">* <?php echo $nominativoErr;?></span>
Isn't you problem rather in the input.php (can you post it ?) ? Are you sure of the path ?
Also, don't trust what is sent, make a validation in your php too, the HTML and JS code can be changed by the user.
you can try something like:
if($email==NULL|$data==NULL) {
?>
<script>
alert("Missing Fields!");
location.href="form1.html";// page where ir your form
</script>
<?php
}
if (!preg_match("/^[a-zA-Z0-9_\.\-]+#[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$/", $email)) {
exit('The email format is incorrect.');
}
Im trying to insert the steamid , steam real name . steam name into my db when the user login in my website
mycode :
<?php
if (isset($_GET['login'])){
$steamids= $steamprofile['steam_steamid'];
$name = $steamprofile['personaname'];
$real = $steamprofile['realname'];
$ESCAPING_real= mysqli_real_escape_string($connection,$real);
$ESCAPING_name= mysqli_real_escape_string($connection,$name);
$ESCAPING_steamids= mysqli_real_escape_string($connection,$steamids);
$query = "INSERT INTO users(steamnid,steamname, steamreal,user_logindate) ";
$query .= "VALUES('{$steamids}','{$name}', '{$real}', now())";
$insert_query = mysqli_query($connection,$query);
if(!$insert_query){
die("failed".mysqli_error($connection));
}
}
?>
$button = "<a href='?login'><img src='http".(isset($_SERVER['HTTPS']) ? "s" : "")."://steamcommunity-a.akamaihd.net/public/images/signinthroughsteam/sits_".$button[$buttonstyle].".png'></a>";
When the user log in i dont get anything in the db .
i tried to store the user info using sessions and it works but alway duplicate the value
the code is a little bit messy Because im still learning
Any Idea?
<?php
$db = array("DB_HOST"=>"localhost","DB_USER"=>"root","DB_PASS"=>"mysql","DB_NAME"=>"databasename",);
foreach ($db as $key => $value)
{
define($key , $value);
}
$connection = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
if (!$connection)
{
die ('<h1>connecting failed</h1>');
}
if (isset($_GET['login'])){
$steamids= $_GET['steam_steamid'];
$name = $_GET['personaname'];
$real = $_GET['realname'];
$ESCAPING_real= mysqli_real_escape_string($connection,$real);
$ESCAPING_name= mysqli_real_escape_string($connection,$name);
$ESCAPING_steamids= mysqli_real_escape_string($connection,$steamids);
$query = "INSERT INTO users(steamnid,steamname, steamreal,user_logindate) ";
$query .= "VALUES('{$steamids}','{$name}', '{$real}', now())";
$insert_query = mysqli_query($connection , $query);
if ($insert_query) {
echo "User added";
}else{
die("we have error " . mysqli_error($connection));
}
}
?>
<form action="" method="GET">
<div class="form-group">
<label for="steam_steamid">Steam ID : </label>
<input name="steam_steamid" type="text">
</div><br>
<div class="form-group">
<label for="steam_steamid">Personal Name: </label>
<input name="personaname" type="text">
</div><br>
<div class="form-group">
<label for="steam_steamid">Real Name: </label>
<input name="realname" type="text">
</div><br>
<button type="submit" name="login"><img src='https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon#2.png?v=73d79a89bded'></button>
</form>
check it we have create data base and check my code it work my table user have
steamid (varchar 255)
steamname (varchar 255)
steamreal (varchar 255)
user_logindate (Date)
i don't saw your HTML Form but i added and i think its work check this
<?php
if (isset($_GET['login'])){
$steamids= $_GET['steam_steamid'];
$name = $_GET['personaname'];
$real = $_GET['realname'];
$ESCAPING_real= mysqli_real_escape_string($connection,$real);
$ESCAPING_name= mysqli_real_escape_string($connection,$name);
$ESCAPING_steamids= mysqli_real_escape_string($connection,$steamids);
$query = "INSERT INTO users(steamnid,steamname, steamreal,user_logindate) ";
$query .= "VALUES('{$steamids}','{$name}', '{$real}', now())";
$insert_query = mysqli_query($connection,$query);
if(!$insert_query){
die("failed".mysqli_error($connection));
}
}
?>
<form action="" method="GET">
<div class="form-group">
<label for="steam_steamid">Steam ID : </label>
<input name="steam_steamid" type="text">
</div><br>
<div class="form-group">
<label for="steam_steamid">Personal Name: </label>
<input name="personaname" type="text">
</div><br>
<div class="form-group">
<label for="steam_steamid">Real Name: </label>
<input name="realname" type="text">
</div><br>
<button type="submit"><img src='https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon#2.png?v=73d79a89bded'></button>
</form>
you can add your src in image tag just copy and paste it in image Tag
Hi so I have a form with 10 fields and I am trying to insert them on an SQL databse through posting them on a PHP page. Connection starts fine, but it returns the error below:
Error: INSERT INTO courses (name, teacher, description, class, DAYONE, DAYTWO, DAYTHREE, STD1, STD2, STD3) VALUES (, , , , , , , , , )
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 ' , , , , , , , , )' at line 1
include_once 'connect.php';
// Create connection
$conn = new mysqli(HOST, USER, PASSWORD, DATABASE);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name = $_POST['name'];
$teacher = $_POST['teacher'];
$description = $_POST['description'];
$class = $_POST['class'];
$dayone = $_POST['dayone'];
$daytwo = $_POST['daytwo'];
$daythree = $_POST['daythree'];
$std1 = $_POST['std1'];
$std2 = $_POST['std2'];
$std3 = $_POST['std3'];
$sql = "INSERT INTO courses (name, teacher, description, class, DAYONE, DAYTWO, DAYTHREE, STD1, STD2, STD3) VALUES ($name, $teacher, $description, $class, $dayone, $daytwo, $daythree, $std1, $std2, $std3)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
I should also mention that the database table has one more field called ID type int(11) which is AUTO_INCREMENT and I expect it to be automatically filled everytime a new row is inserted. Am I wrong?
EDIT: Added HTML code since it has been asked
<form name="registration_form" method="post" class="clearfix" action="create.php">
<div class="form-group">
<label for="name">NAME</label>
<input type="text" class="form-control" id="name" placeholder="Course Name">
</div>
<div class="form-group">
<label for="teacher">Teacher</label>
<input type="text" class="form-control" id="teacher" placeholder="Teacher's Name">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" id="description" placeholder="Description"></textarea>
</div>
<div class="form-group">
<label for="class">Class</label>
<input type="text" class="form-control" id="class" placeholder="Class Name">
</div>
<div class="form-group">
<label for="dayone">Day one</label>
<input type="text" class="form-control" id="dayone" placeholder="Day One">
</div>
<div class="form-group">
<label for="daytwo">Day two</label>
<input type="text" class="form-control" id="daytwo" placeholder="Day Two">
</div>
<div class="form-group">
<label for="daythree">Day three</label>
<input type="text" class="form-control" id="daythree" placeholder="Day Three">
</div>
<div class="form-group">
<label for="std1">std1</label>
<input type="text" class="form-control" id="std1" placeholder="std1">
</div>
<div class="form-group">
<label for="std2">std2</label>
<input type="text" class="form-control" id="std2" placeholder="std2">
</div>
<div class="form-group">
<label for="std1">std3</label>
<input type="text" class="form-control" id="std3" placeholder="std3">
</div>
<div class="checkbox">
<label>
<input type="checkbox">I Understand Terms & Conditions
</label>
</div>
<button type="submit" class="btn pull-right">Create Course</button>
</form>
This should help you identify if the issue is POST variables not being received.
Also a little bit more security.
// create an array of all possible input values
$input_array = array('name', 'teacher', 'description', 'class', 'dayone', 'daytwo', 'daythree', 'std1', 'std2', 'std3');
// create an input array to put any received data into for input to the database
$input_array = array();
include_once 'connect.php';
// Create connection
$conn = new mysqli(HOST, USER, PASSWORD, DATABASE);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// loop through the possible input values to check that a post variable has been received for each.. if received escape the data ready for input to the database
foreach($input_array as $key => $value)
{
if(!isset($_POST[$value])) {
die("no {$value} post variables received");
}
$input_array[$value] = mysqli_real_escape_string($conn, $_POST[$value]);
}
$sql = "INSERT INTO courses (name, teacher, description, class, DAYONE, DAYTWO, DAYTHREE, STD1, STD2, STD3) VALUES ('{$input_array['name']}', '{$input_array['teacher']}', '{$input_array['description']}', '{$input_array['class']}', '{$input_array['dayone']}', '{$input_array['daytwo']}', '{$input_array['daythree']}', '{$input_array['std1']}', '{$input_array['std2']}', '{$input_array['std3']}')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Try:
$sql = "INSERT INTO courses (name, teacher, description, class, DAYONE, DAYTWO, DAYTHREE, STD1, STD2, STD3) VALUES ('".$name."', '".$teacher."', '".$description."', '".$class."', '".$dayone."', '".$daytwo."', '".$daythree."', '".$std1."', '".$std2."', '".$std3."')";
Also, use:
$name = $conn->real_escape_string($_POST['name']);
//etc
Also add name to your form fields:
<input name="class" type="text" class="form-control" id="class" placeholder="Class Name">
For some reason or another the date and time in my date column shows 0000-00-00 00:00:00 when I submit my form to my DB. Only way I can get the date right is by updating it manually. It just started doing it and I'm not sure what I changed. I'm having a real hard time troubleshooting this.
Edit form:
<?php
if(!defined('IN_ADMIN')) exit;
?>
<div class="page">
<h1 class="edit"><?=ucfirst($mode)?> post</h1>
<span class="error-text"><?=$response_text?></span>
<form action="admin.php?mode=<?=$mode?>&id=<?=$post['post_id']?>" method="post">
<p>
<label for="title">Post title:</label><br />
<input type="text" size="80" id="title" name="data[post_title]" value="<?=htmlspecialchars(stripslashes($post['post_title']))?>" />
</p>
<p>
<label for="title">Upload Image:</label><br />
<input type="text" size="80" id="title" name="data[image]" value="<?=htmlspecialchars(stripslashes($post['image']))?>" />
</p>
<p>
<label for="title">Image Alt:</label><br />
<input type="text" size="80" id="title" name="data[image_alt]" value="<?=htmlspecialchars(stripslashes($post['image_alt']))?>" />
</p>
<p>
<label for="title">Post Category:</label><br />
<input type="text" size="80" id="title" name="data[post_category]" value="<?=htmlspecialchars(stripslashes($post['post_category']))?>" />
</p>
<p>
<label for="content">Post Insert:</label><br />
<textarea cols="77" rows="10" id="insert" name="data[post_insert]"><?=htmlspecialchars(stripslashes($post['post_insert']))?></textarea><br />
<span class="form-text">Brief little tid-bit about the article for home page</span>
</p>
<p>
<label for="content">Post content:</label><br />
<script>edToolbar('mytxtarea'); </script>
<textarea cols="77" rows="10" id="mytxtarea" class="ed" name="data[post_content]"><?=htmlspecialchars(stripslashes($post['post_content']))?></textarea><br />
<span class="form-text">To format just use raw HTML.. <strong>, <span>, etc</span>
</p>
<p>
<label for="status">Post status:</label><br />
<select id="status" name="data[published]">
<?=generate_option_list(array('0' => 'Unpublished', '1' => 'Published'), $post['published'])?>
</select>
</p>
<p>
<input class="button" type="submit" name="miniblog_PostBack" value="<?=ucfirst($mode)?>" />
</p>
</div>
That's the form that I use, and here is the index.php that the form is in:
case 'add':
if(isset($_POST['miniblog_PostBack']))
{
$data = $_POST['data'];
$data['post_slug'] = mb_slug($_POST['data']['post_title']);
$data['date'] = time();
$sql ='';
$i = 1;
foreach($data as $field => $value)
{
if($value == '')
{
$failed = true;
break;
}
$fields .= "`" . mysql_real_escape_string($field) . "`";
$values .= "'" . mysql_real_escape_string($value) . "'";
$values .= ($i == sizeof($data)) ? '' : ', ';
$fields .= ($i == sizeof($data)) ? '' : ', ';
$i++;
}
$post = $_POST['data'];
if($failed)
{
$response_text = 'Error: You must fill out all fields';
}
else
{
$result = mysql_query("INSERT INTO `db` ({$fields}) VALUES({$values})");
$response_text = ($result) ? 'Post added' : 'Post could not be added';
}
}
include('edit.php');
break;
$data['date'] = time();
Should be:
$data['date'] = date("Y-m-d H:i:s");
The time() function returns the current time in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
The date() function formats a local date and time (by default the current one), and returns the formatted date string, in this case, in the format MYSQL needs it.
what is the type of the field for the date in your table? you are sending the timestamp as a strIng instead of an integer, perhaps that's the issue, you should also consider taking a look at the NOW() function provided by the mysql engine.
I have the following form:
<h2>Sign the Register</h2>
<form action="sign.php" method="post">
<div><textarea name="firstName" rows="3" cols="60" placeholder="First Name..." required="true"></textarea></div>
<div><textarea name="surname" value="mickey" rows="3" cols="60" placeholder="Surname..." required="true"></textarea></div>
<div><textarea name="course" value="mickey" rows="3" cols="60" placeholder="Your Course..." required="true"></textarea></div>
<div><textarea name="subject" rows="3" cols="60" placeholder="Subject..." required="true"></textarea></div>
<div><textarea name="level" rows="3" cols="60" placeholder="Level: C, I, H, M..." required="true"></textarea></div>
<div><textarea name="date" rows="3" cols="60" placeholder="Date.." required="true"></textarea></div>
<div><textarea name="time" rows="3" cols="60" placeholder="Time.." required="true"></textarea></div>
<div><input type="submit" value="Sign Register"></div>
And sign.php is (the connection is fine):
{
if (array_key_exists('firstName', 'surname', 'course', 'subject', 'level', 'date', 'time', $_POST)) {
$stmt = $db->prepare('INSERT INTO entries (firstName, surname, course, subject, level, date, time) VALUES (:firstName, :surname, :course, :subject, :level, :date, :time)');
$stmt->execute(array(':firstName' => htmlspecialchars($_POST['firstName']),
':surname' => htmlspecialchars($_POST['surname']),
':course' => htmlspecialchars($_POST['course']),
':subject' => htmlspecialchars($_POST['subject']),
':level' => htmlspecialchars($_POST['level']),
':date' => htmlspecialchars($_POST['date']),
':time' => htmlspecialchars($_POST['time'])));
$affected_rows = $stmt->rowCount();
}
}
$db = null;
?>
And when that is executed the user is taken to a following page which has the following:
<?php
try {
// Show existing entries.
foreach($db->query('SELECT * from entries') as $row) {
echo "<div><strong>" . $row['firstName'] . "</strong> wrote <br> " . $row['course'] . "</div>";
}
} catch (PDOException $ex) {
echo "An error occurred in reading or writing to register.";
}
$db = null;
?>
But the problem is that none of the records are showing on the success page. I am using google app engine with cloud SQL database (the connection is fine). It is basically a form, the user fills in the form and then the data is sent to the cloud sql database. Also once the user submits the form, they are taken to a page which displays the information that is just been submitted. Any easier/better ways of doing this are welcome.
Thank you
array_key_exists expects only two parameters (key,array) you should split
if (array_key_exists('firstName', 'surname', 'course', 'subject', 'level', 'date', 'time', $_POST))
into multiple conditions
if(array_key_exists('firstName', $_POST) && array_key_exists('surname', $_POST) ... array_key_exists('time', $_POST))