inserting data into database using php - php

<?php
$con = mysqli_connect("localhost", "root", "" , "prosports1");
if(!isset($con)) {
die("Connection failed !!!");
}
if(isset($_POST['send'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$contact = $_POST['contact'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$query = "INSERT INTO review VALUES
('','$name','$email','$contact','$subject','$message')";
$res = mysqli_query($con,$query);
if(isset($res)) {
//header("Location: homepage.php");
}
}
?>
i have used this code to insert the data to database[phpmyadmin]
but it's not working
what to do

The following is an example code for POST method. It worked for me. Follow the pattern, there isn't much of any change from your code.
<form action="new.php" method="post">
ID:<input type="text" name="id">
Name:<input type="text" name="name">
age:<input type="text" name="age">
place:<input type="text" name="city">
<input type="submit" value="submit" name="submit">
</form>
<?php
if(isset($_POST['submit']))
{
$con = mysqli_connect("localhost", "username", "password","db_name");
$sql = "INSERT INTO employee VALUES ('$_POST[id]','$_POST[name]','$_POST[age]','$_POST[city]')";
mysqli_query($con,$sql);
echo "Data Inserted<br>";
mysqli_close($con);
}
?>
Don't forget to change the action page and essential details. Cheers.

INSERT into TABLE (column1, column2, ...) VALUES (value1, value2, ...)

Use this
if ($con->query($query) === TRUE) {
echo "Record Successfully<br>";
}

write query in this way.
$query = "INSERT INTO review (column1 , column2 , column3 , column4 , column5 , column6) VALUES ('','$name','$email','$contact','$subject','$message')";
if(isset($res)) {
//header("Location: homepage.php");
}
replace column names with your table attributes.

Related

POST method not inserting data into database table

I'm trying to play around with databases and inserting data dynamically with php.
At the moment I have a form with 'post' method and everything seems logical to me but it isn't inserting the data into the table.
Code is attached below, would appreciate if someone could point me into the right direction.
index.php:
<form action="index.php" method="post">
<label for="name">Name</label>
<input type="text" name="name" required>
<label for="breed">Breed</label>
<input type="text" name="breed">
<label for="age">Age</label>
<input type="text" name="age">
<input type="submit" name="submit" value="Submit">
</form>
<?php
require "connect.php";
if('submit') {
$name = $_POST['name'];
$breed = $_POST['breed'];
$age = $_POST['age'];
$newdog = mysqli_query('INSERT INTO `dogs`(`name`, `breed`, `age`) VALUES ([$name],[$breed],[$age)');
if ($newdog) {
echo "$name has been added to the database";
} else {
echo "$name has not been added to database.";
};
};
?>
connect.php:
<?php
$connect = mysqli_connect('localhost', 'max', 'password', 'db_test');
?>
<?php
require "connect.php";
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$breed = $_POST['breed'];
$age = $_POST['age'];
$newdog = mysqli_query($connect, 'INSERT INTO dogs(name, breed, age) VALUES ("'.$name.'","'.$breed.'","'.$age.'")');
if ($newdog) {
echo "$name has been added to the database";
} else {
echo "$name has not been added to database.";
};
};
?>
Change if('submit') {
TO
if(isset($_POST['submit'])){//check if it is set
}
Also change this line:
$newdog = mysqli_query('INSERT INTOdogs(name,breed,age) VALUES ([$name],[$breed],[$age)');
TO
$newdog = mysqli_query($connect, 'INSERT INTOdogs(name,breed,age) VALUES ($name,$breed,$age)');//remove square bracktes and add connection variable
Your code is very well vulnerable to SQL injection
Using prepared statements,
$stmt = $connect->prepare("INSERT INTO dogs (`name`, `breed`, `age`) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $name, $breed, $age);
if($stmt->execute() == true){
echo 'Saved';
} else {
echo 'Error '. $stmt->error;
}
Own answer: Figured it out, I had to configure PHPStorm to use MAMP Apache server instead of the internal server since that one apparently doesn't like $_POST[] requests

When added 3 fields to the MySQL it didn't show some fields

I have added 3 fields to MySQL, but it have shown only "feedback" value, other were empty.
Here is my code:
$name = $_POST['name'];
$email = $_POST['email'];
$feedback = $_POST['feedback'];
if (mysql_query("INSERT INTO `feedback` (`name`, `email`, `feedback`) VALUES ('".mysql_real_escape_string($name)."','".mysql_real_escape_string($email)."','".mysql_real_escape_string($feedback)."')")) {
echo 'Success!';
} else {
echo mysql_error();
exit;
}
<form action="ajax.php" method="post" class="postcard">
<textarea type="text" value="" id="theMessage" name="feedback" required></textarea>
<input type="text" id="input2" name="name">
<input type="text" id="input3" name="email">
</form>
Got my name field - TEXT(30), email and feedback - VARCHAR
You can try this code:
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$feedback =mysql_real_escape_string($_POST['feedback']);
if (mysql_query("INSERT INTO `feedback` (`name`, `email`, `feedback`) VALUES ('$name','$email', '$feedback')")) {
echo 'Success!';
} else {
echo mysql_error();
exit;
}
Also you check your field length. If your value length more than field length may be fail to insert.
Try without quotation marks.
"INSERT INTO `feedback` (name, email, feedback) VALUES ('".mysql_real_escape_string($name)."','".mysql_real_escape_string($email)."','".mysql_real_escape_string($feedback)."')"))

How do I do a PHP insert for two or more separate MySQL tables

The HTML:
<html>
<?php include 'C:\xampp\htdocs\paxdb\head.php';
include 'config/menu.php';?>
<div id="dataentry">
<!--This section is the demographic text field area-->
<form method="post" action="dataentered.php">
First Name: <input type="text" name="First_Name"/></br>
</br>
Last Name: <input type="text" name="Last_Name"/></br>
</br>
E-mail: <input type="text" name="email"/></br>
</br>
<!--This section is the age range checkbox selection area-->
<p><u><b>Age Range</b></u></p>
<input type="checkbox" name="age[]" id="20-25" value="20-25"/> 20-25</br>
<input type="checkbox" name="age[]" id="26-30" value="26-30"/> 26-30</br>
<input type="checkbox" name="age[]" id="31-35" value="31-35"/> 31-35</br>
</div>
<div id="checkboxes">
</div>
<!--This section is the trips take checkbox area-->
<div id="tripstodatetype">
<p><u><b>WHAT TYPE OF TRIPS TO DATE HAVE YOU TAKEN?</b></u></p>
<input type="checkbox" name="trip2date[]" id="Bus" value="Bus"> Bus </br>
<input type="checkbox" name="trip2date[]" id="Car" value="Car"> Car</br>
<input type="checkbox" name="trip2date[]" id="Weekend fly-in" value="Weekend fly-in"> Weekend fly-in </br>
</div>
<div id="tripstodateborder">
</div>
<!--This section is the type of trip client likes best checkbox area-->
<div id="triplikebest">
<p><u><b>WHAT TYPE OF TRIP DO YOU LIKE BEST?</b></u></p>
<input type="checkbox" name="triplikebest[]" value="Bus"> Bus </br>
<input type="checkbox" name="triplikebest[]" value="Car"> Car</br>
<input type="checkbox" name="triplikebest[]" value="Weekend fly-in"> Weekend fly-in </br>
</div>
<div id="triplikeborder">
</div>
and the PHP:
<html>
<?php
include 'head.php';
include 'config/menu.php';
$host="localhost";
$username="somename";
$password="somepass";
$dbname="pax";
$dbc = mysql_connect($host, $username, $password, $dbname);
if (!$dbc)
{
die('Error connecting to MySQL server' . mysql_error());
}
mysql_select_db($dbname, $dbc);
$first_name = mysql_real_escape_string($_POST['First_Name']);
$last_name = mysql_real_escape_string($_POST['Last_Name']);
$email = mysql_real_escape_string($_POST['email']);
$age = $_POST['age'];
$my_range = "";
foreach($age as $range) {
$my_range = $my_range . mysql_real_escape_string($range) . ", ";
}
$trip2date = $_POST['trip2date'];
$my_triprange = "";
foreach($trip2date as $triprange) {
$my_triprange = $my_triprange . mysql_real_escape_string($triprange) . ", ";
}
mysql_query("INSERT INTO `pax` (`First_Name`, `Last_Name`, `email`, `age`,`trip2date`)
VALUES('$first_name','$last_name','$email', '$my_range','$my_triprange')")
or die(mysql_error());
mysql_close($dbc);
?>
<div class = "entered">
<p>Success! Your Data Has Been Submitted. Please click on <b>'DATA ENTRY'</b> above to enter another. </P>
</div>
<?php include 'footer.php';?>
</div>
</div>
</body>
</html>
If I were to put the triprange data into a separate table, how would I convert the INSERT query to perform the insert into the new table? (let's say the new/second table is called 'trip'). -OR- Does it make more sense to use a second INSERT query here? If so, how should it appear to remain connected to the first table/ID
thank you in advance.
looking at your code, are you trying to enter the same data twice into different tables?
if not you should make your query a variable, so the line would read something like this...
$query1 = mysql_query("INSERT INTO `pax` (`First_Name`, `Last_Name`, `email`, `age`,`trip2date`)
VALUES('$first_name','$last_name','$email', '$my_range','$my_triprange')")
or die(mysql_error());
you could look into repeating the insert statement for another table but use the same variables declared in the original code.
if i am on the wrong lines, could you maybe explain a little more?
mysqli_multi_query();
Read the manual here: http://php.net/manual/en/mysqli.multi-query.php
EDIT:
<?php
/* connection conf */
// use p: if you want to have a persistent connection
// this will improve the speed and resource usage of opening a connection
$host = "p:localhost";
$username = "somename";
$password = "somepass";
$dbname = "pax";
/* make connection */
$lnk = mysqli_connect($host, $username, $password, $dbname);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* prepare variables */
$first_name = mysqli_real_escape_string($_POST['First_Name']);
$last_name = mysqli_real_escape_string($_POST['Last_Name']);
$email = mysqli_real_escape_string($_POST['email']);
$age = $_POST['age'];
$my_range = "";
foreach($age as $range) {
$my_range = $my_range . mysqli_real_escape_string($range) . ", ";
}
$trip2date = $_POST['trip2date'];
$my_triprange = "";
foreach($trip2date as $triprange) {
$my_triprange = $my_triprange . mysqli_real_escape_string($triprange) . ", ";
}
/* execute query */
mysqli_query($lnk, "INSERT INTO `pax` (`First_Name`, `Last_Name`, `email`, `age`,`trip2date`) " .
"VALUES('$first_name','$last_name','$email', '$my_range','$my_triprange');"
);
/* execute multi query INSERT */
mysqli_multi_query($lnk, "INSERT INTO `pax` (`First_Name`, `Last_Name`, `email`, `age`,`trip2date`) " .
"VALUES('$first_name','$last_name','$email', '$my_range','$my_triprange');"
"COMMIT;"
);
/* execute multi query SELECT */
$query = "SELECT CURRENT_USER();";
$query .= "SELECT `email` FROM `pax` ORDER BY `id` LIMIT 5";
if (mysqli_multi_query($lnk, $query)) {
do {
/* store first result set */
if ($result = mysqli_store_result($lnk)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);
}
mysqli_free_result($result);
}
/* print divider */
if (mysqli_more_results($lnk))
printf("-----------------\n");
} while (mysqli_next_result($lnk));
}
/* close conenction */
mysqli_close($dbc);
// I used your code and some samples from the PHP manual.
// Hope this piece of code helps you and others to understand mysqli better.
// Thanks to PHP for having the best manual.
?>

SQL Query doesn't get executed

I'm trying to make a very basic comment system in PHP.
The problem is that when I submit the form, the new row doesn't get inserted in my MySQL table.
This is my code (, could someone please check what's wrong?):
<?php
$act = $_POST['act'];
if($act == 1) {
$m = $_POST['message'];
$m = strip_tags($m);
$message = mysql_real_escape_string($m);
$name = "Anonymous"; //Static username for demonstration purposes
$date = "2012-7-28"; //Static date for demonstration purposes
$con = mysql_connect("localhost","username","password");
if (!$con){die('Could not connect: ' . mysql_error());}
mysql_query("INSERT INTO comments (name, message, date) VALUES ('$name', '$message', '$date')");
mysql_close($con);
}
?>
<form action="comments.php" method="post">
<input type="text" name="message">
<input type="hidden" name="act" value="1">
<input type="submit" name="submit" value="Submit">
</form>
I think your problem rests with the escaping, or rather the 'non-escaping' of the column names. Did you know that 'date' is a function name in mySQL?
Try putting all table and column names in backticks.
mysql_query("INSERT INTO `comments` (`name`, `message`, `date`) VALUES ('$name', '$message', '$date')");
Also, for further reference, posting the error message never hurts looking for the answer.
Other than that, I can't find anything particularly wrong with your query.
Edit: DUH! I missed something obvious.
Please execute 'mysql_select_db('name_of_database'); prior to the query.
Otherwise it won't know where to look for the table you're specifying.
For the sake of completeness (as Michael Besteck pointed out), it is necessary to execute 'mysql_real_escape_string' only AFTER the connection has been established.
That is, because the 'escape_string' relies on the encoding of the connection to determine which characters need to be escaped and how.
It is neccessary to first establish the database connection because the escape function is executed my mysql.
$con = mysql_connect("localhost","username","password");
$message = mysql_real_escape_string($m);
Run the script with this code and post mysql_error
<?php
$act = $_POST['act'];
if($act == 1) {
$m = $_POST['message'];
$m = strip_tags($m);
$message = mysql_real_escape_string($m);
$name = "Anonymous"; //Static username for demonstration purposes
$date = "2012-7-28"; //Static date for demonstration purposes
$con = mysql_connect("localhost","username","password");
if (!$con){die('Could not connect: ' . mysql_error());}
mysql_query("INSERT INTO comments (name, message, date) VALUES ('$name', '$message', '$date')") or die(mysql_error());
mysql_close($con);
}
?>
<form action="comments.php" method="post">
<input type="text" name="message">
<input type="hidden" name="act" value="1">
<input type="submit" name="submit" value="Submit">
</form>
UODATE>
The working code is follows:
<?php
$act = $_POST['act'];
if($act == 1) {
$m = $_POST['message'];
$m = strip_tags($m);
$message = mysql_real_escape_string($m);
$name = "Anonymous"; //Static username for demonstration purposes
$date = "2012-7-28"; //Static date for demonstration purposes
$con = mysql_connect("localhost","username","password");
mysql_select_db('databasename');
if (!$con){die('Could not connect: ' . mysql_error());}
mysql_query("INSERT INTO comments (name, message, date) VALUES ('$name', '$message', '$date')") or die(mysql_error());
mysql_close($con);
}
?>
<form action="comments.php" method="post">
<input type="text" name="message">
<input type="hidden" name="act" value="1">
<input type="submit" name="submit" value="Submit">
</form>

register system with php/mysql: can 't find user

i am new in php/mysql and sorry if my question is silly. I am trying to make a register/login/logout system with php and mysql. My skills are not good and i am not a programmer, so i tried to change a script that i found on the web. It contains files, index.php, activate php. login.php, logout.php, register.php.
It worked great when I tried the example given, but i changed the code quite a bit because I wanted the user to add more values in register like first name, last name etc and not just username, password and email. So I changed the code and added more columns on the mysql database. Now it won t work, it says that can 't find user when i try to activate and i also can 't log in.
index.php: is a very simple file that has an html form and asks unknown user if he wants to login or register and also starts a session
logout.php: simply unsets session
login.php:
<?php session_start(); ?>
<html>
<body>
<?php
if(isset($_POST["user"])){
$con = mysql_connect("localhost","root","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("myapp", $con);
$sql = "SELECT * FROM `users` WHERE `user` LIKE '". mysql_real_escape_string($_POST["user"])
."' AND ".
"`pass` LIKE MD5('". mysql_real_escape_string($_POST["pass"])
."') AND ".
"`active` = 'DONE'";
$result = mysql_query($sql);
$found = 0;
while ($row = mysql_fetch_array($result)) {
if ($row[1]==$_POST["user"]) {
$found = 1;
}
}
if ($found) {
$_SESSION["USER"] = $_POST["user"];
?>Thank you for logging in<?
}
else {
?>User/Pass is wrong!<?
}
mysql_close($con);
}
else {
?>
Please log-in:<br/>
<form action="login.php" method="POST">
User: <input type="text" name="user"><br />
Pass: <input type="password" name="pass"><br />
<input type="submit" />
</form>
<?php
}
?>
register.php:
<?php session_start(); ?>
<html>
<body>
<?php
if(isset($_POST["user"])){
$con = mysql_connect("localhost","root","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("myapp", $con);
$random = rand();
$sql = "INSERT INTO `myapp`.`users` (`id`, `user`, `pass`, `active`, `firstname`, `lastname`, `mail`) ".
" VALUES (NULL, '". mysql_real_escape_string($_POST["user"])
."', MD5('".mysql_real_escape_string($_POST["pass"])
."'), '".mysql_real_escape_string($random)
."'), '".mysql_real_escape_string($_POST["firstname"])
."'), '".mysql_real_escape_string($_POST["lastname"])
."')'".mysql_real_escape_string($_POST["mail"])
."');";
mysql_query($sql);
mysql_close($con);
$message = "Please put this url http://localhost/mypage/activate.php?active=" . $random . " in your browser to activate your account.";
#mail($_POST["mail"], 'Thank you for registering', $message);
?>Thank you <?php echo $_POST["user"]; ?> we send you a confirmation e-mail in <?php echo $_POST["mail"]; ?><?php
echo $message;
}
else {
?>
Please register:<br/>
<form action="register.php" method="POST">
User: <input type="text" name="user"><br />
Pass: <input type="password" name="pass"><br />
firstname:<input type="text" name="firstname"><br />
lastname:<input type="text" name="lastname"><br />
mail: <input type="text" name="mail"><br />
<input type="submit" />
</form>
<?php
}
?>
activate.php:
<?php session_start(); ?>
<html>
<body>
<?php
if(isset($_GET["active"])){
$con = mysql_connect("localhost","root","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("myapp", $con);
$sql = "SELECT * FROM `users` WHERE `active` LIKE '".
mysql_real_escape_string($_GET["active"])."'";
$result = mysql_query($sql);
$found = 0;
while ($row = mysql_fetch_array($result)) {
$found = 1;
}
if ($found) {
$sql = "UPDATE `users` SET `active` ='DONE'";
$result = mysql_query($sql);
?>Thank you for activating<?
}
else {
?>Can't find user!<?
}
mysql_close($con);
}
else {
?>Invalid activation<?php
}
?>
</body>
</html>
any help would be welcome, thank you and sorry for the long post!! ^_^
In register.php, you have an error in the SQL syntax, you have too many closed parentheses.
Replace this part like this:
$sql = "INSERT INTO `myapp`.`users` (`id`, `user`, `pass`, `active`, `firstname`, `lastname`, `mail`) VALUES
(NULL,".
"'". mysql_real_escape_string($_POST["user"])."',".
"MD5('".mysql_real_escape_string($_POST["pass"])."'),".
"'".mysql_real_escape_string($random)."',".
"'".mysql_real_escape_string($_POST["firstname"])."',".
"'".mysql_real_escape_string($_POST["lastname"])."',".
"'".mysql_real_escape_string($_POST["mail"])."');";

Categories