I've created a user form in which once the submit button is pressed I would like to send/insert the data to mysql database adding a new record. The form has over 100 input fields. How can I accomplish this. Here is my sample php code.
<html>
<head>
</head>
<body>
<?php
if (isset($_POST['submit'])){
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "hostname";
$username = "username";
$password = "password";
$dbname = "dbname";
$mystuff = "tenant_lname","tenant_fname","tenant_mname","ssn","dl_number","dl_state","birthday","tenant_hphone","tenant_wphone","tenant_cphone","curr_street","curr__unit","curr_city","curr_state","curr_zip","how_long_from","how_long_to","last_rent_mnt","last_rent_amt","own_man_name","own_man_tel","curr_reason","pre_street","pre_unit","pre_city","pre_state","pre_zip","pre_from","pre_to","pre_last_rent","pre_amt","pre_owner","pre_owner_tel","pre_reason","sec_pre_street","sec_pre_unit","sec_pre_city","sec_pre_state","sec_pre_zip","sec_pre_from","sec_pre_to","sec_pre_last_paid_mnt","sec_pre_amt","sec_pre_owner","sec_pre_owner_tel","sec_pre_reason","curr_emp_name","curr_emp_add","curr_emp_phone","curr_emp_pos","curr_emp_bus_type","curr_emp_sup","curr_emp_from","curr_emp_to","curr_emp_salary","pre_emp_name","pre_emp_add","pre_emp_phone","pre_emp_pos","pre_emp_bus_type","pre_emp_sup_name","pre_emp_from","pre_emp_to","pre_emp_salary","move_date","addntl_occ_name","addntl_occ_age","addntl_occ_relation","addntl_ft","addntl_pt","addntl_occ1_name","addntl_occ1_age","addntl_occ1_relation","addntl_occ1_ft","addntl_occ1_pt","addntl_occ2_name","addntl_occ2_age","addnt2_occ1_relation","addntl_occ2_ft","addntl_occ2_pt","addntl_occ3_name","addntl_occ3_age","addntl_occ3_relation","addntl_occ3_ft","addntl_occ3_pt","credit_yes","credit_no","det_yes","det_no","evict_yes","evict_no","bnkry_yes","bnkry_no","fel_yes","fel_no","pet_yes","pet_no","pet_numb","pet_type","furn_yes","furn_no","ins_cov_yes","ins_cov_no","ints_yes","ints_no","ints_type","smoke_yes","smoke_no","occ_smoke_yes","occ_smoke_no","explain_smoke","bnk_name","bnk_add","checking","checking_bal","saving","saving_bal","bnk_name1","bnk_add1","checking1","checking_bal1","saving1","saving_bal1","other_income","credit_name","credit_add","credit_city","credit_acct","credit_bal","credit_payment","credit_name1","credit_add1","credit_city1","credit_acct1","credit_bal1","credit_payment1","credit_acct2_name","credit_add2","credit_city2","credit_acc2","credit_bal2","credit_payment2","credit_acc3_name","credit_acc3_add","credit_acc3_city","credit_acc3_number","credit_acc3_bal","credit_acc3_payment","emer_contact_name","emer_contact_add","emer_relation","emer_phone","reg_owner_yes","reg_owner_no","reg_who","vehicle_year","vehicle_make","vehicle_model","vehicle_color","vehicle_license","veh_state","vehicle2_year","vehicle2_make","vehicle2_model","vehicle2_color","vehicle2_license","veh2_state";
$con = mysql_connect("$hostname","$username","$password");
if (!$con){
die ("Can not connect:" . mysql_error());
}
mysql_select_db("dbname",$con);
$sql = "INSERT INTO dbname ($mystuff) VALUES ('$_POST[$mystuff]')";
mysql_query($sql,$con);
mysql_close($con);
}
?>
</body>
</html>
I will suggest simply write this manually. Don't be so lazy. And use PDO instead of mysql_query because it is future safe. Read the documentation on http://php.net.
Change $mystuff to an array and use foreach to loop through the array and generate post data.
$mystuff = array("tenant_lname","tenant_fname","tenant_mname","ssn","dl_number","dl_state","birthday","tenant_hphone","tenant_wphone","tenant_cphone","curr_street","curr__unit","curr_city","curr_state","curr_zip","how_long_from","how_long_to","last_rent_mnt","last_rent_amt","own_man_name","own_man_tel","curr_reason","pre_street","pre_unit","pre_city","pre_state","pre_zip","pre_from","pre_to","pre_last_rent","pre_amt","pre_owner","pre_owner_tel","pre_reason","sec_pre_street","sec_pre_unit","sec_pre_city","sec_pre_state","sec_pre_zip","sec_pre_from","sec_pre_to","sec_pre_last_paid_mnt","sec_pre_amt","sec_pre_owner","sec_pre_owner_tel","sec_pre_reason","curr_emp_name","curr_emp_add","curr_emp_phone","curr_emp_pos","curr_emp_bus_type","curr_emp_sup","curr_emp_from","curr_emp_to","curr_emp_salary","pre_emp_name","pre_emp_add","pre_emp_phone","pre_emp_pos","pre_emp_bus_type","pre_emp_sup_name","pre_emp_from","pre_emp_to","pre_emp_salary","move_date","addntl_occ_name","addntl_occ_age","addntl_occ_relation","addntl_ft","addntl_pt","addntl_occ1_name","addntl_occ1_age","addntl_occ1_relation","addntl_occ1_ft","addntl_occ1_pt","addntl_occ2_name","addntl_occ2_age","addnt2_occ1_relation","addntl_occ2_ft","addntl_occ2_pt","addntl_occ3_name","addntl_occ3_age","addntl_occ3_relation","addntl_occ3_ft","addntl_occ3_pt","credit_yes","credit_no","det_yes","det_no","evict_yes","evict_no","bnkry_yes","bnkry_no","fel_yes","fel_no","pet_yes","pet_no","pet_numb","pet_type","furn_yes","furn_no","ins_cov_yes","ins_cov_no","ints_yes","ints_no","ints_type","smoke_yes","smoke_no","occ_smoke_yes","occ_smoke_no","explain_smoke","bnk_name","bnk_add","checking","checking_bal","saving","saving_bal","bnk_name1","bnk_add1","checking1","checking_bal1","saving1","saving_bal1","other_income","credit_name","credit_add","credit_city","credit_acct","credit_bal","credit_payment","credit_name1","credit_add1","credit_city1","credit_acct1","credit_bal1","credit_payment1","credit_acct2_name","credit_add2","credit_city2","credit_acc2","credit_bal2","credit_payment2","credit_acc3_name","credit_acc3_add","credit_acc3_city","credit_acc3_number","credit_acc3_bal","credit_acc3_payment","emer_contact_name","emer_contact_add","emer_relation","emer_phone","reg_owner_yes","reg_owner_no","reg_who","vehicle_year","vehicle_make","vehicle_model","vehicle_color","vehicle_license","veh_state","vehicle2_year","vehicle2_make","vehicle2_model","vehicle2_color","vehicle2_license","veh2_state");
$post_data = '';
$post_array = implode(',',$mystuff);
foreach($mystuff as $value)
{
$post_data .=($post_data)? ",'".$_POST[$value]."'" : "'".$_POST[$value]."'" ;
}
$sql = "INSERT INTO dbname ($post_array) VALUES ($post_data)";
Related
Sorry for the newbie question, but I have this task which kind of got me stuck.
So, I made a database in PhpMyAdmin, created a table with data : Products(id, name, city) and created a stored procedure that will actually do a query on the table to find out the product with a certain name (which will be input-ed by the user on the web page). My stored procedure is: proc_test and takes one VARCHAR paramter.
So, how can I do this in a php script? How can i ask the user for some data, (on the site he should have like a box to type it) then click a search button, and get redirected to the page with the query results. This is my code so far:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "CALL proc_test('pencil');";
if ($result = mysqli_query($conn, $sql)) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['numec'] . "<br/>";
}
}
$conn->close();
?>
Here, of course, I manually give the parameter in the script. But I don't know how to change this and ask for a user input instead. Any help is welcome!
You can use ajax to send the data from your website to the php file where you can search for it in the database and send that data back to the user. In my example, the data is being displayed on the same webpage. You could echo the link to the website and redirect the user on the webpage using JavaScript if you really wanted to but my example is just a proof of concept.
index.html
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<input required type="text" id="user_input">
<button onclick="sendData()">Search</button>
<p id="result"></p>
<script>
function sendData() {
var var_params = $('#user_input').val();
$.post('test.php', {params: var_params}, function(data) {
document.getElementById('result').innerHTML = "Your search result: " + data;
});
}
</script>
</body>
</html>
test.php
<?php
if(isset($_POST['params'])) {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
$conn = new mysqli($servername, $username, $password, $dbname); // Create connection
if ($conn->connect_error) { // Check connection
die("Connection failed: " . $conn->connect_error);
}
$param = mysqli_real_escape_string($conn, $_POST['params']);
$sql = "CALL proc_test('$param');";
if($result = mysqli_query($conn, $sql)) {
while($row=mysqli_fetch_assoc($result)) {
echo $row['numec']. "<br/>";
}
}
$conn->close();
}
?>
Im trying to create a login for my website and i need to store emails, usernames, passwords, ect in a database i have created already using phpMyAdmin. I have gone through article after article and nothing seems to be working. i have my connect.php like this:
<?
$hostname = "localhost";
$username = "username";
$password = "password";
$databaseName = "_mySiteUserDataBase";
mysql_connect($hostname, $username, $password) or die("Cannot connect to server");
mysql_select_db($databaseName) or die("Cannot select database");
?>
And my main.php like this:
<?
include("connect.php");
$tableName = "myUsers";
$sql = "SELECT * FROM $tableName";
$result = mysql_query($sql);
?>
And i have created a simple form in my html like this:
<html>
<head></head>
<body>
<form>
<input type = "submit" action = "main.php" method = "post" value = "Login">
</form>
</body>
</html>
After submitting the form it says cannot connect to server. I am new to php and mysql and i dont understand what each parameter in the mysql_connect is, and i dont know what they do therefore im not sure what im supposed to enter in but everyone i keep reading about seems to be inputing random values? I could use a brief explanation on that, because i am stuck at connecting and cant even get past this point sadly enough. Also i have been reading that mysql_connect is deprecated and isnt valid anymore but i dont understand what im supposed to use as an alternative. I know its mysqli but thats it and im unclear of the syntax.
mysqli:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
echo "start<br/>";
try {
$mysqli= new mysqli('localhost', 'myusername', 'mypassword', 'dbname');
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
echo "I am connected and feel happy.<br/>";
$mysqli->close();
} catch (mysqli_sql_exception $e) {
throw $e;
}
?>
If you need to know how to create users, what the heck the hostname is, how to grant access (often useful after the connect :>), just ask.
Try this code in 'connect.php'
<?php
error_reporting(0);
$con=mysql_connect('localhost','root','');// here 'root' is your username and "" is password
if(!$con)
{
echo 'not connect';die;
}
mysql_select_db('dbname',$con);// here 'dbname' is your database name
?>
And also try following code to include sql connection in your other php file(main.php)
<?php
include 'connect.php';
$sql = "SELECT * FROM myUsers";
$result=mysql_query($sql);
?>
Let me convert it to mysqli for you and maybe that will fix the problem. Also, make sure the username, password, and database name are correct.
Try this code. At very least, it will provide a better error message for debugging.
<?
$hostname = "localhost";
$username = "username";
$password = "password";
$databaseName = "_mySiteUserDataBase";
$con = mysqli_connect($hostname, $username, $password, $databaseName) or die(mysqli_error($con));
?>
Main.php
<?
include("connect.php");
$tableName = "myUsers";
$sql = "SELECT * FROM $tableName";
$result = mysqli_query($con,$sql);
?>
I am working on a small social web application as a final project for my iOS class. I have a profile view controller where all the info about the user from the database is supposed to be displayed on the labels. The problem is that I don't really know the best way to do this. Here is my php script:
<?
// Database credentials
$host = 'localhost';
$db = 'blabla';
$uid = 'blabla';
$pwd = 'blabla';
// Connect to the database server
$link = mysql_connect($host, $uid, $pwd) or die("Could not connect");
//select the json database
mysql_select_db($db) or die("Could not select database");
// Create an array to hold our results
$arr = array();
//Execute the query
$rs = mysql_query("SELECT IdUser, username, fullname, phonenumber, facebook, instagram FROM login");
// Add the rows to the array
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
//return the json result.
echo '{"users":'.json_encode($arr).'}';
?>
So here I get the info about all the users in the database. I am sure this is not the right way to go, so I guess I need to change the SQL query to retrieve the data for the current user only. But how can I do this? Should I put the username which I enter on the login page into an extra variable and then pass it with JSON to this php script and add the 'WHERE username = 'blabla' statement to the SQL query then? If so, how can I pass the variable to this script with JSON?
Can you please give me some sample code? Or is there a different way to do this?
Thank you so much!
<?php
// Database credentials
$host = 'localhost';
$db = 'blabla';
$uid = 'blabla';
$pwd = 'blabla';
// Connect to the database server
$link = mysql_connect($host, $uid, $pwd) or die("Could not connect");
//select the json database
mysql_select_db($db) or die("Could not select database");
//Execute the query
$rs = mysql_query("SELECT IdUser, username, fullname, phonenumber, facebook, instagram FROM login");
// Add the rows to the array
$data = mysql_fetch_array($rs);
foreach($data as $rec){
echo "user: $rec<br>";
}
?>
I am trying to display a Website Title on my Home Page. This website title is stored in the database named mywebsite and in table settings. I want to update this with an input type text's value. The title is displayed perfectly but when I write something in the text field and submit it, the database doesn't update. I think I am doing everything right and there isn't any error displaying on my page, but still it is not working. Can anyone figure out the error?
Here's my code:
<?php
// Some database detail
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'mywebsite';
// Making connection
$con = mysqli_connect($host, $username, $password, $database);
// Making a sql query for "Website Title" and saving it in variable $query
$query = "SELECT * FROM settings WHERE NameOfSetting='Website Title'";
// Applying query
$result = mysqli_query($con, $query);
// Fetching data from database
$row = mysqli_fetch_array($result);
if (isset($_POST['submit'])) {
$title = $_POST['text'];
mysqli_query($con, "UPDATE settings SET TheSetting=$title WHERE NameOfSetting='Website Title'");
}
?>
<h1><?php echo $row['TheSetting']; ?></h1>
<form method="POST">
<input type="text" placeholder="Change the title" name="text">
<input type="submit" name="submit">
</form>
EDIT: When I enter any numbers in the field and then submit and refresh it works fine but it's only working with numbers not with alphabets. I don't know why?
This line:
SET TheSetting=$title
$title needs to be wrapped in quotes:
SET TheSetting='$title'
Sidenote: You may also want to change this line (as a security precaution):
$title = $_POST['text'];
to:
$title = mysqli_real_escape_string($con,$_POST['text']);
Try with
mysqli_query($con, "UPDATE settings SET TheSetting='$title' WHERE NameOfSetting='Website Title'");
Well you can always do some sort of error checking. I.e. using or die(mysqli_error);
$con = mysqli_connect($host, $username, $password, $database)or die(mysqli_error);
This will atleast give you an idea of what your proplem is. Use this error checking method every time you connect, query, or close a database.
use this code it will solve your problem.
<?php
// Some database detail
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'mywebsite';
// Making connection
$con = mysqli_connect($host, $username, $password, $database)or die(mysqli_error());
// Making a sql query for "Website Title" and saving it in variable $query
$query = "SELECT * FROM settings WHERE NameOfSetting='Website Title'";
// Applying query
$result = mysqli_query($con, $query);
// Fetching data from database
$row = mysqli_fetch_array($result);
if (isset($_POST['submit'])) {
$title = $_POST['text'];
mysqli_query($con, "UPDATE settings SET TheSetting='".$title."' WHERE NameOfSetting='Website Title'");
}
?>
<h1><?php echo $row['TheSetting']; ?></h1>
<form method="POST">
<input type="text" placeholder="Change the title" name="text">
<input type="submit" name="submit">
</form>
I'm getting the error: No database selected
Here is the code:
<?php
$host = "localhost";
$user = "root";
$password = "";
$database_name = "Student";
mysql_connect($host, $user, $password);
mysql_select_db($database_name);
?>
This code is for php-connect.php class and for the form:
<!DOCTYPE html>
<html>
<body>
<?php
//load database connection
include("php-connect.php");
$id = "1";
$name = "Elena";
$city = "Lahore";
//Command to insert into table
$query = "INSERT INTO studentdata (id,name,city) VALUES ('$id','$name','$city')";
//run the query to insert the person.
$result = mysql_query($query) OR die(mysql_error());
//let them know the person has been added.
echo "Data successfully inserted into the database table ... ";
?>
</body>
</html>
This is the code for the form.. I've tried a lot of things to fix this error but it does not work. Is there any problem with my database?
Try this...
<?php
$host = "localhost";
$user = "root";
$password = "";
$database_name = "Student";
$mLink = mysql_connect($host, $user, $password) or die(mysql_error());
mysql_select_db($database_name , $mLink);
another file
<?php
require 'php-connect.php';
//...... etc..
but, read this first:
This extension is deprecated as of PHP 5.5.0, and will be removed in
the future. Instead, the MySQLi or PDO_MySQL extension should be used.
See also MySQL: choosing an API guide and related FAQ for more
information. Alternatives to this function include:
mysqli_select_db()
PDO::__construct() (part of dsn)
http://br.php.net/mysql_select_db