mysqli insert row id - php

I'm trying to learn PHP & Mysqli and ran into a few problems when trying to echo/print row id (or in this case "ref") as H2 (where it says "FORM").
Also when I add a new row it should get the next id in the database.
I hope that makes sense.
Sorry if this has already been posted. Couldn't find it.
<?php
//server with default setting (user 'root' with no password) */
define('DB_SERVER', 'host');
define('DB_USERNAME', 'user');
define('DB_PASSWORD', '****');
define('DB_NAME', 'database');
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
if (!$link) {
die('could not connect: ' . mysqli_connect_error());
}
$db_selected = mysqli_select_db($link, DB_NAME);
if (!$db_selected) {
die('Cant use ' . DB_NAME . ': ' . mysqli_connect_error());
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$value_1 = $_POST['column_1'];
$value_2 = $_POST['column_2'];
$value_3 = $_POST['column_3'];
$sql = "INSERT INTO maskiner (column_1, column_2, column_3) VALUES ('$value_1', '$value_2', '$value_3')";
if (!mysqli_query($link, $sql)) {
die('ERROR: ' . mysqli_connect_error());
}
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test2</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; }
.wrapper{ width: 350px; padding: 20px; }
</style>
</head>
<body>
<div class="wrapper">
<h2>FORM</h2>
<p>Please fill this form to create an account.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group">
<label>Column_1</label>
<input type="text" name="column_1"class="form-control" value="<?php echo $value_1; ?>">
<span class="help-block"></span>
</div>
<div class="form-group">
<label>Column_2</label>
<input type="text" name="column_2"class="form-control" value="<?php echo $value_2; ?>">
<span class="help-block"></span>
</div>
<div class="form-group">
<label>Column_3</label>
<input type="text" name="column_3"class="form-control" value="<?php echo $value_3; ?>">
<span class="help-block"></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</div>
</form>
</div>
</body>
</html>

I'm not sure to understand properly your problem, but please try to create your table in your database using
CREATE TABLE IF NOT EXISTS `your table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
this way, your ID row will auto increment, and you don't have to feed the value

If i understand you need last insert id. If that true, you sould use fallowing code
$last_id = mysqli_insert_id($link);
Above code gets last inserted increment id.
Note: Your id column in your table, it have to been increment property

If you want to know in advance the next id, you can't use
$next_id = mysqli_insert_id($link)+1;
because when you close mysql connection the next time you use mysqli_insert_id() you get 0.
You can use the query: select max(id)+1 as next_id from maskiner; , but if you delete the last inserted row you'll get a wrong id. To avoid that you can assign next_id in the sql insert statement:
$sql = "INSERT INTO maskiner (id, column_1, column_2, column_3) VALUES ('$next_id','$value_1', '$value_2', '$value_3')";

Related

How to store input given by user in html form in sql using php

This is my PHP code.
<html><head>
<title>login.php</title>
<link rel = "stylesheet" href="login-style.css">
</head>
<body>
<div class = "container">
<div class = "message">
<?php
define('DB_NAME','mydb');
define('DB_USER','root');
define('DB_PASSWORD','');
define('DB_HOST','127.0.0.1');
$link = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
if($link){
die('could not connect:'. mysql_error());
}
$db_selected = mysql_select_db(DB_NAME,$link);
if(!$db_selected){
die('can\'t use'.DB_NAME . ': ' . mysql_error());
}
$value1 = $_POST['name'];
$value2 = $_POST['password'];
$sql = "INSERT INTO Account (username,password) VALUES ('$value1','$value2')";
if(!mysql_query($sql))
{die('ERROR'.mysql_error());
}
mysql_close();
?>
<h1>Thank you for logging in </h1>
<form action = "form.html">
<p class ="submit">
<button type ="submit" >
GO TO FORM
</button>
</p>
</div>
</div>
</body>
</html>
I want to store the data in MySQL but when I run the html code (which i have connected to this php code using action =" name of this file"), no entry is done in database I created, can you tell me what is done wrong and help me to correct it?
<DOCTYPE! html>
<html lang = "en-US">
<head>
<meta charset = "UTF-8">
<title>Sign-In</title>
<link rel = "stylesheet" href ="style-sign.css">
<script type = "text/javascript">
function validateForm(){
var x = document.forms["forma"]["login"].value;
if(x == null || x == "")
{ alert("fill the field ");
return false;
}
var y = document.forms["forma"]["password"].value;
if( y == null || y == "")
{
alert("fill the field");
return false;
}
}
</script>
</head>
<body >
<div class="container">
<div class="login">
<h1>Login</h1>
<form name = "forma" method="post" onsubmit="return validateForm()" action = "login.php">
<p>
<input type="text" name="name" value="" placeholder="Username or Email">
</p>
<p>
<input type="password" name="password" value="" placeholder="Password">
</p>
<p class="submit">
<input type="submit" name="commit" value="Login" >
</p>
</form>
</div>
</div>
</body>
</html>
this is my html code which i have connected to this php file ,I am using xampp and using phpmyadmin , I am not getting any error and apache and mysql both are running
help me with this problem
Change the following:
$sql = "INSERT INTO Account (username,password) VALUES ('$value1','$value2')";
To:
$sql = "INSERT INTO Account (username,password) VALUES ($value1,$value2)";
EDIT:
You do not have input fields setup for the username and password. So POST will not work.
First you From needs an action and a method.
Best woould be to rename the file to form.php
<form action = "form.php" method="POST">
in the result file ...
Connect to the database
$mysqli= #new mysqli('localhost', 'fake_user', 'my_password', 'my_db');
if ($mysqli->connect_errno) {
die('Connect Error: ' . $mysqli->connect_errno);
}
escape your value strings
$query= "INSERT INTO Account (username,password) VALUES ('".$mysqli->real_escape_string($value1)."','".$mysqli->real_escape_string($value2)."')"
Execute query
$result=$mysqli->query($query);
Verify results if any or check if an Error occured
if(!$result) {
$ErrMessage = $mysqli->error . "\n";
$mysqli->close();
die( $ErrMessage) ;
}

MYSQL ERROR when submitting form

Hi I'm having some problems when I'm trying to submit a form of mine, everything seems to look fine on my end but im not quite sure why it's still not working any help would be appreciated.
config.php
<?php
$servername = "localhost";
$username = "release";
$password = "";
$dbname = "release";
// Create connection
$con = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
submit.php
<?php
include('config.php');
$producers = $_POST['producers'];
$company = $_POST['company'];
$title = $_POST['title'];
if(!$producers or !$company or !$title) {
echo 'Please make sure to fill out all required feilds.';
} else {
// Insert into DB
$sql = "INSERT INTO release (id, producers, company, title)
VALUES ('null', '$producers', '$company', '$title')";
}
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}$con->close();
?>
index.php
<html>
<head>
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">
<script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<style>
input[type="text"] {
height: 30px;
}
</style>
<title>RRP ยป Welcome!</title>
</head>
<body>
<div style="width: 1080px; margin-top: 50px;">
<h3>Welcome!</h3>
<h4>You can edit the basic release form info below. <br /> Once done hit the "Submit" button to carry on to the new form!</h4>
<div class="container">
<form class="contact-us form-horizontal" action="submit.php" method="post">
<div class="control-group">
<label class="control-label">Producers</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-user"></i></span>
<input type="text" class="input-xlarge" name="producers" placeholder="Producers(seperate by commas)">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">Production Company</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-globe"></i></span>
<input type="text" class="input-xlarge" name="company" placeholder="Rolling Ridges Productions">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">Title</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-pencil"></i></span>
<input type="text" class="input-xlarge" name="title" placeholder="Desperate Measures">
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="button" class="btn">Cancel</button>
</div>
</div>
</form>
</body>
</html>
error
Error: INSERT INTO release (id, producers, company, title) VALUES ('null', 'lol', 'lol', 'lol')
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 'release (id, producers, company, title) VALUES ('null', 'lol', 'lol', 'lol')' at line 1
Resolved: was as simple as adding ticks to release
release is a MySQL keyword, and should be enclosed in backticks: `release`
try to use backticks in table name if it is keyword release
$sql = "INSERT INTO `release` (id, producers, company, title)
VALUES ('null', '$producers', '$company', '$title')";
Also it is better to write your database in the following format
database name -> db_name eg db_release, and
table name -> tb_name eg tb_release
so as to avoid keywords errors
It seems to me that id should not be assigned the string value 'null'. Typically id columns are auto increment, in which case you should simply omit the column:
$sql = "INSERT INTO `release` (producers, company, title)
VALUES ('".addslashes($producers)."', '".addslashes($company)."', '".addslashes($title)."'";
The addslashes is to protect again SQL injection. You should also sanitize your inputs:
$producers = strval($_POST['producers']);
$company = strval($_POST['company']);
$title = strval($_POST['title']);

How to insert a record in MySQL with PHP with an HTML form

I have created a form in html and I would like that the dataentered in the form is sent to a mysql database in XAMMP. I created the database, the table and the connectivity.php file that manages the connection to the database and data entry, but when I try I get the following error:
"Fatal error: Uncaught Error: Call to undefined function mysql_connect() in C:\xampp\htdocs\example\connectivity.php:8 Stack trace: #0 {main} thrown in C:\xampp\htdocs\example\connectivity.php on line 8"
I post all the code that I wrote. Does anyone know where I'm wrong?
here is the form index.html
<!DOCTYPE HTML>
<html>
<head>
<title>Contact Us</title>
<link rel="stylesheet" type="text/css" href="style.css">
<?php include("connectivity.php"); ?>
</head>
<body>
<div id="contact">
<h3>Contact Us For Any Query</h3>
<form method="POST" action="connectivity.php">
Name
<br>
<input type="text" name="name">
<br> Email
<br>
<input type="text" name="email">
<br> Message
<br>
<textarea rows="10" cols="50" maxlength="100" name="message"></textarea>
<br>
<input type="submit" value="Send Message">
</form>
</div>
</body>
</html>
Then the code used to define database and the table:
CREATE DATABASE practice;
USE practice;
CREATE TABLE contact
(
contactID INT(9) NOT NULL auto_increment,
contactName VARCHAR(40) NOT NULL,
contactEmail VARCHAR(40) NOT NULL,
message VARCHAR(250) NOT NULL,
PRIMARY KEY(contactID)
);
Finally the connectivity.php file:
<?php
//connecting to the database
define('DB_HOST', 'localhost');
define('DB_NAME', 'practice');
define('DB_USER','root');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
//inserting Record to the database
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$query = "INSERT INTO contact(contactName,contactEmail,message)VALUES('$name','$email','$message')";
$result = mysql_query($query);
if($result)
{
echo "Successfully updated database";
}
else
{
die('Error: '.mysql_error($con));
}
mysql_close($con);
?>
P.S: I installed the latest version of XAMMP (5.6.15)
$con=mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD,##TABLE NAME##) or die("Failed to connect to MySQL: " . mysql_error());
$query = "INSERT INTO contact(contactName,contactEmail,message)VALUES('$name','$email','$message')";
$result = mysqli_query($con,$query);
If you are using one of the latest version of xampp therefore you have to use PDO or MySQLi .
Your have to change your codes to something like this.
Your connectivity page
<?php
$db = new PDO('mysql:host=localhost;dbname=practice;charset=utf8',
'root',
'',
array(PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
?>
<?php
if (isset($_POST['name'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$stmt = $db->prepare("INSERT INTO `contact` (contactName,contactEmail,message)
VALUES (:name, :email, :message)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':message', $message);
$stmt->execute();
echo 'added';
}
?>
Your home page
<!DOCTYPE HTML>
<html>
<head>
<title>Contact Us</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="contact">
<h3>Contact Us For Any Query</h3>
<form method="POST" action="connectivity.php">
Name
<br>
<input type="text" name="name">
<br> Email
<br>
<input type="text" name="email">
<br> Message
<br>
<textarea rows="10" cols="50" maxlength="100" name="message"></textarea>
<br>
<input type="submit" value="Send Message">
</form>
</div>
</body>
</html>
Hope this helps
Firts you see your phpinfo:
<?php
phpinfo();
?>
Then see in here , php_mysql is enabled or disabled?
If there not php_mysql, change php.ini file:
Uncomment extension=php_mysql.dll

PHP POST and GET in same statement

I've found similar questions, but have been unable to tie them into my example. I am very new to PHP and completely self teaching.
At present I have a form for entering a new customer. In that form I want the user to be able to select an existing DB item (business) and insert that BusinessID into the CUSTOMER table. My problem is that I can GET the BusinessID, but then I can't POST that same ID with the other field inputs. Code below
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>New Contact</title>
<!--Declare CSS and JavaScript-->
<link rel="stylesheet" type="text/css" href="RealtyCRM_Style.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="jquery.resmenu.min.js"></script>
</head>
<body>
<script>
$(document).ready(function () {
$('.toresponsive').ReSmenu();
});
</script>
<!--Begin Header Code-->
<!--Begin Header Code-->
<div class="BodyHeader">
<div>
</div>
</div>
<!--Begin Menu Code-->
<div class="menu_container" style="position:relative; z-index:11;">
<ul class="toresponsive">
<li>Log In</li>
<li>Contact</li>
<li>News</li>
<li class="current-menu-item">Dashboard
<ul>
<li>Add New Data</li>
<li>Update Data</li>
<li>Search</li>
<li>Report</li>
<li>Admin Page</li>
<li>Log Interaction</li>
</ul>
</li>
</ul>
</div>
<br>
<!--Begin Dashboard Buttons Code-->
<div class="DashboardButtonsTop">
<h1 class="centeredDashBoardButtonInactive">New Retailer</h1>
<h1 class="centeredDashBoardButton">New Contact</h1>
<h1 class="centeredDashBoardButtonInactive">New Property</h1>
</div>
<hr style="width:700px; height:5px;">
<br>
<br>
<!--END Dashboard Buttons Code-->
<?php
if(isset($_POST['add']))
{
$dbhost = 'localhost';
$dbuser = 'leasingl_dbwrite';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() )
{
$contactFirstName = addslashes ($_POST['contactFirstName']);
$contactLastName = addslashes ($_POST['contactLastName']);
}
else
{
$contactFirstName = $_POST['contactFirstName'];
$contactLastName = $_POST['contactLastName'];
}
$contactPhoneNumber = $_POST['contactPhoneNumber'];
$contactEmail = $_POST['contactEmail'];
$Business = $_POST['BusinessID'];
$sql = "INSERT INTO Contact ". "(ContactFName,ContactLName, ContactMobilePhone, contactEmail, BusinessID, CreatedDate) ". "VALUES('$contactFirstName','$contactLastName','$contactPhoneNumber', '$contactEmail', '$Business', NOW())";
mysql_select_db('applicationDatabase');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "<div style='text-align:center;'>Entered data successfully\n</div>";
echo "<br><div><a href='contactdataentry.php' class='redirectButton'>Add More Contacts</a>\n</div>";
echo "<br><div><a href='dashboard.php' class='redirectButton'>Return to Dashboard</a></div>";
mysql_close($conn);
}
else
{
?>
<div class="Form_container">
<form method="post" action="<?php $_PHP_SELF ?>">
Contact First Name<br>
<input class="largeInput" type="text" name="contactFirstName" ID="contactFirstName"><br>
Contact Last Name<br>
<input class="largeInput" type="text" name="contactLastName" ID="contactLastName"><br>
Contact Phone Number<br>
<input class="largeInput" type="text" name="contactPhoneNumber" placeholder="### - ### - ####" ID="contactPhoneNumber"><br>
Contact Email<br>
<input class="largeInput" type="text" name="contactEmail"><br>
Business<br>
<?php
$servername = "localhost";
$username = "leasingl_dbread";
$password = "password";
$dbname = "applicationDatabase";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT RetailerID, RetailerName FROM Retailer ORDER BY RetailerName DESC";
$result = $conn->query($sql);
?>
<select style='text-align:center;' class='largeInput' name='Business' ID='Business'>
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='". $row["RetailerID"]. "'>" . $row["RetailerName"]. " - " . $row["RetailerID"]. "</option><br><br>";
}
} else {
echo "0 results";
}
?>
</select><br><br>
<?php
$conn->close();
?>
<input name="add" type="submit" id="add" value="Add Contact" class="button">
</form>
<br>
<hr style="width:400px; height:10px;">
</div>
<?php
}
?>
</body>
</html>'
So being able to insert the value from my drop down is the main issue. Additionally, I'm sure there is unnecessary / incorrect code in what I posted, I've been piecing together examples one at a time.
Thank you for all the help, if I can get this working I can have a functioning basic version of my application
EDIT
I have successfully prepopulated my drop down, and the user then chooses from that list. I want to pass that choice via my INSERT statement. I worry that the two different CONNECTIONS which I establish are part of the reason my INSERT won't recognize $Business
It appears you are referring to GET in a confusing way. In PHP there is $_GET and $_POST variables, and when you mention GET in all-caps, in implies you are using $_GET - which in fact you are not.
The solution - as I understand the question - is actually fairly straightforward.
Inside your form, add a hidden input that stores (and then passes) the BusinessID variable, like so:
<input type="hidden" name="BusinessID" value="<?php echo $Business; ?>">
As you mention you are just learning, here's some additional tips:
Name your variables consistently throughout. If the name of the database column is BusinessID, then name your variable $businessID" and your inputBusinessID".
Kudos to you for good indenting / formatting! That will save you gobs of time when troubleshooting / reading your own code!
EDIT
If what you are trying to do is pre-select the record in the dropdown, then alter your loop like so:
while($row = $result->fetch_assoc()) {
// Note: I've removed the <br> tags here, they don't belong in a select dropdown
echo "<option value='". $row["RetailerID"]. "'";
// If the ID matches, make this the selected option
// NOTE: Per my tip above, I'd strongly recommend changing the variable name $Business to match the field name - $RetailerID in this case
echo ($row['RetailerID'] == $Business) ? ' selected' : '';
echo ">" . $row["RetailerName"]. " - " . $row["RetailerID"]. "</option>";
}

HTML will not connect to PHP

I am new working on a project that has me connecting a database and a webpage and before doing the official database, I wanted to test a basic database.
I test to make sure everything is working by using phpMyAdmin. I can tell that I formed SOME kind of connection between my html and php, but that's where the issue is. whenever I press the submit button on my site, instead of getting a message telling me that everything works, I instead get a white page with all of my php code. I have tried making sure all my syntax is correct and all the variables are labeled correctly, but nothing is going through.
<!DOCTYPE php>
<?php
define('DB_NAME', 'training');
define('DB_USER', 'root');
define('DB_PASSWORD', '********');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!link){
die('Could not connect: ' .mysql_error);
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!db_selected){
die('Error: ' .mysql_error());
}
$Name = $_POST=['name'];
$Job = $_POST['job'];
$sql = "INSERT INTO employee (name,job) VALUES ('$Name', '$Job')";
if (!mysql_query($sql)){
die('Error: ' .mysql_error());
}
echo 'Success!';
mysql_close();
?>
<!DOCTYPE html>
<html>
<h1 style="text-align:center">Undergrad Sign-up</h1>
<style>
#body {background-color:#001b38;}
</style>
<body id="body" style="color:white;text-align:center" >
<form action="DBconnect.php" method="post" />
Name<br>
<input type="text" name="name" maxlength=20 required/>
<br>
Job<br>
<input type="text" name="job" maxlength=20 required/>
<br>
<button type="submit" value="submit">Submit</button>
</form>
</body>
</html>

Categories