This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 1 year ago.
I write my code but I still have this error (Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in database). I have table users which have username and user_id. And I have table country which has country_id as primary key(Varchar) and has country_name, the table education has user_id as foreign key and also country_id as foreign key.
<?php
include_once "connection.php";
/** #var PDO $conn */
if(isset($_REQUEST['btn_register'])) {
$user_id = $_REQUEST['user_id'];
$edname = $_REQUEST['edname'];
$street = $_REQUEST['street_address'];
$postcode = $_REQUEST['postal_address'];
$city = $_REQUEST['city'];
$pofiletext = $_REQUEST['profiletext'];
$positionn = $_REQUEST['position_com'];
$video = $_REQUEST['video'];
$logo = $_REQUEST['logo'];
$contactperson = $_REQUEST['contactpersoon'];
$emailcon = $_REQUEST['email_contactpersoon'];
$website = $_REQUEST['website'];
$country="SELECT country_id FROM country WHERE country_id= 'AD'";
try {
$select_stmt = $conn->prepare("INSERT INTO education (user_id ,edname, street_address, postal_address, city, country_id , profiletext ,position_com, video, logo,contactpersoon, email_contactpersoon , website )
VALUES (':user_id',':edname',':street_address', ':postal_address',':city',':countryid', ':about',':position_com', ':video', ':logo', ':contactperson',':email_contactpersoon', ':website')");
$select_stmt->bindParam(':user_id', $user_id);
$select_stmt->bindParam(':edname', $_POST['edname']);
$select_stmt->bindParam(':street_address', $_POST['street_address']);
$select_stmt->bindParam(':postal_address', $_POST['postal_address']);
$select_stmt->bindParam(' :city', $_POST['city']);
$select_stmt->bindParam(':country_id',$country );
$select_stmt->bindParam(':profiletext', $_POST['profiletext']);
$select_stmt->bindParam(':position_com', $_POST['position_com']);
$select_stmt->bindParam(':video', $_POST['video']);
$select_stmt->bindParam(':logo', $_POST['logo']);
$select_stmt->bindParam(':contactpersoon', $_POST['contactpersoon']);
$select_stmt->bindParam(':email_contactpersoon', $_POST['email_contactpersoon']);
$select_stmt->bindParam(':website', $_POST['website']);
$select_stmt->execute();
$resiterMsg = "Register successfully";
header("location: index.php");
} catch (PDOExeption $e) {
echo $e->getMessage();
}
}
?>
And my html code:
<?php
include_once "html.html";
include "connection.php";
/** #var PDO $conn */
$sql = $conn->prepare('SELECT * From intern where user_id = :user_id');
$sql->bindParam(":user_id", $_GET['user_id']);
$sql->execute();
$row = $sql->fetch();
?>
<!DOCTYPE html>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!------ Include the above in your HEAD tag ---------->
<html>
<head>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link href="educationRegister.php">
<!------ Include the above in your HEAD tag ---------->
</head>
<body id="educationForm">
<div class="container">
<div class="login-form">
<div class="main-div">
<div class="panel">
<h2>Register</h2>
</div>
<form method="post" class="cd-form floating-labels" action="educationRegister.php">
<div class="form-group">
<input type="hidden" name="type" value="education">
<input type="hidden" name="user_id" value="<?php echo $_GET['user_id'] ?>" >
<input type="text" name="edname" class="form-control" placeholder="Name">
</div>
<div class="form-group">
<input type="text" name="street_address" class="form-control" placeholder="Street">
</div>
<div class="form-group">
<input type="text" name="postal_address" class="form-control" placeholder="Postal Code">
</div>
<div class="form-group">
<select name="city">
<option>--Select city--</option>
<?php
$country_stmt=$conn->prepare('SELECT * FROM country');
$country_stmt->execute();
while ($row = $country_stmt->fetch(PDO::FETCH_ASSOC)) { ?>
<option value="<?php echo $row['country_id']; ?>"><?php echo $row['countryname']; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<input type="text" name="profiletext" class="form-control" placeholder="About you">
</div>
<div class="form-group">
<input type="text" name="position_com" class="form-control" placeholder="position">
</div>
<div class="form-group">
<input type="text" name="video" class="form-control" placeholder="video">
</div>
<div class="form-group">
<input type="text" name="logo" class="form-control" placeholder="logo">
</div>
<div class="form-group">
<input type="text" name="contactpersoon" class="form-control" placeholder="contactperson">
</div>
<div class="form-group">
<input type="email" name="email_contactpersoon" class="form-control" placeholder="emailContactperson">
</div>
<div class="form-group">
<input type="text" name="website" class="form-control" placeholder="website">
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9 m-t-15">
<button type="submit" name="btn_register" class="btn btn-primary" value="Regsiter" >
<button type="button" class="btn btn-primary"> Cancel </button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
$select_stmt->bindParam(' :city', $_POST['city']);
You have an empty space between ' and :. Try with it like this:
$select_stmt->bindParam(':city', $_POST['city']);
Related
I'm trying to create an edit page where data is read from MySQL with PHP and then displayed in HTML.
Normal fields like VARCHAR displays correctly, but I have difficulty in displaying TEXT fields.
<?php
$DATABASE_HOST = '';
$DATABASE_USER = '';
$DATABASE_PASS = '';
$DATABASE_NAME = '';
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if ( mysqli_connect_errno() ) {
exit('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$idjob = $_POST['jobID'];
$jobquery = $mysqli->prepare('SELECT * FROM jobs WHERE id = ?');
$jobquery->bind_param('s', $idjob); // 's' specifies the variable type => 'string'
$jobquery->execute();
$jobresult = $jobquery->get_result();
while ($row = $jobresult->fetch_assoc()) {
$jobtitle = $row['jobtitle'];
$workhours = $row['workhours'];
$type = $row['type'];
$availfrom = $row['availfrom'];
$deadline = $row['deadline'];
$customer = $row['customer'];
$province = $row['province'];
$town = $row['town'];
$minreq = $row['minreq'];
$posdetails = $row['posdetails'];
$minsal = $row['minsal'];
$maxsal = $row['maxsal'];
}
mysqli_free_result($jobresult);
mysqli_close($mysqli);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Edit Job Listing</title>
<link rel="shortcut icon" type="image/jpg" href="images/Logo.jpg">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0 shrink-to-fit=no">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<link rel="stylesheet" href="../assets/css/style.css" type="text/css"/>
</head>
<body id="editjoblisting">
<!-- Container (About Add New Job Listing Section) -->
<div id="abouteditnewjob" class="container-fluid bg-grey">
<div class="row">
<div class="col-sm-2"></div>
<div class="col-sm-8">
<div class="text-center">
<h2> Edit Job Listing </h2>
</div>
</div>
<div class="col-sm-2"></div>
</div>
</div>
<div class="container-fluid bg-grey">
<form method="post" id="updedit_form" action="../php/updeditjob.php">
<div class="form-row">
<div class="col-sm-2"></div>
<div class="col-sm-4">
<div class="form-group">
<label for="jobtitle"> Job Title</label>
<input type="text" class="form-control" name="jobtitle" value='<?php echo $jobtitle; ?>'>
<label for="workhours"> Working Hours</label>
<input type="text" class="form-control" name="workhours" value='<?php echo $workhours; ?>'>
<label for="worktype">Type</label>
<select class="form-control" name="worktype" >
<option value='<?php echo $type; ?>' selected><?php echo $type; ?></option>
<option>--None--</option>
<option>Temporary</option>
<option>Permanent</option>
</select>
<label for="availfrom"> Available From</label>
<input type="date" class="form-control" id="availfrom" name="availfrom" required maxlength="50" value='<?php echo $availfrom; ?>'>
<label for="deadline"> Application Deadline</label>
<input type="date" class="form-control" id="deadline" name="deadline" required maxlength="50" value='<?php echo $deadline; ?>'>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="minreq">Minimum Requirements</label>
<textarea class="form-control" type="textarea" name="minreq" id="minreq" maxlength="6000" rows="5" value='<?php echo $minreq; ?>'></textarea>
<label for="posdetails">Position Details</label>
<textarea class="form-control" type="textarea" name="posdetails" id="posdetails" maxlength="6000" rows="5" value='<?php echo $posdetails; ?>'></textarea>
<label for="minsal"> Minimum Salary</label>
<input type="text" class="form-control" id="minsal" name="minsal" value='<?php echo $minsal; ?>'>
<label for="maxsal"> Maximum Salary</label>
<input type="text" class="form-control" id="maxsal" name="maxsal" value='<?php echo $maxsal; ?>'>
</div>
</div>
<div class="col-sm-2"></div>
</div>
</form>
</div>
</body>
</html>
This is the data I'm trying to show/edit.
id "251"
jobid "ID#20101664"
jobtitle "SENIOR CONVEYANCING SECRETARY"
workhours "Monday - Friday 7:00 - 17:00"
type "Permanent"
availfrom "2021-06-07"
deadline "2021-10-29"
minreq
"- Matric Certificate
- Minimum 3 years experience
- Knowledge in Law programs (Lexis Nexis, Windeed) – Compulsory
- Knowledge of Bonds: Absa, Standard Bank, FNB and Nedbank
- Bilingual (English & Afrikaans)
- Computer literate
- Be accurate and methodical etc.." \N
minsal "0"
maxsal "0"
Everything works nicely except minreq which is a TEXT field in MySQL. It is not displayed, yet echo shows that it was retrieved in the $row array.
Try to echo the value between the textarea tags, not in the value attribute:
<textarea class="form-control" type="textarea" name="minreq" id="minreq" maxlength="6000" rows="5"><?php echo $minreq; ?></textarea>
Please remove the value from inside the text area and write your code like this:
//here is the valid code...this will 100% work.
<textarea class="form-control" type="textarea" name="posdetails" id="posdetails" maxlength="6000" rows="5">
<?php echo $posdetails; ?>
</textarea>
When I press register button in crudindex.php It will insert data in to cruduser(table)
once done Call crudadd.php and insert data into crud(table) with max(id) from cruduser table as id.
The issue is :Once I press REGISTER button Cruduser(table) is getting inserted properly.
But In crud(table) it inserts only the id and other fields are blank.
I have a doubt the post is not picking the values or insert command some issues.
But when I give static values ex : firstname as 'Tim', lastname as 'cook' etc its inserting in the table crud.
Also when I run crudadd.php separately it inserts properly.
Structure :
cruduser(
id(int),
username(varchar),
password(varchar)
)
crud(
id(int),
firstname(varchar),
lastname(varchar),
email(varchar),
gender(varchar),
age(varchar)
)
used : tables : cruduser and crud
php : crudindex.php and crudadd.php
Core issue : data is not properly inserted in to crud table
Crudindex.php
<?php
$con = mysqli_connect("127.0.0.1", "kkits996_ganesh", "mysql123#", "kkits996_testmysql") or die("Error " . mysqli_error($con));
if (isset($_POST) && (!empty($_POST))){
$uname=mysqli_real_escape_string($con,$_POST["uname"]);
$pwd=mysqli_real_escape_string($con,$_POST["pwd"]);
$cpwd=mysqli_real_escape_string($con,$_POST["cpwd"]);
if (isset($_POST['register'])) {
# Register-button was clicked
$createsql1="INSERT INTO cruduser(id,username,password) VALUES
('','$uname','$pwd')";
if (mysqli_query($con,$createsql1)) {
echo "Insert Successful in Table cruduser";
mysqli_close($con);
include ("crudadd.php");
}
else
{
die(mysqli_error($con));
}
}
mysqli_close($con);
}
?>
<!--DocType HTML -->
<! bootstrap link is downloaded from bootstrapcdn.com for css and js -->
<! col-mod-6 col-mod-offset are bootstrap related-->
<HTML>
<head>
<title>"Add records in CRUD Table"</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<form method="post" class="form-horizontal col-mod-6 col-mod-offset-3">
<h2>Create The table CRUD</h2>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Firstname</label>
<div class="col-sm-10">
<input type="text" name="uname" class="form-control" id="input1" placeholder="Username"/>
</div>
</div>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Lastname</label>
<div class="col-sm-10">
<input type="text" name="pwd" class="form-control" id="input1" placeholder="Password"/>
</div>
</div>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="text" name="cpwd" class="form-control" id="input1" placeholder="Confirm Password"/>
</div>
</div>
<div class="row">
<div class="col-mod-6 col-mod-offset-3">
<button id="submit1" name="register" class="btn btn-primary pull-right">Register</button>
<button id="submit2" name="login" class="btn btn-secondary pull-right">Login</button>
</div>
</div>
</form>
</body>
</html>
Crudadd.php
<?php
//session_start();
//$maxiid = $_SESSION['id'];
//echo $maxiid;
$con = mysqli_connect("127.0.0.1", "kkits996_ganesh", "mysql123#", "kkits996_testmysql") or die("Error " . mysqli_error($con));
$result = mysqli_query($con,"SELECT * FROM cruduser WHERE id=(SELECT MAX(id) FROM cruduser)");
$row1 = mysqli_fetch_array($result);
$c1 = $row1['id'];
mysqli_close($con);
$con = mysqli_connect("127.0.0.1", "kkits996_ganesh", "mysql123#", "kkits996_testmysql") or die("Error " . mysqli_error($con));
if (isset($_POST) && (!empty($_POST))){
$fname=mysqli_real_escape_string($con,$_POST["fname"]);
$lname=mysqli_real_escape_string($con,$_POST["lname"]);
$email=mysqli_real_escape_string($con,$_POST["email"]);
$gender=$_POST["gender"];
$age=$_POST["age"];
print "I am here";
echo $finame;
echo $liname;
print email;
//Notes : In Insert if numeric do not use quotes. if string use quotes.for auto use ''
$createsql="INSERT INTO crud(id,firstname,lastname,email,gender,age) VALUES
($c1,'$fname','$lname','$email','$gender','$age')";
if (mysqli_query($con,$createsql)) {
echo "Connection Successful";
}
else
{
echo "Connection Issue";
die(mysqli_error($con));
}
mysqli_close($con);
}
?>
<!--DocType HTML -->
<! bootstrap link is downloaded from bootstrapcdn.com for css and js -->
<! col-mod-6 col-mod-offset are bootstrap related-->
<HTML>
<head>
<title>"Add records in CRUD Table"</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<form method="post" class="form-horizontal col-mod-6 col-mod-offset-3">
<h2>Create The table CRUD</h2>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Firstname</label>
<div class="col-sm-10">
<input type="text" name="finame" class="form-control" id="input1" placeholder="First name"/>
</div>
</div>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Lastname</label>
<div class="col-sm-10">
<input type="text" name="liname" class="form-control" id="input1" placeholder="Last name"/>
</div>
</div>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="text" name="eimail" class="form-control" id="input1" placeholder="Email"/>
</div>
</div>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Gender</label>
<div class="col-sm-10">
<label>
<input type="radio" name="giender" id="optionsRadios1" value="male" checked> Male
</label>
<label>
<input type="radio" name="giender" id="optionsRadios1" value="female" > Female
</label>
</div>
</div>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Age</label>
<div class="col-sm-10">
<select name="aige" class="form-control">
<option>Select your age</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
</select>
</div>
</div>
<input type="submit" class="btn btn=primary col-md-2 col-md-offset-10" value="submit"/>
</form>
</body>
</html>
While clicking on 'Register' you are sending uname, pwd and cpwd ina POST request which are properly used to be inserted into cruduser. After that you are including the crudadd.php (include ("crudadd.php");). But remember you are still at the same request. So the only data available is uname, pwd and cpwd. This is why your rows are semi-empty.
if Id is AUTO INCREMENT.
you must use
$createsql1="INSERT INTO cruduser(id,username,password) VALUES
(NULL,'$uname','$pwd')";
not ((you can not set string for id value. Your id is of int type ))
$createsql1="INSERT INTO cruduser(id,username,password) VALUES
('','$uname','$pwd')";
When trying to submit my form I get the following error message:
Notice: Undefined index: application_results in C:\xampp\htdocs\cas\insert.php
This is my form php code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>CAS Application</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap /3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body style="background-color:#FF9933">
<div class="container" >
<form action="insert.php" method="post" class="form-horizontal" role="form" enctype="multipart/form-data">
<h2 style="text-align:center">Application Form</h2>
</div>
<div class="form-group">
<label for="surname" class="col-sm-3 control-label">Surname</label>
<div class="col-sm-9">
<input type="text" name="surname" id="surname" placeholder="Surname" class="form-control" autofocus>
</div>
</div>
<div class="form-group">
<label for="firstName" class="col-sm-3 control-label">First Name</label>
<div class="col-sm-9">
<input type="text" name="first_name" id="first_name" placeholder="First Name" class="form-control" autofocus>
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-3 control-label">Email</label>
<div class="col-sm-9">
<input type="text" id="email" placeholder="Email" class="form-control" name="email">
</div>
</div>
<div class="col-sm-offset-3">
<h2>Application Results</h2>
<label for="application_results">Please upload your application results here:</label>
<input type="file" name="application_results" ><br>
</div>
<div class="form-group">
<div class="col-sm-6 col-sm-offset-3">
<button type="submit" class="btn btn-primary btn-block" name="submit">Submit</button>
</div>
</div>
</form>
</div>
</body>
</html>
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db("cas",$con);
if(isset($_POST['submit'])) {
$file = rand(1000,100000). "-".$_FILES['application_results']['name'];
$file_loc = $_FILES['application_results']['tmp_name'];
$folder="application_results";
if(move_uploaded_file($file)) {
$sql="INSERT INTO applications (application_results) VALUES ($application_results)";
mysql_query($sql);
}
}
?>
This is my code for insertion:
<?php
$link = mysqli_connect("localhost", "root", "", "cas");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$surname = mysqli_real_escape_string($link, $_REQUEST['surname']);
$first_name = mysqli_real_escape_string($link, $_REQUEST['first_name']);
$email = mysqli_real_escape_string($link, $_REQUEST['email']);
$application_results = mysqli_real_escape_string($link, $_REQUEST['application_results']);
// attempt insert query execution
$sql = "INSERT INTO applications ( surname, first_name,
email, application_results )
VALUES ('$surname', '$first_name', '$email', $application_results )";
if(mysqli_query($link, $sql)){
echo "Your application has been submitted.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
What I am actually trying to accomplish is after insertion when calling an applications.php page details of the applicant must be displayed together with the uploaded file for reading. I suspect most of the uploaded files will be in pdf.
I really hope you can help me.
I've done a form, where I can opt if a client I'm adding to the database is "Active or "Inactive", using a dropdown select box.
My code saves all the data correctly to the datbase, but when I want to edit the client, the option displays always as "Active", ignoring the value from the database.
I have 2 files:
edita_clientes.php - the form where I can edit the clients values
salvar_edicao.php - the file that saves the edition.
Here are the codes:
edita_clientes.php:
<?php
#ini_set('display_errors', '1');
error_reporting(E_ALL);
$id = $_GET["id_cliente"];
settype($id, "integer");
mysql_connect("localhost", "root", "");
mysql_select_db("sistema");
$resultado = mysql_query("select * from tabela where id_cliente = $id");
$dados = mysql_fetch_array($resultado);
mysql_close();
?>
<form id="edita_pj" name="edita_pj" method="post" action="salvar_edicao.php">
<input type="hidden" name="id_cliente" id="id_cliente" value="<?php echo $id;?>" />
<div class="box-body">
<div class="form-group">
<label>Razão Social</label>
<input type="text" name="razao" id="razao" class="form-control" value="<?php echo $dados["razao"];?>" />
</div>
<div class="form-group">
<label>Nome Fantasia</label>
<input type="text" name="fantasia" id="fantasia" class="form-control" value="<?php echo $dados["fantasia"];?>" />
</div>
</div>
<div class="box-body">
<div class="form-group">
<label>CNPJ</label>
<input type="text" name="cnpj" id="cnpj" class="form-control" data-inputmask='"mask": "999.999.999-99"' data-mask value="<?php echo $dados["cnpj"];?>">
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-9">
<label>Logradouro</label>
<input type="text" name="logradouro" id="logradouro" class="form-control" value="<?php echo $dados["logradouro"];?>">
</div>
<div class="col-xs-3">
<label>Número</label>
<input type="text" name="numero" id="numero" class="form-control" value="<?php echo $dados["numero"];?>">
</div>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-9">
<label>Bairro</label>
<input type="text" name="bairro" id="bairro" class="form-control" value="<?php echo $dados["bairro"];?>">
</div>
<div class="col-xs-3">
<label>CEP</label>
<input type="text" name="cep" id="cep" class="form-control" data-inputmask='"mask": "99999-999"' data-mask value="<?php echo $dados["cep"];?>">
</div>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-10">
<label>Cidade</label>
<input type="text" name="cidade" id="cidade" class="form-control" value="<?php echo $dados["cidade"];?>">
</div>
<div class="col-xs-2">
<label>UF</label>
<input type="text" name="uf" id="uf" class="form-control" value="<?php echo $dados["uf"];?>">
</div>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-9">
<label>E-mail</label>
<input type="text" name="email" id="email" class="form-control" value="<?php echo $dados["email"];?>">
</div>
<div class="col-xs-3">
<label>Telefone</label>
<input type="text" name="telefone" id="telefone" class="form-control" data-inputmask='"mask": "(99) 9999.9999"' data-mask value="<?php echo $dados["telefone"];?>"/>
</div>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-9">
<label>Contato</label>
<input type="text" name="contato" id="contato" class="form-control" value="<?php echo $dados["contato"];?>">
</div>
<div class="col-xs-3">
<label>Estado</label>
<select class="form-control" name="estado" id="estado" value=""><?php echo $dados["estado"];?>
<option>Ativo</option>
<option>Inativo</option>
</select>
</div>
</div>
<div class="form-group">
<label>Observações</label>
<textarea class="form-control" name="obs" id="obs" rows="6" ><?php echo $dados["obs"];?>
</textarea>
</div>
</div>
<div class="box-footer">
<button type="submit" name="Submit" class="btn btn-primary">Salvar</button>
</div>
</form>
salvar_edicao.php:
<?php
#ini_set('display_errors', '1');
error_reporting(E_ALL);
$razao = $_POST["razao"];
$fantasia = $_POST["fantasia"];
$cnpj = $_POST["cnpj"];
$logradouro = $_POST["logradouro"];
$numero = $_POST["numero"];
$bairro = $_POST["bairro"];
$cep = $_POST["cep"];
$cidade = $_POST["cidade"];
$uf = $_POST["uf"];
$email = $_POST["email"];
$telefone = $_POST["telefone"];
$contato = $_POST["contato"];
$estado = $_POST["estado"];
$obs = $_POST["obs"];
$id = $_POST["id_cliente"];
mysql_connect("localhost", "root", "");
mysql_select_db("sistema");
mysql_query("UPDATE tabela SET razao = '$razao', fantasia = '$fantasia', cnpj = '$cnpj', logradouro = '$logradouro', numero='$numero', bairro='$bairro', cep='$cep', cidade = '$cidade', uf='$uf', email = '$email', telefone = '$telefone', contato = '$contato', estado = '$estado', obs = '$obs' WHERE tabela.id_cliente = $id");
mysql_close();
header("Location: consulta.php");
?>
You need to add 'selected' to the option that you want to be selected, based on a value from the form/db. Here is an example using $value as the option value that you want selected.
<select class="form-control" name="estado" id="estado">
<option <?php echo $value == 'Ativo' ? selected : '' ?>>Ativo</option>
<option <?php echo $value == 'Inativo' ? selected : '' ?>>Inativo</option>
</select>
Also, your <select> tag does not require a 'value' element..
The HTML select element does not have a value attribute. For the select to do what you want you need to add the selected attribute to the option you want selected. It's always showing as 'Active' because that's the first option and it is the default.
The resulting post-php HTML will need to look something like this stripped back example for 'Inactive' to be selected.
<select>
<option>Active</option>
<option selected>Inactive</option>
</select>
Thank's for all the help!
The solution I've found was:
<?php
$resultado = mysql_query("select * from tabela where id_cliente = $id");
$dados = mysql_fetch_array($resultado);
$query = mysql_query("SELECT * FROM estado");
?>
And the html part:
<select class="form-control" name="estado" id="estado">
<option selected="selected"><?php echo $dados["estado"];?></option>
<option value="Ativo">Ativo</option>
<option value="Inativo">Inativo</option>
</select>
first of all i would like to appolagise on the amount of code i am about to paste, i didn't want to snippet any more incase its a bit that's giving me the errors
i have a table named contacts and want to update the table by a form.
i am not sure if its the form or if its the code as the delete user isn't working
i have just started to learn this (a few days ago)so the code might be messy or not 100% secure as it should this is for a offline database so i would improve it as i learn.
<?php include("header.php");
//include database connection
include 'db_connect.php';
$action = isset( $_POST['action'] ) ? $_POST['action'] : "";
if($action == "update"){
//write query
$query = "update contacts
set
name = '".$mysqli->real_escape_string($_POST['name'])."',
surname = '".$mysqli->real_escape_string($_POST['surname'])."',
email = '".$mysqli->real_escape_string($_POST['email'])."',
pcode = '".$mysqli->real_escape_string($_POST['pcode'])."',
website = '".$mysqli->real_escape_string($_POST['website'])."',
gender = '".$mysqli->real_escape_string($_POST['gender'])."'
mobile = '".$mysqli->real_escape_string($_POST['mobile'])."'
phone = '".$mysqli->real_escape_string($_POST['phone'])."'
county = '".$mysqli->real_escape_string($_POST['county'])."'
town = '".$mysqli->real_escape_string($_POST['town'])."'
address = '".$mysqli->real_escape_string($_POST['address'])."'
notes = '".$mysqli->real_escape_string($_POST['notes'])."'
business = '".$mysqli->real_escape_string($_POST['business'])."'
where id='".$mysqli->real_escape_string($_REQUEST['id'])."'";
if( $mysqli->query($query) ) {
echo "User was updated.";
}else{
echo "Database Error: Unable to update record.";
}
}
if($action=='delete'){ //if the user clicked ok, run our delete query
$query = "DELETE FROM users WHERE id = ".$mysqli->real_escape_string($_GET['id'])."";
if( $mysqli->query($query) ){
echo "User was deleted.";
}else{
echo "Database Error: Unable to delete record.";
}}
$query = "select id, name, pcode, website, email, surname, mobile, phone, business, gender, address, town, county, notes
from contacts
where id='".$mysqli->real_escape_string($_REQUEST['id'])."'
limit 0,1";
$result = $mysqli->query( $query );
$row = $result->fetch_assoc();
$id = $row['id'];
$name = $row['name'];
$surname = $row['surname'];
$pcode = $row['pcode'];
$email = $row['email'];
$business = $row['business'];
$phone = $row['phone'];
$mobile = $row['mobile'];
$gender = $row['gender'];
$address = $row['address'];
$county = $row['county'];
$notes = $row['notes'];
$town = $row['town'];
$website = $row['website']; ?>
<?php echo "<a href='#' onclick='delete_user( {$id} );'>Delete</a>";
?>
<body>
<div class="div-middle-big">
<!--we have our html form here where new user information will be entered-->
<a href='index.php'>Back to index</a>
</td>
</tr>
</table>
</form>
<div id="loader_cont"><img src="img/loaders/page_loader.gif"></div>
<?php include'topnav.php' ?>
<div class="container">
<div class="main_content row-fluid">
<div class="span3">
<?php include'menu.php' ?>
<!--/.well -->
</div>
<!--/span-->
<div class="span9">
<div class="row-fluid">
<div class="span12">
<ul class="breadcrumb br_styled no_space">
<li> Dashboard <span class="divider">/</span> </li>
<li class="active">Profile</li>
</ul>
<div class="widget profile_cont">
<header>
<h3>Profile: <span class="profile_title"><?php echo$name; ?> <?php echo$surname; ?></span></h3>
<ul class="toggle_content">
<li class="arrow">Toggle Content</li>
</ul>
</header>
<section class="group">
<div class="info"> <img src="http://api.thumbalizr.com/?url=http://<?php echo$website; ?>&width=250" alt="Profile picture">
<h4>Profile Picture</h4>
<div class="profile_picture">
<input type="file" />
<!-- <input type="submit" /> -->
visit website
<!-- UPLOAD -->
</div>
<ul>
<li><i class="sweet-user"></i> Profile</li>
<li><i class="sweet-settings"></i> Settings</li>
<li><i class="sweet-mail"></i> Email <?php echo$name; ?></li>
<li><i class="sweet-cog-4"></i> Widgets</li>
<li><i class="sweet-exit"></i> Logout</li>
</ul>
<div class="span3">
<div class="widget">
<header>
<h3>Grid 3</h3>
<ul class="toggle_content" style="display: none;">
<li class="arrow">Toggle Content</li>
</ul>
</header>
<section class="code_align"> <code>class="span3"</code> </section>
</div>
</div>
</div>
<div class="details">
<form action='#' method='post' border='0' class="well form-horizontal">
<fieldset>
<h4 class="group"> <span>Personal details</span> </h4>
<div class="control-group">
<div class="controls"> </div>
</div>
<div class="control-group">
<label class="control-label" for="name">First name</label>
<div class="controls">
<input id="name" type="text" name="name" value="<?php echo$name; ?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="surname">Last name</label>
<div class="controls">
<input id="surname" type="text" name="surname" value="<?php echo$surname; ?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="business">Company Name</label>
<div class="controls">
<input id="business" type="text" name="business" value="<?php echo$business; ?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="phone">Phone number</label>
<div class="controls">
<input id="phone" type="text" name="phone" value="<?php echo$phone; ?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="mobile">Mobile number</label>
<div class="controls">
<input id="mobile" type="text" name="mobile" value="<?php echo$mobile; ?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="gender">Sex</label>
<div class="controls">
<select class="gender" style="width:210px;" tabindex="2">
<option value="<?php echo$gender; ?>"><?php echo$gender; ?></option>
<option value="female">Female</option>
<option value="male">Male</option>
</select>
</div>
</div>
<h4>Contact details</h4>
<div class="control-group">
<label class="control-label" for="email">E-mail</label>
<div class="controls">
<input id="email" type="text" name="email" value="<?php echo$email; ?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="website">Website</label>
<div class="controls">
<input id="website" type="text" name="website" value="<?php echo$website; ?>" data-original-title="Without the http://">
</div>
</div>
<div class="control-group">
<label class="control-label" for="address">Address</label>
<div class="controls">
<textarea id="address" rows="3" name="address" ><?php echo$address; ?></textarea>
</div>
</div>
<div class="control-group">
<label class="control-label" for="skypeid">Town</label>
<div class="controls">
<input id="town" type="text" name="town" value="<?php echo$town; ?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="county">County</label>
<div class="controls">
<input id="county" type="text" name="county" value="<?php echo$county; ?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="pcode">Post code</label>
<div class="controls">
<input id="pcode" type="text" name="pcode" value="<?php echo$pcode; ?>">
</div>
</div>
<h4>Notes about <?php echo$name; ?> <?php echo$surname; ?></h4>
<p>
<textarea id="notes" rows="5" name="notes" ><?php echo$notes; ?></textarea>
</p>
<div class="form-actions">
<!-- so that we could identify what record is to be updated -->
<input type='hidden' name='id' value='<?php echo $id ?>' />
<!-- we will set the action to edit -->
<input type='hidden' name='action' value='update' />
<input type='submit' value='Edit' />
</div>
</fieldset>
</form>
The problem with the above code is thats its not updating my database and i am getting
Database Error: Unable to update record
UPDATE
i have gone back to my old files and now this dosent work
ok i gone right back to the basic files i had....
<meta http-equiv="refresh" content="0; url=../contacts.php"> <?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = "DELETE FROM contacts
WHERE created='$_GET[id]'";
mysql_select_db('pcrepairs');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not delete data: ' . mysql_error());
}
echo "Deleted data successfully\n";
mysql_close($conn);
?>
i am now getting this error
Could not delete data: Unknown column 'created' in 'where clause'
You seems to be using users table in your delete query.Does the users table exist?,if not please change it to contacts.Please let me know
Thanks
Forgetting PHP for a moment if you were to issue a SQL query, say in the command-line, you would need to use single quotes to signify the search string.
So it would like this:
DELETE FROM users WHERE id = '100';
The above has to remain true when you construct the query via PHP:
$query = "DELETE FROM users WHERE id='".$mysqli->real_escape_string($_GET['id'])."'";
If your code's failing, you really need to get into the mindset of debugging your code. Approach it in smaller chunks and work your way back up. So for instance, you can try executing the above query with a hard-coded id value in the console and confirm it works.
Can you try echo'ing the $query value before running it through mysqli? Get that sql statement and try manually running it through the database. You may also want to double check your data types. You can get an error if you try, for example, setting an NUMBER/INT field with a string value.
You forgot the commas in your SQL UPDATE statement:
$query = "update contacts
set
name = '".$mysqli->real_escape_string($_POST['name'])."',
surname = '".$mysqli->real_escape_string($_POST['surname'])."',
email = '".$mysqli->real_escape_string($_POST['email'])."',
pcode = '".$mysqli->real_escape_string($_POST['pcode'])."',
website = '".$mysqli->real_escape_string($_POST['website'])."',
gender = '".$mysqli->real_escape_string($_POST['gender'])."',
mobile = '".$mysqli->real_escape_string($_POST['mobile'])."',
phone = '".$mysqli->real_escape_string($_POST['phone'])."',
county = '".$mysqli->real_escape_string($_POST['county'])."',
town = '".$mysqli->real_escape_string($_POST['town'])."',
address = '".$mysqli->real_escape_string($_POST['address'])."',
notes = '".$mysqli->real_escape_string($_POST['notes'])."',
business = '".$mysqli->real_escape_string($_POST['business'])."'
where id='".$mysqli->real_escape_string($_REQUEST['id'])."'";
You also need to review your HTML code.
EDIT
The SQL syntax for an update statement is:
UPDATE my_table_name SET col1='value1', col2='value2', ... WHERE conditions
And this should work for the delete query:
$query = "DELETE FROM users WHERE id='".$mysqli->real_escape_string($_GET['id'])."'";
If you are using PHP5+ I recommend you to use PDO instead of the old sqlite functions.
You also need to verify your data before saving into the DB.