PHP - How To Insert Multiple Check Box Values Into Table
I have displayed check box values(ugroup field) from ugroups table.now what i want to do is,when user select multiple check boxes and submit it should be insert into relavent feild in table.now it's insert check boxes values.but not in relevant field.this is my code.Please help me.
//select ugroup's from group table. <?php $result = "SELECT id,ugroup FROM group"; $res_result = db::getInstance()->query($result); ?> <form action="db_sql/db_add_page.php" method="get"> Tittle :<input type="text" size="100" name="tittle" /> Description :<textarea cols="80" id="editor1" name="description" rows="10"></textarea> //Display ugroups in textboxes and checkboxes <?php while( $line=$res_result->fetch(PDO::FETCH_ASSOC)) { echo '<input type="checkbox" name="group[]" value=" '. $line['ugroup'] .'" />'; echo'<input type="text" name="ugroup" disabled="disabled" value=" '. $line['ugroup'] .'" size="7" "/>'; echo ' '; } ?><input type="submit" value="Submit"> </form>db_add_page.php if(isset($_POST)) { $tittle = $_POST['tittle']; $description = $_POST['description']; $ugroup = $_POST['group']; $acc_status = "INSERT INTO add_services (id,tittle,description,g1,g2,g3,g4,g5,g6,g7,g8) VALUES(NULL,'".$tittle."','".$description."','".$ugroup[0]."','".$ugroup[1]."','".$ugroup[2]."',' ".$ugroup[3]."','".$ugroup[4]."','".$ugroup[5]."','".$ugroup[6]."','".$ugroup[7]."')"; $rate = db::getInstance()->exec($acc_status); if(!$rate){ echo '<script type="text/javascript">alert("Update Error !");</script>'; }else{ header('Location:../add_page.php'); echo '<script type="text/javascript">alert("Successfuly Updated User Group !");</script>'; } }Attached Files group.jpg 22.14KB 0 downloads add_services.jpg 21.36KB 0 downloads Similar Tutorials
Table Issue - Multiple Location Values For User Pushes Values Out Of Row Instead Of Wrapping In Cell
I have 3 tables.
1)state(s_id, details);
2)univer(u_id,details,s_id);
3)sub(su-id,daetails,u_id, s_id)
Now there is a problem, for ever selection of state and univer there is multiple choice of sub and they can be common in different selections. And how to store these values in databse and can call in a selection menu. so how can i solve it?
Edited by N0name, 31 May 2014 - 10:38 PM. Hi all, i've got a string ($currentcatid) which contains one number which changes dependant on which page the visitor is on.. ie it may be perhaps "23" or "17" . I need to do a check against this string to see if it contains any of the following values .. 31,32, 1, 24 . I cant remember how i did it before but i think it was with pipes.. something along the lines of if ($currentcatid =="31"||"32"||"1"||"24") { action } can anyone help? Thanks Hi, My company has 240+ locations and as such some users (general managers) cover multiple sites. When I run a query to pull user information, when the user has multiple sites to his or her name, its adds the second / third sites to the next columns, rather than wrapping it inside the same table cell. It also works the opposite way, if a piece of data is missing in the database and is blank, its pull the following columns in. Both cases mess up the table and formatting. I'm extremely new to any kind of programming and maybe this isn't the forum for this question but figured I'd give it a chance since I'm stuck. The HTML/PHP code is below: <table id="datatables-column-search-select-inputs" class="table table-striped" style="width:100%"> <thead> <tr> <th>ID</th> <th>FirstName</th> <th>LastName</th> <th>Username</th> <th>Phone #</th> <th>Location</th> <th>Title</th> <th>Role</th> <th>Actions</th> </tr> </thead> <tbody> <?php //QUERY TO SELECT ALL USERS FROM DATABASE $query = "SELECT * FROM users"; $select_users = mysqli_query($connection,$query);
// SET VARIABLE TO ARRAY FROM QUERY while($row = mysqli_fetch_assoc($select_users)) { $user_id = $row['user_id']; $user_firstname = $row['user_firstname']; $user_lastname = $row['user_lastname']; $username = $row['username']; $user_phone = $row['user_phone']; $user_image = $row['user_image']; $user_title_id = $row['user_title_id']; $user_role_id = $row['user_role_id'];
// POPULATES DATA INTO THE TABLE echo "<tr>"; echo "<td>{$user_id}</td>"; echo "<td>{$user_firstname}</td>"; echo "<td>{$user_lastname}</td>"; echo "<td>{$username}</td>"; echo "<td>{$user_phone}</td>";
//PULL SITE STATUS BASED ON SITE STATUS ID $query = "SELECT * FROM sites WHERE site_manager_id = {$user_id} "; $select_site = mysqli_query($connection, $query); while($row = mysqli_fetch_assoc($select_site)) { $site_name = $row['site_name']; echo "<td>{$site_name}</td>"; } echo "<td>{$user_title_id}</td>"; echo "<td>{$user_role_id}</td>"; echo "<td class='table-action'> <a href='#'><i class='align-middle' data-feather='edit-2'></i></a> <a href='#'><i class='align-middle' data-feather='trash'></i></a> </td>"; //echo "<td><a href='users.php?source=edit_user&p_id={$user_id}'>Edit</a></td>"; echo "</tr>"; } ?>
<tr> <td>ID</td> <td>FirstName</td> <td>LastName</td> <td>Username</td> <td>Phone #</td> <td>Location</td> <td>Title</td> <td>Role</td> <td class="table-action"> <a href="#"><i class="align-middle" data-feather="edit-2"></i></a> <a href="#"><i class="align-middle" data-feather="trash"></i></a> </td> </tr> </tbody> <tfoot> <tr> <th>ID</th> <th>FirstName</th> <th>LastName</th> <th>Username</th> <th>Phone #</th> <th>Location</th> <th>Title</th> <th>Role</th> </tr> </tfoot> </table>
Hi guys, im inserting data into the table using drop-down list & multi select list,well it works very well. but i need to make sure i should not insert same StudentID & CourseID twice. here my code for you could anyone tell me pls where should i write code to check existing data? <?php $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("uni", $con)or trigger_error('MySQL error: ' . mysql_error()); $result = mysql_query("SELECT * FROM student") or trigger_error('MySQL error: ' . mysql_error()); echo '<select name="sid">'; while($row = mysql_fetch_array($result)) { echo '<option value="' . $row['StudentID'] . '">' . $row['StudentName'] . '</option>'; } echo '</select>'; // ---------------- ?> </div> <div class="style41" id="Layer7"> <?php $result = mysql_query("SELECT * FROM course") or trigger_error('MySQL error: ' . mysql_error()); echo '<select name ="cid[]" multiple="multiple" size="10">'; while($row = mysql_fetch_array($result)) { echo '<option value="' . $row['CourseID'] . '">' . $row['CourseName'] . '</option>'; } echo '</select>'; mysql_close($con); ?> ------------------------------------ <?php $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("uni", $con)or trigger_error('MySQL error: ' . mysql_error()); if (!empty($_POST['sid']) && !empty($_POST['cid'])) { $ct = 0; $student = $_POST['sid']; foreach ($_POST['cid'] as $key => $course) { $sql = "INSERT INTO take (StudentID, CourseID) VALUES('".mysql_real_escape_string($student)."', '".mysql_real_escape_string($course)."')"; $query = mysql_query($sql) or trigger_error('MySQL error: ' . mysql_error()); if (mysql_affected_rows() > 0){$ct++;} } echo $ct . ' rows added.'; } mysql_close($con); ?> What gets put in for the values is my problem. I have tried every way I can think of but I get errors in the code or I don't get the row inserted. Can anyone give me a code sample using $ variables, preferably a multi-line list? I would have to fix up my code to show you what I am trying as it is in between tries now. I have to be doing something wrong and may have to put together a simple test script but a working example would be better. Everything I look at on the web shows "xxxxx xxxx" examples not $variables. Thanks in advance. I have 3 tables w/ the following fields: Cities id | state_id | city_name States id | state_name New_cities id | state_id | city_name I am trying to write a script (and still working on it) that will INSERT new cities in cities WHERE New_cities.state_id = Cities.state_id. Obviously I am still in testing and results sort out, but honest to all hell, I might be going about this all wrong, and would appreciate any comments, criticism, assistance or feedback on what I am trying to do. <?php $query = "SELECT * FROM cities, states, new_cities"; if ($results = mysqli_query($cxn, $query)) { $row_cnt = mysqli_num_rows($results); echo $row_cnt . " Total Records in Query.<br /><br />"; if (mysqli_num_rows($results)) { while ($row = mysqli_fetch_array($results)) { if ($row['cities']['state_id'] == $row['new_cities']['new_state_id']) { $insert_city_query = "INSERT INTO cities id, new_state_id, city_name VALUES ('','$new_state_id','$city_name')" or mysqli_error(); } //if ($row['cities']['state_id'] == $row['new_cities']['new_state_id']) echo "$row[new_city_name]<br />"; } //while ($row = mysqli_fetch_array($results)) } //if (mysqli_num_rows($results)) } //if ($results = mysqli_query($cxn, $query)) ?> Apologies... I'm a noob trying to reverse engineer code. I have a script that can retrieve values from a MySQL database (based on a session login that recognizes which user you are) and places those values into the text fields of a form, pre-populating the form. Code: [Select] <?php mysql_connect('localhost', 'db', 'password'); mysql_select_db('users'); $id = mysql_real_escape_string($_SESSION['userid']); $select = "SELECT * FROM user_info WHERE md5(Member_No) = '$id';"; $query = mysql_query($select); if ($row = mysql_fetch_array($query)) { ?> <form> FIRST name: <input type="text" name="First" value="<?php echo stripslashes($row['First']); ?>" LAST name: <input type="text" name="Last" value="<?php echo stripslashes($row['Last']); ?>" > Birthday: <input type="text" name="Birthday" value="<?php echo stripslashes($row['Birthday']); ?>" <input type="submit" value="Submit"> </form> <?php } ?> I want to be able to connect to that same database and update ALL the values (3 in the example above) with the single click of the form button. I think I was told some time ago that it's not possible to update all the values at once? Thanks, ~Wayne Dear All Members here is my table data.. (4 Columns/1row in mysql table)
id order_no order_date miles How to split(miles) single column into (state, miles) two columns and output like following 5 columns /4rows in mysql using php code.
(5 Columns in mysql table) id order_no order_date state miles 310 001 02-15-2020 MI 108.53 310 001 02-15-2020 Oh 194.57 310 001 02-15-2020 PA 182.22
310 001 02-15-2020 WA 238.57 ------------------my php code -----------
<?php
if(isset($_POST["add"]))
$miles = explode("\r\n", $_POST["miles"]);
$query = $dbh->prepare($sql);
$lastInsertId = $dbh->lastInsertId(); if($query->execute()) {
$sql = "update tis_invoice set flag='1' where order_no=:order_no"; $query->execute();
} ----------------- my form code ------------------
<?php -- Can any one help how to correct my code..present nothing inserted on table
Thank You Edited February 8, 2020 by karthicbabuOk I'm trying to insert multiple rows by using a while loop but having problems. At the same time, need to open a new mysql connection while running the insert query, close it then open the previous mysql connection. I managed to insert multiple queries before using a loop, but for this time, the loop does not work? I think it is because I am opening another connection... yh that would make sense actually? Here is the code: $users = safe_query("SELECT * FROM ".PREFIX."user"); while($dp=mysql_fetch_array($users)) { $username = $dp['username']; $nickname = $dp['nickname']; $pwd1 = $dp['password']; $mail = $dp['email']; $ip_add = $dp['ip']; $wsID = $dp['userID']; $registerdate = $dp['registerdate']; $birthday = $dp['birthday']; $avatar = $dp['avatar']; $icq = $dp['icq']; $hp = $dp['homepage']; echo $username." = 1 username only? :("; // ----- Forum Bridge user insert ----- $result = safe_query("SELECT * FROM `".PREFIX."forum`"); $ds=mysql_fetch_array($result); $forum_prefix = $ds['prefix']; define(PREFIX_FORUM, $forum_prefix); define(FORUMREG_DEBUG, 0); $con = mysql_connect($ds['host'], $ds['user'], $ds['password']) or system_error('ERROR: Can not connect to MySQL-Server'); $condb = mysql_select_db($ds['db'], $con) or system_error('ERROR: Can not connect to database "'.$ds['db'].'"'); include('../_phpbb_func.php'); $phpbbpass = phpbb_hash($pwd1); $phpbbmailhash = phpbb_email_hash($mail); $phpbbsalt = unique_id(); safe_query("INSERT INTO `".PREFIX_FORUM."users` (`username`, `username_clean`, `user_password`, `user_pass_convert`, `user_email`, `user_email_hash`, `group_id`, `user_type`, `user_regdate`, `user_passchg`, `user_lastvisit`, `user_lastmark`, `user_new`, `user_options`, `user_form_salt`, `user_ip`, `wsID`, `user_birthday`, `user_avatar`, `user_icq`, `user_website`) VALUES ('$username', '$username', '$phpbbpass', '0', '$mail', '$phpbbmailhash', '2', '0', '$registerdate', '$registerdate', '$registerdate', '$registerdate', '1', '230271', '$phpbbsalt', '$ip_add', '$wsID', '$birthday', '$avatar', '$icq', '$hp')"); if (FORUMREG_DEBUG == '1') { echo "<p><b>-- DEBUG -- : User added: ".mysql_affected_rows($con)."<br />"; echo "<br />-- DEBUG -- : Query used: ".end($_mysql_querys)."</b></p><br />"; $result = safe_query("SELECT user_id from ".PREFIX_FORUM."users WHERE username = '$username'"); $phpbbid = mysql_fetch_row($result); safe_query("INSERT INTO `".PREFIX_FORUM."user_group` (`group_id`, `user_id`, `group_leader`, `user_pending`) VALUES ('2', '$phpbbid[0]', '0', '0')"); safe_query("INSERT INTO `".PREFIX_FORUM."user_group` (`group_id`, `user_id`, `group_leader`, `user_pending`) VALUES ('7', '$phpbbid[0]', '0', '0')"); mysql_close($con); } include('../_mysql.php'); mysql_connect($host, $user, $pwd) or system_error('ERROR: Can not connect to MySQL-Server'); mysql_select_db($db) or system_error('ERROR: Can not connect to database "'.$db.'"'); } So I need to be able to insert these rows using the while loop.. how can I do this? I really appreciate any help. Hello all, I am trying to learn OOP in PHP so please forgive my ignorance. I seem to be having difficulty inserting data into my database from checkbox items. My database has a column for each each fruit. I would like for each column to be populated with either a one(1) for checked or a zero(0) for not checked. Currently, my attempts have failed. I can either get all checkboxes to insert all zeros or I can get the first column to insert a one(1) while the others as zeros. Is there anybody here that can help me figure out what I am doing wrong and help me to re-work my code so I can get this to work? If anybody can help me using OOP methods that would be fantastic. Thank you all in advance.
$preffruit->create_preffruit(array( 'fruit_apple' => escape(Input::get(['fruit_selection'][0]) ? 1 : 0), 'fruit_orange' => escape(Input::get(['fruit_selection'][1]) ? 1 : 0), 'fruit_banana' => escape(Input::get(['fruit_selection'][2]) ? 1 : 0), 'fruit_pear' => escape(Input::get(['fruit_selection'][3]) ? 1 : 0), 'fruit_kiwi' => escape(Input::get(['fruit_selection'][4]) ? 1 : 0) )); <input type="checkbox" name="fruit_selection[]" value="fruit_apple"> <input type="checkbox" name="fruit_selection[]" value="fruit_orange"> <input type="checkbox" name="fruit_selection[]" value="fruit_banana"> <input type="checkbox" name="fruit_selection[]" value="fruit_pear"> <input type="checkbox" name="fruit_selection[]" value="fruit_kiwi"> public function insert_preffruit($table, $fields = array()) { $keys = array_keys($fields); $values = ''; $x = 1; foreach($fields as $field) { $values .= '?'; if($x < count($fields)) { $values .= ', '; } $x++; } $sql = "INSERT INTO preffruit (`user_id`, `" . implode('`, `', $keys) . "`) VALUES (LAST_INSERT_ID(), {$values})"; if(!$this->query($sql, $fields)->error()) { return true; } return false; } Edited September 23, 2020 by ke-jo I have a form where a user can duplicate part of a form like below: I've named the fields with the HTML arrays (ie. "fieldName[]") and came up with this: //--> CONTROLLERS $system_controllers_qty = $_POST['system_controllers_qty']; $system_controllers_make = $_POST['system_controllers_make']; $system_controllers_model = $_POST['system_controllers_model']; $system_controllers_serial_no = $_POST['system_controllers_serial_no']; for ($i = 0; $i < count($system_controllers_qty); $i++) { echo "qty " . clean($system_controllers_qty[$i]) . "<br/>"; echo "make " . clean($system_controllers_make[$i]) . "<br/>"; echo "model " . clean($system_controllers_model[$i]) . "<br/>"; echo "serial_no " . clean($system_controllers_serial_no[$i]) . "<br/>"; } //--> CPUS $system_cpus_qty = $_POST['system_cpus_qty']; $system_cpus_model = $_POST['system_cpus_model']; $system_cpus_serial_no = $_POST['system_cpus_serial_no']; $system_cpus_speed = $_POST['system_cpus_speed']; for ($i = 0; $i < count($system_cpus_qty); $i++) { echo "qty " . clean($system_cpus_qty[$i]) . "<br/>"; echo "model " . clean($system_cpus_model[$i]) . "<br/>"; echo "serial_no " . clean($system_cpus_serial_no[$i]) . "<br/>"; echo "speed " . clean($system_cpus_speed[$i]) . "<br/>"; } //--> DISKS $system_disks_qty = $_POST['system_disks_qty']; $system_disks_make = $_POST['system_disks_make']; $system_disks_model_no = $_POST['system_disks_model_no']; $system_disks_size = $_POST['system_disks_size']; $system_disks_serial_no = $_POST['system_disks_serial_no']; for ($i = 0; $i < count($system_disks_qty); $i++) { echo "qty " . clean($system_disks_qty[$i]) . "<br/>"; echo "make " . clean($system_disks_make[$i]) . "<br/>"; echo "model_no " . clean($system_disks_model_no[$i]) . "<br/>"; echo "size " . clean($system_disks_size[$i]) . "<br/>"; echo "serial_no " . clean($system_disks_serial_no[$i]) . "<br/>"; } //--> MEMORY $system_memory_qty = $_POST['system_memory_qty']; $system_memory_serial_no = $_POST['system_memory_serial_no']; $system_memory_manf = $_POST['system_memory_manf']; $system_memory_part_no = $_POST['system_memory_part_no']; $system_memory_size = $_POST['system_memory_size']; for ($i = 0; $i < count($system_memory_qty); $i++) { echo "qty " . clean($system_memory_qty[$i]) . "<br/>"; echo "serial " . clean($system_memory_serial_no[$i]) . "<br/>"; echo "manf " . clean($system_memory_manf[$i]) . "<br/>"; echo "part_no " . clean($system_memory_part_no[$i]) . "<br/>"; echo "size " . clean($system_memory_size[$i]) . "<br/>"; } This just outputs all the fields I post at the moment. Say I have 3 different disk types, it's going to loop 3 times. Is it possible to make this all into 1 giant query or am I better off doing each query separately? Each section is a different table. Hello PHP World, I don't have access to the database yet for the project I am working on so I created a work around until I get full access to the mysql database. I Code: [Select] <?php $xml_file = "affiliate.xml"; // OPEN XML FILE ###################################################### if(!$xml=simplexml_load_file($xml_file)){ trigger_error('Error reading XML file',E_affiliate_ERROR); } if(!empty($_GET['add'])){ $u_name = stripslashes($_POST['name']); $u_company = stripslashes($_POST['company']); $u_address = stripslashes($_POST['address']); $u_city = stripslashes($_POST['city']); $u_state = stripslashes($_POST['state']); $u_phone = stripslashes($_POST['phone']); $u_email = stripslashes($_POST['email']); $u_desc = stripslashes($_POST['description']); $u_region = stripslashes($_POST['region']); // Generate new (appended) ID foreach($xml as $affiliate){ $last_id = $affiliate->uid; } $id = $last_id+1; // Add node $x = $xml->addChild("affiliate"); $x->addChild("uid",$id); $x->addChild("name",$u_name); $x->addChild("company",$u_company); $x->addChild("address",$u_address); $x->addChild("city",$u_city); $x->addChild("state",$u_state); $x->addChild("phone",$u_phone); $x->addChild("email",$u_email); $x->addChild("description",$u_desc); $x->addChild("region",$u_region); $xml->asXML($xml_file); } ?> html form Code: [Select] <br /> <br /> <h1>Affiliate </h1> <form name="xml_writing" method="post" action="?add=t"> <table width="393"> <tr><td width="56"> Name:<br /></td><td width="206"> <input type="text" name="name" width="150"/></td> <td>Region:</td> <td><select name="region" value="options"> <option value="resellerNE">NorthEast</option> <option value="resellerSE">SouthEast</option> <option value="resellerC">Central</option> <option value="resellerNE">NorthWest</option> <option value="resellerNE">SouthWest</option> <option value="resellerNE">International</option> </select></td> </tr> <tr> <td> Company:<br /></td><td> <input type="text" name="company" width="150" /></td> </tr> <tr><td> Address:<br /></td><td> <input type="text" name="address" width="150"/></td> </tr> <tr><td height="45"> City:<br /></td><td> <input type="text" name="city" width="150"/></td> <tr><td> State:<br /></td><td> <input type="text" name="state" width="150"/></td> <tr><td> Phone:<br /></td><td> <input type="text" name="phone" width="150"/></td> <tr><td> Email:<br /></td><td> <input type="text" name="email" width="150"/></td> </tr> <tr><td colspan="2"> Short description of yourself, your practice, your services, and other information of interest to potential clients or collaborators.<br /></td> <tr><td colspan="2"> <textarea name="description" style="width: 406px; height: 136px;"></textarea></td> </tr> <tr><td></td><td> <input type="submit" value="Submit" /></td> </tr> </table></form> What I am trying to do is have on submit check against the email node in the xml file to see if email exist. if exist string already a member else insert. if you can help with code or point to something that will help. "Everyone needs a mentor to lead them into success." Quote by Shelby Poston Hello, i've got this code, to insert some form data into my db, it checks for a value if it exists already, it won't insert, now i want to add another value to check, but i don't know how. This is my code: Code: [Select] <?php if(isset($_POST['submit'])){ if (strlen($_POST['code']) == 12 && substr($_POST['code'],0,6) == '610147'){ $code = $_POST['code']; $select_query = mysql_query("SELECT * FROM jupiter WHERE code = '$code'"); if(mysql_num_rows($select_query) == 0){ $remote_addr = $_SERVER['REMOTE_ADDR']; $secret = $_POST['euro']; mysql_query("INSERT INTO jupiter(code,euro,ip,date,used) VALUES('$code','$secret','$remote_addr',CURDATE(),'n')"); } Print "<font color='green'>OK</font>"; } else { Print "<font color='red'>Error</font>"; } }?> This checks if "code" already exists, now i want to also have it check for "ip" Can someone help me out here please. Thanks ! Hello, i am inserting some form data into my mysql db, i happen to get some duplicates so i want to check first if the entry exists already before i insert. my current code: Code: [Select] <?php if(isset($_POST['submit'])) { ?> <?php if (strlen($_POST['code']) == 19 && substr($_POST['code'],0,7) == '5541258') { mysql_query("INSERT INTO table(code,secret,ip,date) VALUES('$_POST[code]','$_POST[secret]','$_SERVER[REMOTE_ADDR]',CURDATE())"); Print "<font color='green'>The code will be checked now</font>"; } else { Print "<font color='red'>The code is invalid</font>"; } ?><?php } ?> I would like to use the value 'code' to check if the entry exists, that one is unique for each entry. How would i do that ? Thanks ! I have a register script, and I am wanting to make it so that if the username field contains, lets say "mod", "ass", and more, then it'll return an error and wont let them register. //database create table mydata ( id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, fname varchar(20), phoneno int(12) NOT NULL /*......*/ ); //class my data php <?php include('connect.php'); class InsertMydata { public function insertnow($fname, $phoneno) { $connect = new Connect; $insrt = $db -> prepare('INSERT INTO mydata (fname, phoneno) VALUES (?,?)'); $insrt -> execute(array($fname, $phoneno)); } } ?> //insernow validate form <?php include('../classs/mydata.php'); //Declare data and error arrays $errors = []; $mydara = []; if(!preg_match('/^[a-zA-Z]{4,15}$/', $_POST['fname'])) { $errors['fname'] = 'Enter full name!'; } //this block not working even the phone exist $connect = new Connect; $phoneno = $_POST['phoneno']; $checkiexist = $connect -> prepare('SELECT * FROM mydata WHERE phoneno = ?'); $checkiexist -> execute([$phoneno]); if($checkiexist->rowCount() > 0) { $errors['phonenoexist'] = 'Try another phone number!'; } if(!empty($errors)){ $data['success'] = false; $data['errors'] = $errors; }else{ $data['success'] = true; $data['message'] = 'success message!'; $mydata = new InsertMydata; $mydata -> insertnow($fname, $phoneno); } echo json_encode($data); ?> //my ajax $("#insertbtn").click( function(e) { var fname = $('#fname').val(), phoneno = $('#phoneno').val(), $.ajax({ url: 'insertnow.php', type: 'POST', data: {fname:fname, phoneno:phoneno}, dataType: "JSON", encode: true, }).done( function (data) { if (data.success == false) { if (data.errors.fname) { $('#fname').append('<p class="text-danger">' + data.errors.fname + '</p>'); } if (data.errors.phonenoexist) { $('.card-header').append('<div class="alert alert-info alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+data.errors.phonenoexist+'</div>'); } } else { $('.card-header').append('<div class="alert alert-success alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+data.message+'</div>'); } }); e.preventDefault(); }); //the problem is, the code insert data even if the phone exist why? the problem is, the code insert data even if the phone exist why? Edited April 8 by mahendaHi everyone. I have a registration form on my website that returns errors if the form isnt filled out correctly. An example of the code that returns the errors is: // if first name is blank return error if (!$first_name) { echo "Please enter your first name!<br />"; } // if first name contains invalid charcters return error if (preg_match('/[^a-zA-Z\s]/', $first_name)) { echo "Your first name contains invalid charcters!<br />"; } // set first name maximum length if ($first_name && !preg_match('/[^a-zA-Z0-9\s]/', $first_name)) { if (strlen($first_name) >25) { echo "The maximum length for first name is 25 characters!<br />"; } } Iv wrote it like this so that i can get multiple error messages appearing at the same time. When it comes to writing the form data to the database im using the following: if ($first_name && !preg_match('/[^a-zA-Z\s]/', $first_name) && strlen($first_name) <26 && $last_name && !preg_match('/[^a-zA-Z\s]/', $last_name) && strlen($last_name) <26 && $dob_day != "Day" && $dob_month != "Month" && $dob_year != "Year" && $gender != "Select" && $email && filter_var($email, FILTER_VALIDATE_EMAIL) && $confirm_email && $email == $confirm_email && $email_count == 0 && $town && !preg_match('/[^a-zA-Z0-9\s]/', $town) && strlen($town) < 26 && $location != "Select" && $postcode && !preg_match('/[^a-zA-Z0-9\s]/', $postcode) && $username && !preg_match('/[^a-zA-Z\s]/', $username) && strlen($username) >2 && strlen($username) <25 && $username_count == 0 && $password && strlen($password) >5 && strlen($password) <26 && $confirm_password && $password == $confirm_password) { // code to write to database here } I was wondering if there was a better way to confirm that all the form data is ok, and if so write the data to the database? Im new to php and would love to learn a way to make this easier instead of typing out loads of lines of code. Thanks to anyone that can help me. |