PHP: вставка значений из формы в MySQL

Я создал таблицу users в mysql с терминала, и я пытаюсь создать простую задачу: вставьте значения из формы. Это мой dbConfig file

 <?php $mysqli = new mysqli("localhost", "root", "pass", "testDB"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } ?> 

и это мой Index.php .

 <!doctype html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="description" content="$1"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="style.css"> <title>test</title> <?php include_once 'dbConfig.php'; ?> </head> <body> <?php if(isset($_POST['save'])){ $sql = "INSERT INTO users (username, password, email) VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')"; } ?> <form method="post"> <label id="first"> First name:</label><br/> <input type="text" name="username"><br/> <label id="first">Password</label><br/> <input type="password" name="password"><br/> <label id="first">Email</label><br/> <input type="text" name="email"><br/> <button type="submit" name="save">save</button> <button type="submit" name="get">get</button> </form> </body> </html> 

После нажатия кнопки сохранения ничего не происходит, база данных по-прежнему пуста. Я попытался echo'ing -запрос INSERT и он принимает все значения из формы, как предполагается. После того, как я попытаюсь проверить, работает ли это с терминала, я вхожу в мой sql чтобы вернуть все данные из таблицы пользователей, и я получаю пустой набор.

Следующий код просто объявляет строковую переменную, содержащую запрос MySQL:

$sql = "INSERT INTO users (username, password, email) VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')";

Он не выполняет запрос. Для этого вам нужно использовать некоторые функции, но позвольте мне сначала объяснить что-то еще.

NEVER TRUST USER INPUT : вы никогда не должны добавлять пользовательский ввод (например, ввод формы из $_GET или $_POST ) непосредственно в ваш запрос. Кто-то может тщательно манипулировать вводом таким образом, чтобы он мог нанести большой ущерб вашей базе данных. Это называется SQL Injection. Вы можете узнать больше об этом здесь

Чтобы защитить ваш скрипт от такой атаки, вы должны использовать Подготовленные заявления. Подробнее о подготовленных заявлениях здесь

Включите подготовленные заявления в свой код следующим образом:

$sql = "INSERT INTO users (username, password, email) VALUES (?,?,?)"

Обратите внимание, как ? используются в качестве заполнителей для значений. Затем вы должны подготовить инструкцию, используя mysqli_prepare :

$stmt = mysqli_prepare($sql);

Затем начните привязывать входные переменные к подготовленному оператору:

$stmt->bind_param("sss", $_POST['username'], $_POST['email'], $_POST['password']);

И, наконец, выполните подготовленные заявления. (Здесь происходит фактическая вставка)

$stmt->execute();

ПРИМЕЧАНИЕ. Хотя это и не является частью вопроса, я настоятельно рекомендую вам никогда не хранить пароли в ясном тексте. Вместо этого вы должны использовать password_hash для хранения хэша пароля

В вашем коде есть две проблемы.

  1. Никаких действий не найдено в форме.
  2. Вы не выполнили запрос mysqli_query ()

dbConfig.php

 <?php $conn=mysqli_connect("localhost","root","password","testDB"); if(!$conn) { die("Connection failed: " . mysqli_connect_error()); } ?> 

index.php

  include('dbConfig.php'); <!Doctype html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="description" content="$1"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="style.css"> <title>test</title> </head> <body> <?php if(isset($_POST['save'])) { $sql = "INSERT INTO users (username, password, email) VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')"; $result = mysqli_query($conn,$sql); } ?> <form action="index.php" method="post"> <label id="first"> First name:</label><br/> <input type="text" name="username"><br/> <label id="first">Password</label><br/> <input type="password" name="password"><br/> <label id="first">Email</label><br/> <input type="text" name="email"><br/> <button type="submit" name="save">save</button> </form> </body> </html> в  include('dbConfig.php'); <!Doctype html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="description" content="$1"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="style.css"> <title>test</title> </head> <body> <?php if(isset($_POST['save'])) { $sql = "INSERT INTO users (username, password, email) VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')"; $result = mysqli_query($conn,$sql); } ?> <form action="index.php" method="post"> <label id="first"> First name:</label><br/> <input type="text" name="username"><br/> <label id="first">Password</label><br/> <input type="password" name="password"><br/> <label id="first">Email</label><br/> <input type="text" name="email"><br/> <button type="submit" name="save">save</button> </form> </body> </html> 
 <?php $username="root"; $password=""; $database="test"; #get the data from form fields $Id=$_POST['Id']; $P_name=$_POST['P_name']; $address1=$_POST['address1']; $address2=$_POST['address2']; $email=$_POST['email']; mysql_connect(localhost,$username,$password); @mysql_select_db($database) or die("unable to select database"); if($_POST['insertrecord']=="insert"){ $query="insert into person values('$Id','$P_name','$address1','$address2','$email')"; echo "inside"; mysql_query($query); $query1="select * from person"; $result=mysql_query($query1); $num= mysql_numrows($result); #echo"<b>output</b>"; print"<table border size=1 > <tr><th>Id</th> <th>P_name</th> <th>address1</th> <th>address2</th> <th>email</th> </tr>"; $i=0; while($i<$num) { $Id=mysql_result($result,$i,"Id"); $P_name=mysql_result($result,$i,"P_name"); $address1=mysql_result($result,$i,"address1"); $address2=mysql_result($result,$i,"address2"); $email=mysql_result($result,$i,"email"); echo"<tr><td>$Id</td> <td>$P_name</td> <td>$address1</td> <td>$address2</td> <td>$email</td> </tr>"; $i++; } print"</table>"; } if($_POST['searchdata']=="Search") { $P_name=$_POST['name']; $query="select * from person where P_name='$P_name'"; $result=mysql_query($query); print"<table border size=1><tr><th>Id</th> <th>P_name</th> <th>address1</th> <th>address2</th> <th>email</th> </tr>"; while($row=mysql_fetch_array($result)) { $Id=$row[Id]; $P_name=$row[P_name]; $address1=$row[address1]; $address2=$row[address2]; $email=$row[email]; echo"<tr><td>$Id</td> <td>$P_name</td> <td>$address1</td> <td>$address2</td> <td>$email</td> </tr>"; } echo"</table>"; } echo"<a href=lab2.html> Back </a>"; ?> в <?php $username="root"; $password=""; $database="test"; #get the data from form fields $Id=$_POST['Id']; $P_name=$_POST['P_name']; $address1=$_POST['address1']; $address2=$_POST['address2']; $email=$_POST['email']; mysql_connect(localhost,$username,$password); @mysql_select_db($database) or die("unable to select database"); if($_POST['insertrecord']=="insert"){ $query="insert into person values('$Id','$P_name','$address1','$address2','$email')"; echo "inside"; mysql_query($query); $query1="select * from person"; $result=mysql_query($query1); $num= mysql_numrows($result); #echo"<b>output</b>"; print"<table border size=1 > <tr><th>Id</th> <th>P_name</th> <th>address1</th> <th>address2</th> <th>email</th> </tr>"; $i=0; while($i<$num) { $Id=mysql_result($result,$i,"Id"); $P_name=mysql_result($result,$i,"P_name"); $address1=mysql_result($result,$i,"address1"); $address2=mysql_result($result,$i,"address2"); $email=mysql_result($result,$i,"email"); echo"<tr><td>$Id</td> <td>$P_name</td> <td>$address1</td> <td>$address2</td> <td>$email</td> </tr>"; $i++; } print"</table>"; } if($_POST['searchdata']=="Search") { $P_name=$_POST['name']; $query="select * from person where P_name='$P_name'"; $result=mysql_query($query); print"<table border size=1><tr><th>Id</th> <th>P_name</th> <th>address1</th> <th>address2</th> <th>email</th> </tr>"; while($row=mysql_fetch_array($result)) { $Id=$row[Id]; $P_name=$row[P_name]; $address1=$row[address1]; $address2=$row[address2]; $email=$row[email]; echo"<tr><td>$Id</td> <td>$P_name</td> <td>$address1</td> <td>$address2</td> <td>$email</td> </tr>"; } echo"</table>"; } echo"<a href=lab2.html> Back </a>"; ?> в <?php $username="root"; $password=""; $database="test"; #get the data from form fields $Id=$_POST['Id']; $P_name=$_POST['P_name']; $address1=$_POST['address1']; $address2=$_POST['address2']; $email=$_POST['email']; mysql_connect(localhost,$username,$password); @mysql_select_db($database) or die("unable to select database"); if($_POST['insertrecord']=="insert"){ $query="insert into person values('$Id','$P_name','$address1','$address2','$email')"; echo "inside"; mysql_query($query); $query1="select * from person"; $result=mysql_query($query1); $num= mysql_numrows($result); #echo"<b>output</b>"; print"<table border size=1 > <tr><th>Id</th> <th>P_name</th> <th>address1</th> <th>address2</th> <th>email</th> </tr>"; $i=0; while($i<$num) { $Id=mysql_result($result,$i,"Id"); $P_name=mysql_result($result,$i,"P_name"); $address1=mysql_result($result,$i,"address1"); $address2=mysql_result($result,$i,"address2"); $email=mysql_result($result,$i,"email"); echo"<tr><td>$Id</td> <td>$P_name</td> <td>$address1</td> <td>$address2</td> <td>$email</td> </tr>"; $i++; } print"</table>"; } if($_POST['searchdata']=="Search") { $P_name=$_POST['name']; $query="select * from person where P_name='$P_name'"; $result=mysql_query($query); print"<table border size=1><tr><th>Id</th> <th>P_name</th> <th>address1</th> <th>address2</th> <th>email</th> </tr>"; while($row=mysql_fetch_array($result)) { $Id=$row[Id]; $P_name=$row[P_name]; $address1=$row[address1]; $address2=$row[address2]; $email=$row[email]; echo"<tr><td>$Id</td> <td>$P_name</td> <td>$address1</td> <td>$address2</td> <td>$email</td> </tr>"; } echo"</table>"; } echo"<a href=lab2.html> Back </a>"; ?> 
 <?php if(isset($_POST['save'])){ $sql = "INSERT INTO users (username, password, email) VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')"; } **mysql_query($sql) or die(mysql_error());** ?> 
 <!DOCTYPE html> <?php $con = new mysqli("localhost","root","","form"); ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Untitled Document</title> <script type="text/javascript"> $(document).ready(function(){ //$("form").submit(function(e){ $("#btn1").click(function(e){ e.preventDefault(); // alert('here'); $(".apnew").append('<input type="text" placeholder="Enter youy Name" name="e1[]"/><br>'); }); //} }); </script> </head> <body> <h2><b>Register Form<b></h2> <form method="post" enctype="multipart/form-data"> <table> <tr><td>Name:</td><td><input type="text" placeholder="Enter youy Name" name="e1[]"/> <div class="apnew"></div><button id="btn1">Add</button></td></tr> <tr><td>Image:</td><td><input type="file" name="e5[]" multiple="" accept="image/jpeg,image/gif,image/png,image/jpg"/></td></tr> <tr><td>Address:</td><td><textarea cols="20" rows="4" name="e2"></textarea></td></tr> <tr><td>Contact:</td><td><div id="textnew"><input type="number" maxlength="10" name="e3"/></div></td></tr> <tr><td>Gender:</td><td><input type="radio" name="r1" value="Male" checked="checked"/>Male<input type="radio" name="r1" value="feale"/>Female</td></tr> <tr><td><input id="submit" type="submit" name="t1" value="save" /></td></tr> </table> <?php //echo '<pre>';print_r($_FILES);exit(); if(isset($_POST['t1'])) { $values = implode(", ", $_POST['e1']); $imgarryimp=array(); foreach($_FILES["e5"]["tmp_name"] as $key=>$val){ move_uploaded_file($_FILES["e5"]["tmp_name"][$key],"images/".$_FILES["e5"]["name"][$key]); $fname = $_FILES['e5']['name'][$key]; $imgarryimp[]=$fname; //echo $fname; if(strlen($fname)>0) { $img = $fname; } $d="insert into form(name,address,contact,gender,image)values('$values','$_POST[e2]','$_POST[e3]','$_POST[r1]','$img')"; if($con->query($d)==TRUE) { echo "Yoy Data Save Successfully!!!"; } } exit; // echo $values;exit; //foreach($_POST['e1'] as $row) //{ $d="insert into form(name,address,contact,gender,image)values('$values','$_POST[e2]','$_POST[e3]','$_POST[r1]','$img')"; if($con->query($d)==TRUE) { echo "Yoy Data Save Successfully!!!"; } //} //exit; } ?> </form> <table> <?php $t="select * from form"; $y=$con->query($t); foreach ($y as $q); { ?> <tr> <td>Name:<?php echo $q['name'];?></td> <td>Address:<?php echo $q['address'];?></td> <td>Contact:<?php echo $q['contact'];?></td> <td>Gender:<?php echo $q['gender'];?></td> </tr> <?php }?> </table> </body> </html> , <!DOCTYPE html> <?php $con = new mysqli("localhost","root","","form"); ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Untitled Document</title> <script type="text/javascript"> $(document).ready(function(){ //$("form").submit(function(e){ $("#btn1").click(function(e){ e.preventDefault(); // alert('here'); $(".apnew").append('<input type="text" placeholder="Enter youy Name" name="e1[]"/><br>'); }); //} }); </script> </head> <body> <h2><b>Register Form<b></h2> <form method="post" enctype="multipart/form-data"> <table> <tr><td>Name:</td><td><input type="text" placeholder="Enter youy Name" name="e1[]"/> <div class="apnew"></div><button id="btn1">Add</button></td></tr> <tr><td>Image:</td><td><input type="file" name="e5[]" multiple="" accept="image/jpeg,image/gif,image/png,image/jpg"/></td></tr> <tr><td>Address:</td><td><textarea cols="20" rows="4" name="e2"></textarea></td></tr> <tr><td>Contact:</td><td><div id="textnew"><input type="number" maxlength="10" name="e3"/></div></td></tr> <tr><td>Gender:</td><td><input type="radio" name="r1" value="Male" checked="checked"/>Male<input type="radio" name="r1" value="feale"/>Female</td></tr> <tr><td><input id="submit" type="submit" name="t1" value="save" /></td></tr> </table> <?php //echo '<pre>';print_r($_FILES);exit(); if(isset($_POST['t1'])) { $values = implode(", ", $_POST['e1']); $imgarryimp=array(); foreach($_FILES["e5"]["tmp_name"] as $key=>$val){ move_uploaded_file($_FILES["e5"]["tmp_name"][$key],"images/".$_FILES["e5"]["name"][$key]); $fname = $_FILES['e5']['name'][$key]; $imgarryimp[]=$fname; //echo $fname; if(strlen($fname)>0) { $img = $fname; } $d="insert into form(name,address,contact,gender,image)values('$values','$_POST[e2]','$_POST[e3]','$_POST[r1]','$img')"; if($con->query($d)==TRUE) { echo "Yoy Data Save Successfully!!!"; } } exit; // echo $values;exit; //foreach($_POST['e1'] as $row) //{ $d="insert into form(name,address,contact,gender,image)values('$values','$_POST[e2]','$_POST[e3]','$_POST[r1]','$img')"; if($con->query($d)==TRUE) { echo "Yoy Data Save Successfully!!!"; } //} //exit; } ?> </form> <table> <?php $t="select * from form"; $y=$con->query($t); foreach ($y as $q); { ?> <tr> <td>Name:<?php echo $q['name'];?></td> <td>Address:<?php echo $q['address'];?></td> <td>Contact:<?php echo $q['contact'];?></td> <td>Gender:<?php echo $q['gender'];?></td> </tr> <?php }?> </table> </body> </html> , <!DOCTYPE html> <?php $con = new mysqli("localhost","root","","form"); ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Untitled Document</title> <script type="text/javascript"> $(document).ready(function(){ //$("form").submit(function(e){ $("#btn1").click(function(e){ e.preventDefault(); // alert('here'); $(".apnew").append('<input type="text" placeholder="Enter youy Name" name="e1[]"/><br>'); }); //} }); </script> </head> <body> <h2><b>Register Form<b></h2> <form method="post" enctype="multipart/form-data"> <table> <tr><td>Name:</td><td><input type="text" placeholder="Enter youy Name" name="e1[]"/> <div class="apnew"></div><button id="btn1">Add</button></td></tr> <tr><td>Image:</td><td><input type="file" name="e5[]" multiple="" accept="image/jpeg,image/gif,image/png,image/jpg"/></td></tr> <tr><td>Address:</td><td><textarea cols="20" rows="4" name="e2"></textarea></td></tr> <tr><td>Contact:</td><td><div id="textnew"><input type="number" maxlength="10" name="e3"/></div></td></tr> <tr><td>Gender:</td><td><input type="radio" name="r1" value="Male" checked="checked"/>Male<input type="radio" name="r1" value="feale"/>Female</td></tr> <tr><td><input id="submit" type="submit" name="t1" value="save" /></td></tr> </table> <?php //echo '<pre>';print_r($_FILES);exit(); if(isset($_POST['t1'])) { $values = implode(", ", $_POST['e1']); $imgarryimp=array(); foreach($_FILES["e5"]["tmp_name"] as $key=>$val){ move_uploaded_file($_FILES["e5"]["tmp_name"][$key],"images/".$_FILES["e5"]["name"][$key]); $fname = $_FILES['e5']['name'][$key]; $imgarryimp[]=$fname; //echo $fname; if(strlen($fname)>0) { $img = $fname; } $d="insert into form(name,address,contact,gender,image)values('$values','$_POST[e2]','$_POST[e3]','$_POST[r1]','$img')"; if($con->query($d)==TRUE) { echo "Yoy Data Save Successfully!!!"; } } exit; // echo $values;exit; //foreach($_POST['e1'] as $row) //{ $d="insert into form(name,address,contact,gender,image)values('$values','$_POST[e2]','$_POST[e3]','$_POST[r1]','$img')"; if($con->query($d)==TRUE) { echo "Yoy Data Save Successfully!!!"; } //} //exit; } ?> </form> <table> <?php $t="select * from form"; $y=$con->query($t); foreach ($y as $q); { ?> <tr> <td>Name:<?php echo $q['name'];?></td> <td>Address:<?php echo $q['address'];?></td> <td>Contact:<?php echo $q['contact'];?></td> <td>Gender:<?php echo $q['gender'];?></td> </tr> <?php }?> </table> </body> </html> 

Попробуй это:

dbConfig.php

 <?php $mysqli = new mysqli('localhost', 'root', 'pwd', 'yr db name'); if($mysqli->connect_error) { echo $mysqli->connect_error; } ?> 

Index.php

 <html> <head><title>Inserting data in database table </title> </head> <body> <form action="control_table.php" method="post"> <table border="1" background="red" align="center"> <tr> <td>Login Name</td> <td><input type="text" name="txtname" /></td> </tr> <br> <tr> <td>Password</td> <td><input type="text" name="txtpwd" /></td> </tr> <tr> <td>&nbsp;</td> <td><input type="submit" name="txtbutton" value="SUBMIT" /></td> </tr> </table> control_table.php <?php include 'config.php'; ?> <?php $name=$pwd=""; if(isset($_POST['txtbutton'])) { $name = $_POST['txtname']; $pwd = $_POST['txtpwd']; $mysqli->query("insert into users(name,pwd) values('$name', '$pwd')"); if(!$mysqli) { echo mysqli_error(); } else { echo "Successfully Inserted <br />"; echo "<a href='show.php'>View Result</a>"; } } ?> 

Когда вы нажимаете кнопку

 if(isset($_POST['save'])){ $sql = "INSERT INTO `members`(`id`, `membership_id`, `email`, `first_name`) VALUES ('".$_POST["id"]."','".$_POST["membership_id"]."','".$_POST["email"]."','".$_POST["firstname"]."')"; **if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; }** } 

Это выполнит запрос в переменной $ sql

  if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; }