Well I am pretty much trying to create database with some table, the values in the table and check them in phpMyAdmin. I am able to create the table and database, but not the values
2.) when I add the isset $_post['submit'] variable, when I click the submit button, nothing is getting created. Is there a syntax error I am not seeing?
<html>
<body>
<p> welcome to my Page
Please insert the data below
<br>
<br>
<form action="input.php" method="post">
<p> Name: <input type="text" name="name">
<p> Age: <input type="text" name="age">
<p> Address: <input type="text" name="address">
<p> Email: <input type="text" name="email">
<input type="submit" value="Send!" name="submit">
</form>
<?php
if(isset($_POST['submit'])){
//connects to the sql database
$con = mysql_connect("localhost", "willc86", "tigers330");
if (!$con) {
echo 'can not connect to Database' . "<br>";
}
//creates the database in mySQL
$db = mysql_query("CREATE DATABASE form");
if (!$db) {
echo 'Did not create database';
}
//select the database and connect to it. on where you want to create tables.
mysql_select_db("form", $con);
//create the table once "form database" is selected
$table = "CREATE TABLE users (
Name varchar(30),
Age varchar(30),
Address varchar(30),
Email varchar(30)
)";
mysql_query($table,$con);
//insert the data from the form
$value= "INSERT INTO users (Name, Age, Address, Email)
VALUES ('$_POST[name]','$_POST[age]','$_POST[address]','$_POST[email]')";
mysql_query($value,$con);
mysql_close();
}//end of submit
?>
</body>
</html>
Your form action is input.php, is your file called input.php as well? Otherwise you'd be executing input.php when you're submitting the form instead of executing the PHP on your page.
I think user willc86 don't have access rights for create databases.
In second your script is incorrect, because it run for each "user add" operation and tried create database and table.
You can create it once in phpadmin and use in your script only insert.
No point in highlighting particular errors here as others are unlikely to have the exact same issue. Better to just give you the tools/means to debug the issue for yourself.
Instead of:
mysql_query($table,$con);
Try:
$res = mysql_query($table,$con);
if($res === false){
throw new Exception(mysql_error($conn));
}
Better yet, use PDO.
First of all your code is fine if this file name is input.php. There can be few reasons, one that you have incorrect credentials second that the user does not have a right to create table, for that go to Phpmyadmin and give user all rights.
Secondly and most importantly, use Prepared statements or mysqli otherwise you are vulnerable to SQL Injection
For that do go through this post
How can I prevent SQL injection in PHP?
Related
Im trying to send form data to my sql database but the database isn't receiving any of my values. The name of my database is taxibooking and table name is bookings.
I tried separating the php code in another file and using action on form to access the php code. on clicking submit I was redirected to a blank page with my php file name.
<form method="POST" action="">
Name of customer:<input type="text" name="fname"><br><br>
Enter pickup address:<textarea name="padd" rows="5" cols="10"></textarea><br><br>
Enter destination address:<textarea name="dadd" rows="5" cols="10"></textarea><br><br>
Select Taxi type:<select name="taxi"><option value="Viennese Fiaker">The Viennese Fiaker</option><option value="Indian Auto Rickshaw">Indian Auto Rickshaw</option><option value="Little Yellow">Little Yellow</option><option value="Mumbai Taxi Fiat">Mumbai Taxi Fiat</option><option value="Tricycles">Tricycles</option><option value="Water Taxi">Water Taxi</option><option value="Impeccable Taxi">Impeccable Taxi</option><option value="Red Taxi">Red Taxi</option></select><br><br>
<input type="submit" value="submit" name="sub">
</form>
<?php
$con=mysqli_connect("localhost","root","","taxibooking");
if(isset($_POST['sub']))
{
$n=$_POST['fname'];
$p=$_POST['padd'];
$d=$_POST['dadd'];
$type=$_POST['taxi'];
$sql="insert into bookings(name,pickup,destination,type) values ('$n','$p','$d','$type')";
mysqli_query($con,$sql);
}
?>
Try to debug and put query on if condition
if(mysqli_query($con,$sql)){
echo'done';
}else{
echo "error".$sql."</br>" . mysqli_error($con);
}
Here's how to add parameters on your insert script.
$sql="insert into bookings(name,pickup,destination,type) values ('".$n."','".$p."','".$d."','".$type."')";
I made a new database with a different name with the same table name and properties and now it sort of mysteriously works now. No changes done to the code.
I am currently working on a form that uses PHP and SQL to update information in a database. It is functioning properly and updating the information but the issue is... is that it updates everything, including fields that I didn't even put any input in which means it will only update a particular row in the database and leave the others blanks... I need it to just change information from a field with an actual input and leave it if there is no input.
Here is the PHP and SQL code:
try {
$deleteRecId = $_GET['id'];
$update_event_name = $_POST['updateName'];
$update_event_location = $_POST['updateLocation'];
$update_event_date = $_POST['updateDate'];
include 'connect.php';
if(isset($_POST["submit"])) {
// new data
$sql = "UPDATE events SET event_name='$update_event_name',
event_location='$update_event_location', event_date='$update_event_date'
WHERE event_id=$deleteRecId";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
and here if the form:
<form class="update-form" action="<?php echo $_PHP_SELF ?>" method="post">
<p id="input-headers">Event Name</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateName" value="">
</p>
<p id="input-headers">Event Location</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateLocation" value="">
</p>
<p id="input-headers">Event Date</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateDate" value="" placeholder="01/01/2000">
</p>
<input type="submit" name="submit" value="Submit" id="updateBtn">
</form>
So to sum up I need this application to only update information of a field with an actual input and if the form field has no input I need that database info to remain the same. I appreciate any help with this as I am pretty new to these concepts... thanks!
I found a really handy solution to this! Here is how I implemented it into my code.
$sql = "UPDATE events SET event_name=IF(LENGTH('$update_event_name')=0, event_name, '$update_event_name'), event_location=IF(LENGTH('$update_event_location')=0, event_location, '$update_event_location'), event_date=IF(LENGTH('$update_event_date')=0, event_date, '$update_event_date') WHERE event_id=$deleteRecId";
It basically just checks whether the string is empty or not. If it's empty it won't be updated. If it isn't empty it'll go through with the update! Very simple way to achieve this effect when creating an update form.
Using your current code structure, you can do this.
Use SQL to select * from event ID. Populate your update_event_xxx with the parameters.
If $_POST[xx] is blank, ignore. Else, update_event_xx = $_POST[xx]
I am trying to add an "admin" section of my website. Right now I am working on a section to add a new row to my MySQL database.
The first file is my admin.php:
<html>
...
<body>
<form action="add.php" method="post">
<input type="text" name="order" />
<input type="text" name="newstatus" />
<input type="submit" value="Add" />
</form>
</body>
</html>
My goal here is to add 2 pieces of data (the table only has 2 columns right now) to the new row.
Then, I have my add.php file:
<?
//declare my connection variables - I'll move these to a secure method later
mysql_connect($servername, $username, $password) or die (mysql_error ());
// Select database
mysql_select_db($dbname) or die(mysql_error());
// The SQL statement is built
$sql="INSERT INTO $tblname(id, status)VALUES('$order', '$newstatus')";
$result=mysql_query($sql);
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='admin.php'>Back to main page</a>";
}
else {
echo mysqli_errno($this->db_link);
}
?>
<?php
// close connection
mysql_close();
?>
Anytime i input any data (non-duplicate of what is already in the table), it gives me an error. If I clear my table completely of all data, it will input once. I am getting a duplicate key error, but my key should be "orders", which is unique every time I input it.
Suggestions?
If you are actually inserting a new row, you shouldn't fill the ID yourself but rather set it as AUTO_INCREMENT in your database. And then, have you form as such:
<form action="add.php" method="post">
<input type="text" name="newstatus" />
<input type="submit" value="Add" />
</form>
And your PHP code like so:
$newstatus = mysql_real_escape_string($_POST['newstatus']); // note the usage of $_POST variable
$sql="INSERT INTO `$tbl_name` (`status`) VALUES ('$newstatus')";
$result = mysql_query($sql) or die('Failed executing query: '.mysql_error());
AUTO_INCREMENT can be set up in phpMyAdmin with the following query:
ALTER TABLE `WorkOrders` MODIFY `id` INTEGER NOT NULL AUTO_INCREMENT;
Finally, don't use mysql_* functions, they are deprecated.
I am guessing the 'id' field of your table is a primary key. If that's the case, you cannot have two rows that have the same identifier.
By your variable name newstatus, it seems to me like you're trying to update the status of an order ; is it the case? If yes, you should use a UPDATE SQL query of the form:
UPDATE table SET status='somestatus' WHERE id=someid
Please help!
I'm a complete php/sql newb, and i'm feeling pretty (ok, really) dumb.
I really need help pre-populating text fields of a form i've built for our office staff to contact the workmen in the field, (and the form works well enough); I've searched a million threads, but just could not figure it out...
Only some of the form fields need to pre-populate after a users login, but I have no idea how to make that happen... I've created a mysql DB with a table called 'users', and i know how to open the DB (and close it), but can't figure out how to pull the data from a given row, and populate the fields I need correctly. here's where I'm at:
mysql_connect("localhost", "XXXXX", "XXXXX") or die("Error connecting to MySQL: ".mysql_error());
mysql_select_db("vendor_sqldb") or die("Error selecting database: ".mysql_error());
$sql = mysql_query("SELECT * FROM USERS") or die("Error connecting to table: ".mysql_error());
$rowdetail=mysql_fetch_array($sql);
date_default_timezone_set('America/Los_Angeles');
//1. Add your email address here.
//You can add more than one receipient-
$formproc->AddRecipient('foreman#mysite.com'); //<<--- supervisor email address here
$formproc->SetConditionalField('select field emplyee');
$formproc->AddConditionalReceipent(employee1,'email#email.com');
$formproc->AddConditionalReceipent('employee2','email#email.com');
$formproc->AddConditionalReceipent('employee3','email#email.com');
$formproc->AddConditionalReceipent('employee4','email#email.com');
$formproc->AddConditionalReceipent('employee5','email#email.com');
$formproc->AddConditionalReceipent('employee6','email#email.com');
$formproc->AddConditionalReceipent('employee7','email#email.com');
$formproc->AddFileUploadField('newupload','',1024);//<<------- New file upload
if(isset($_POST['submitted']))
{
if($formproc->ProcessForm())
{
$formproc->RedirectToURL("thank-you.php");
}
And heres the area where I need the help to prepopulate fields:
<p align="center">
<label for='email' ></label>
<label for='name' >Office Staff Employee Name* </label>
<input type='text' name='name' id='name' readonly='readonly' 'value='<?php echo $formproc->SafeDisplay('name') ?>' maxlength="50" value="<?php echo $session->name?>" name="name" />" />
</p>
<p align="center">
<label for='email2' >Your Email Address*</label>
<input type='text' name='email2' id='email2' value='<?php echo $row_Recordset1['email']; ?><?php echo $formproc->SafeDisplay('email') ?>' maxlength="50" />
I'm not sure how to prepopulate the values for office staffer's name, their email etc? I supposed that it was a simple echo command, but if it is, I guess I'm not getting the syntax right?
I'm sure im missing a line of code, which would specify row and collumn containing the data too, but don't know how to write this!?
Thanks a bunch for your help!
Your sql selects a row for each user.
$sql = mysql_query("SELECT * FROM USERS") or die("Error connecting to table: ".mysql_error());
You need to specify which user you are trying to get from the database table. I am going to give you an example for the SQL query if the user's names were stored in a column named "USERNAME":
$sql = mysql_query("SELECT * FROM USERS WHERE USERNAME='name'") or die("Error connecting to table: ".mysql_error());
You can then pull the user specific data and insert it where needed.
I am making a php page that retrieves data from a database table and putting it in a table for the user to see via MySQLi commands.
I was wondering how I should approach the reverse situation. I want the user to be able to enter in information into textboxes and the click a button at the bottom of the page called 'save' which will prompt the user "are you sure" before saving to the database. If the user clicks 'yes', then the new entry is inserted into the database.
I have the following code to create the labels and textboxes:
<FORM>
ID: <input type="text" name="id"><br />
NM: <input type="text" name="nm"><br />
Company: <input type="text" name="company"><br />
Address: <input type="text" name="address"><br />
City: <input type="text" name="city"><br />
Zip: <input type="text" name="zip"><br />
State: <input type="text" name="state"><br />
Phone: <input type="text" name="phone"><br />
Website: <input type="text" name="web_site"><br />
</FORM>
However, when it comes to the 'save' button, I can implement the button just fine, but how would I go about saving the information entered into the database?
My initial thought process was to find the values that the user entered. I'm new to PHP and WEB dev in general, but I need to know how to get the value of the text in the textbox. Would I have to sift all the values through via the PHP Post method?
Once I have the information the user wants to enter, I was thinking maybe MySQLi has an insert function, which I found here, http://php.net/manual/en/mysqli.insert-id.php. Then it's just a quick insert and it's in the database after the user gives the 'yes' at the prompt.
Do I have the right idea in mind? Is there a more efficient way to do this?
Any help is greatly appreciated. I've looked around for problems and solutions similar to the ones related to my scenario but there were none. =(
Thanks!
EDIT:
Here is the code I have on the agentprocess.php that the action form sends the information to:
<?php
$agent_nm = $_POST['nm']; // gather all the variables
$company = $_POST['company'];
$address = $_POST['address'];
$city = $_POST['city'];
$zip = $_POST['zip'];
$state = $_POST['state'];
$phone = $_POST['phone'];
$web_site = $_POST['web_site'];
$batch_id = $_POST['batch_id']; // added batch id
//connect
$conn = new mysqli('local', 'admin', 'pass', 'DB');
if(mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
//generate the query (doesn't add id because id is autoincremented)
$query = "INSERT INTO t_agent VALUES (NULL, " . $agent_nm . ", " . $company . ", " . $address . ", " . $city . ", " . $zip . ", " . $state . ", " . $phone . ", " . $web_site . ", " . $batch_id . ")";
//insert and close.
mysqli_query($conn, $query);
mysqli_close($conn);
Despite the code here, I've queried the table and the new entry is not there. Am I missing something here?
Thanks in advance!
Very simple example, added the label tag to the labels for your input and put it inside of a form.
<form method="post" action="process.php" id="myForm" name="myForm" >
<label for="ID">ID</label>: <input type="text" name="ID" /><br />
<label for="nm">NM:</label> <input type="text" name="nm"><br />
<label for="company">Company:</label> <input type="text" name="company"><br />
<label for="address">Address:</label> <input type="text" name="address"><br />
<label for="city">City</label>: <input type="text" name="city"><br />
<label for="zip">Zip</label>: <input type="text" name="zip"><br />
<label for="state">State</label>: <input type="text" name="state"><br />
<label for="phone">Phone</label>: <input type="text" name="phone"><br />
<label for="web_site">Website</label>: <input type="text" name="web_site"><br />
<input type="submit" name="submit" />// this is your submit button
</form>
On the process.php page
//get your inputs from the form
$ID = $_POST['ID'];
//do the same for each of the text inputs
Then you can use mysqli as you described to insert the values into your database, feel free to comment if you need any help with the mysqli part of the question, I didn't include it here since you had the link posted in the original question.
you need to use forms. yes, using the name attributes in your elements, you sift through $_POST(eg. $_POST['company']) for the values you want to store into the DB. here's an example. Use MYSQLi statements instead of mysql as in the eg.
this is simple yet a little complex task for web development beginers.
So I am going to give you an full example of what you need to do...
To do the SAVE button check the fastest way is to use javascript confirm dialog and if confirmed to submit form with javascript also.
The Mysql insert part is easy, you need to check if there is data that you submited via form in $_REQUSET (this works better than $_POST or $_GET because it catchs it both.) and then to connect to db and do an insert query...
Everything is explained in this example:
http://pastebin.com/thNmsXvn
But please use some template engine like Smarty because doing php, javascript and html in one file without template is awful and long term will give you only problems.
I think that I was very clear in the example I put on pastebin but if you have some questions feel free to ask...
Just to add, I have removed ID from HTML form because the best solution for managing ID's in MySQL is auto increment option, you configure that when you create table and set it to a specific field. Most usually it is ID, and it must be an integer.
You should use PDO functions for PHP/MySQL
id field should be autoincrement
<?php
$host= "xxx";
$username="xxx";
$password="xxx";
$database="xxx ";
// Gets data from URL parameters
$name = $_POST['nm'];
//Repeate for all other parameters
// Opens a connection to a MySQL server
try {
// DBH means "DB Handle"
// MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$host;dbname=$database", $username, $password);
}
catch(PDOException $e) {
echo $e->getMessage();
}
// STH means "Statement Handle"
$STH = $DBH->prepare("INSERT INTO mytable ( id, nm,company,address,city,zip,state,phone,web_site ) values ( NULL,:nm,:company,:address,:city,:zip,:state,:phone,:web_site)");
$STH->bindParam(':name', $name);
//Repeate for all other parameters
$STH->execute();
//# close the connection
$DBH = null;
?>