PHP - Php Insert Into Two Database Tables
Hi guys,
Is it possible to insert into two tables in a database? Thanks Similar TutorialsQuote $con = mysql_connect("localhost","****","****"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("checkmyw_database", $con); mysql_query("INSERT INTO requests (username, password, email, weavecode, mobile, jobtitle, relationship, sexuality, venue, type) VALUES ('$me', '$pw', '$email','1999','$mobile','$job','$relationship','$sexuality','$venue','newuser')"); mysql_query("INSERT INTO members (username, password, email, weavecode, mobile, jobtitle, relationship, sexuality,) VALUES ('$me', '$pw', '$email','1999','$mobile','$job','$relationship','$sexuality',)"); mysql_close($con); any idea why this doesn't work? I have a form that inserts a tables records into my database. Ive tried to modify it so it will insert into two tables but it only seems to insert into one table and not the other. I made a query that counts the rows of the 2nd table and +1, which is then suppose to be inserted. Code: [Select] <?php $editFormAction = $_SERVER['PHP_SELF']; if (isset($_SERVER['QUERY_STRING'])) { $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) { $insertSQL = sprintf("INSERT INTO fleet (FleetName) VALUES (%s)", GetSQLValueString($_POST['ffleetname'], "text")); $insertSQL = sprintf("INSERT INTO ships (ShipName, FleetName, PlayerName, Image, Image2, Cost, HealthA, HealthB, MaxHealthA, MaxHealthB, `Class`, PlanetName) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", GetSQLValueString($_POST['shipname'], "text"), GetSQLValueString($_POST['fleetname'], "text"), GetSQLValueString($_POST['playername'], "text"), GetSQLValueString($_POST['image1'], "text"), GetSQLValueString($_POST['image2'], "text"), GetSQLValueString($_POST['cost'], "int"), GetSQLValueString($_POST['ha'], "int"), GetSQLValueString($_POST['hb'], "int"), GetSQLValueString($_POST['mha'], "int"), GetSQLValueString($_POST['mhb'], "int"), GetSQLValueString($_POST['class'], "int"), GetSQLValueString($_POST['select'], "text")); mysql_select_db($database_swb, $swb); $Result1 = mysql_query($insertSQL, $swb) or die(mysql_error()); $insertGoTo = "ship.php"; if (isset($_SERVER['QUERY_STRING'])) { $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?"; $insertGoTo .= $_SERVER['QUERY_STRING']; } header(sprintf("Location: %s", $insertGoTo)); } $colname_Fleetcount = "-1"; if (isset($_GET['recordID'])) { $colname_Fleetcount = (get_magic_quotes_gpc()) ? $_GET['recordID'] : addslashes($_GET['recordID']); } mysql_select_db($database_swb, $swb); $query_Fleetcount = sprintf("SELECT * FROM fleet"); $Fleetcount = mysql_query($query_Fleetcount, $swb) or die(mysql_error()); $row_Fleetcount = mysql_fetch_assoc($Fleetcount); $totalRows_Fleetcount = mysql_num_rows($Fleetcount); ?> <input name="image1" type="hidden" value="<?php echo $row_Ships['Image']; ?>" /> <input name="image2" type="hidden" value="<?php echo $row_Ships['Image2']; ?>" /> <input name="cost" type="hidden" value="<?php echo $row_Ships['Cost']; ?>" /> <input name="ha" type="hidden" value="<?php echo $row_Ships['HealthA']; ?>" /> [b] <input name="ffleetname" type="hidden" value="<?php echo $totalRows_Fleetcount = mysql_num_rows($Fleetcount) + 1;?>" /> <input name="fleetname" type="hidden" value="<?php echo $totalRows_Fleetcount = mysql_num_rows($Fleetcount) + 1;?>" />[/b] <input name="hb" type="hidden" value="<?php echo $row_Ships['HealthB']; ?>" /> <input name="mha" type="hidden" value="<?php echo $row_Ships['MaxHealthA']; ?>" /> <input name="mhb" type="hidden" value="<?php echo $row_Ships['MaxHealthB']; ?>" /> <input name="class" type="hidden" value="<?php echo $row_Ships['Class']; ?>" /> <input name="playername" type="hidden" value="<?php echo $_SESSION['MM_Username']; ?>" /> <input name="shipname" type="hidden" value="<?php echo $row_Ships['ShipName']; ?>" /> <input type="submit" name="Submit" value="Submit" /> <input type="hidden" name="MM_insert" value="form1"> </form> Any ideas? Thanks hello I want query from one table and insert in another table on another domain . each database on one domain name. for example http://www.site.com $con1 and http://www.site1.com $con. can anyone help me? my code is : <?php $dbuser1 = "insert in this database"; $dbpass1 = "insert in this database"; $dbhost1 = "localhost"; $dbname1 = "insert in this database"; // Connecting, selecting database $con1 = mysql_connect($dbhost1, $dbuser1, $dbpass1) or die('Could not connect: ' . mysql_error()); mysql_select_db($dbname1) or die('Could not select database'); $dbuser = "query from this database"; $dbpass = "query from this database"; $dbhost = "localhost"; $dbname = "query from this database"; // Connecting, selecting database $con = mysql_connect($dbhost, $dbuser, $dbpass) or die('Could not connect: ' . mysql_error()); mysql_select_db($dbname) or die('Could not select database'); //query from database $query = mysql_query("SELECT * FROM `second_content` WHERE CHANGED =0 limit 0,1"); while($row=mysql_fetch_array($query)){ $result=$row[0]; $text=$row[1]."</br>Size:(".$row[4].")"; $alias=$row[2]; $link = '<a target="_blank" href='.$row[3].'>Download</a>'; echo $result; } //insert into database mysql_query("SET NAMES 'utf8'", $con1); $query3= " INSERT INTO `jos_content` (`id`, `title`, `alias`, `) VALUES (NULL, '".$result."', '".$alias."', '')"; if (!mysql_query($query3,$con1)) { die('Error: text add' . mysql_error()); } mysql_close($con); mysql_close($con1); ?> Hi, I'm quite new to php and not the greatest of coders, so urgently require your help. I want to be able to take data from an un-normalised table and load into 2 normalised tables as below: 1) Table 1 - All Music Tracks (Un-normalised table) Album Name Artist Name Track Name Track Length etc. 2) Table 2 - Albums Table (Normalised table) ID Artist Name Album Name etc. 3) Table 3 - Tracks Table (Normalised table) ID Track Name Album ID (foreign key to Albums table) etc. Can someone please provide some sample code as a starting point? The All Music Tracks table includes both the album name and track name in each row, but I only want the album appearing once in the Albums tables, would I have to do an Distinct select first to get the album names into an array? I'm not sure how I would then have nested loop to do the insert into the Tracks table. Much Appreciated, PD 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)) ?> I've begun to play around with object oriented php and I was wondering how I would go about writing a method that inserts values into a table.
I have a class, called queries, and I made this very simple function:
class queries { public function insert($table, $field, $value){ global $dbh; $stmt = $dbh->prepare("INSERT INTO $table ($field) VALUES (:value)"); $stmt->bindParam(":value", $value); $stmt->execute(); } } $queries = new queries();
Hi guys, Thanks
if(isset($_POST['send'])){ $category = $_POST['category']; $item_type = $_POST['item_type']; $item_size = $_POST['item_size']; $product_name = $_POST['product_name']; $item_qty = $_POST['item_qty']; $price = $_POST['price']; $total_price = $_POST['total_price']; $item_price = $_POST['item_price']; $sql = " INSERT INTO shopping( trans_ref, category, product_name, item_type, item_size, item_qty, item_price, price, date ) VALUES( :trans_ref, :category, :product_name, :item_type, :item_size, :item_qty, :item_price, :price, NOW() ) "; $stmt = $pdo->prepare($sql); $stmt->execute(array( ':trans_ref' => $_SESSION['trans_ref'], ':category' => $category, ':product_name' => $product_name, ':item_type' => $item_type, ':item_size' => $item_size, ':item_qty' => $item_qty, ':item_price' => $item_price, ':price' => $price )); if ( $stmt->rowCount()){ echo '<div class="alert bg-success text-center">SHOPPING COMPLETED</div>'; }else{ echo '<div class="alert bg-danger text-center">SHOPPING NOT COMPLETED. A PROBLE OCCURED</div>'; } }
how do I make the $image piece so that it inserts "images/$image.php" into the database? VALUES('$name', '$id', '$image','$event')"; Hi... Got a slight problem with my code, it keeps telling me that there is an error in my syntax, yet I have used the same code before perfectly, and for the life of me cannot see the problem? ....any ideas? <?php if (!isset($_SESSION)) { session_start(); } // Connects to your Database mysql_connect("localhost", "justair1_mick", "guru1969") or die(mysql_error()) ; mysql_select_db("justair1_justair") or die(mysql_error()) ; $filename = ($_FILES['image']['name']); $group = $_POST['group']; $make_model = $_POST['make_model']; $seats = $_POST['seats']; $transmission = $_POST['transmission']; $doors = $_POST['doors']; $lg_bags = $_POST['lg_bags']; $sm_bags = $_POST['sm_bags']; $aircon = $_POST['aircon']; $day1 = $_POST['1_day']; $days2 = $_POST['2_days']; $days3_6 = $_POST['3_6days']; $week = $_POST['week']; $days8_13 = $_POST['8_13days']; $days14 = $_POST['14_days']; if(isset($filename)){ //This is the directory where images will be saved $target = "images/"; $target2 = $target . basename( $_FILES['image']['name']); //This gets all the other information from the form $fileA=($_FILES['image']['name']); } $updateSQL = "INSERT INTO car_groups (group, make_model, transmission, seats, doors, lg_bags, sm_bags, aircon, image) VALUES ('$group', '$make_model', '$transmission', '$seats', '$doors', '$lg_bags', '$sm_bags', '$aircon', '$filename')"; mysql_query($updateSQL) or die(mysql_error()); //Writes the photo to the server move_uploaded_file($_FILES['image']['tmp_name'], $target2); header ("Location: carhireInsert.php"); ?> It keeps telling me... "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'group, make_model, transmission, seats, doors, lg_bags, sm_bags, aircon, image) ' at line 1" ..? Really stuck on this one... Any help would be apreciated.. thanks.. Mick. i have this code... and i want to make it more dynamic.... Code: [Select] <?php $content = $content[1].$content[2].$content[3].$content[4].$content[5].$content[6].$content[7].$content[8].$content[9].$content[10].$content[11].$content[12] .$content[13].$content[14].$content[15].$content[16] .$content[17].$content[18].$content[19].$content[20].$content[21].$content[22].$content[23].$content[24]; $sql = mysql_query ("insert into database (content) values ('$content')") or die(mysql_error()); ?> for example... instead content[1]. content[2]. content[3] ...etc... i want something like this....... $content = $content[from 1 to 24]; or $content = $content[from 1 to 777]; any solutions? Everything on this page works the form loads and i can insert info into the form but when i click submit it just reloads the page(action="this page") and nothing happens. thanks in advance -Adam Code: [Select] <?php require("connection/connection.php"); include("connection/functions.php"); ?> <HTML> <head> <meta content="yes" name="apple-mobile-web-app-capable" /> <meta content="index,follow" name="robots" /> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <link href="" rel="apple-touch-icon" /> <meta content="minimum-scale=1.0, width=device-width, maximum-scale=0.6667, user-scalable=no" name="viewport" /> <meta name="format-detection" content="telephone=no"/> <link href="css/style.css" rel="stylesheet" media="screen" type="text/css" /> <script src="javascript/functions.js" type="text/javascript"></script> <title>.: Bookmarks :.</title> <link href="" rel="apple-touch-startup-image" /> <meta content="apple-mobile-web-app-status-bar-style" content="default" /> </head> <body class="musiclist"> <div id="topbar"> <div id="title">.: Bookmarks :.</div> <div id="leftbutton"> <a href="default.html"><img src="images/home.png"></a> </div> <div id="rightbutton"> <a href="">Programs</a> </div> </div> <div id="tributton"> <div class="links"> <a id="pressed" href="Bookmarks/Bookmarks.php">Bookmarks</a><a href="Music/Music.html">Music</a><a href="">Movies</a> </div> </div> <div id="content" style="top: 36px"> <form method="post" action="AddBookmark.php"> <span class="graytitle">Add Bookmark</span> <ul class="pageitem"> <li class="bigfield"><input type="text" name="BookmarkName" placeholder="Bookmark Name" /></li> <li class="bigfield"><input type="text" name="BookmarkLink" placeholder="Bookmark Link" /></li> <li class="select"><select name="d"> <?php $getbookmarksections = mysql_query("SELECT * FROM bookmarksections"); confirm_query($getbookmarksections); while($getbm = mysql_fetch_array($getbookmarksections)){ $id = $getbm["ID"]; $sn = $getbm["SectionName"]; echo "<option value=\"$id\">$sn</option>"; } ?> </select><span class="arrow"></span></li> <li class="button"> <input name="AddBookmark" type="submit" value="Add Bookmark" /> </li> </ul> </form> <?php if(isset($_POST["AddBookmark"])){ $SectionID = $id; $Bookmark = $_POST["BookmarkName"]; $BookmarkLink = $_POST["BookmarkLink"]; $add = "INSERT INTO `bookmarks` (`ID` ,`SectionID` ,`Bookmark` ,`BookmarkLink`) VALUES ('NULL', '$SectionID', '$Bookmark', '$BookmarkLink')"; if(confirm_query($add)){ echo "<span class=\"graytitle\">Bookmark '$BookmarkName' in '$sn' Added.</span>"; } } ?> </div> <div id="footer"> </div> </body> </HTML> <?php //Close Connection if(isset($connection)){ mysql_close($connection); } ?> this is the code i suspect is not working Code: [Select] <?php if(isset($_POST["AddBookmark"])){ $SectionID = $id; $Bookmark = $_POST["BookmarkName"]; $BookmarkLink = $_POST["BookmarkLink"]; $add = "INSERT INTO `bookmarks` (`ID` ,`SectionID` ,`Bookmark` ,`BookmarkLink`) VALUES ('NULL', '$SectionID', '$Bookmark', '$BookmarkLink')"; if(confirm_query($add)){ echo "<span class=\"graytitle\">Bookmark '$BookmarkName' in '$sn' Added.</span>"; } } ?> Hi I have started my error checking for my form. I am understand that the date must be inserted in the format yyyy/mm/dd but on my form i need it to be inserted in the format dd/mm/yyyy. I have wrote some code but have only been doing php about a week properly so I can't see what my error is. Whenever I try to insert the date, the form its self does not error but if i check the database the date is simply 0000/00/00. Can anyone help? if(isset($_POST['submit'])) { $first_name = mysql_real_escape_string($_POST['first_name']); $last_name = mysql_real_escape_string($_POST['last_name']); $DOB = mysql_real_escape_string($_POST['DOB']); $sex = mysql_real_escape_string($_POST['sex']); $email = mysql_real_escape_string($_POST['email']); $username = mysql_real_escape_string($_POST['username']); $password = mysql_real_escape_string($_POST['password']); $agree = mysql_real_escape_string($_POST['agreed']); $creation_date = mysql_real_escape_string($_POST['creation_date']); $user_type = mysql_real_escape_string($_POST['member_type']); $access_level = mysql_real_escape_string($_POST['access_level']); $validation = mysql_real_escape_string($_POST['validation_id']); $club_user = mysql_real_escape_string($_POST['user_type']); $date_check = "/^([0-9]{2})/([0-9]{2})/([0-9]{4})$/"; if($first_name == "") { $message = "Please enter a first name"; $success = 0; } else if($last_name == "") { $message = "Please enter a surname"; $success = 0; } else if($DOB =="") { $message = "Please enter your date of birth."; $success = 0; } else if(!(preg_match("/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/", $DOB))) { $message = "Please enter your birthday in the format dd/mm/yyyy"; $success = 0; } else if($email =="") { $message = "Please enter a correct email."; $success = 0; } else if($username =="") { $message = "Please enter a username."; $success = 0; } else if($password =="") { $message = "Please enter a password greater than 6 characters long."; $success = 0; } else { $DOB = $explode[2]."-".$explode[1]."-".$explode[0]; $password_md5 = md5($password); $insert_member= "INSERT INTO Members (`first_name`,`last_name`,`DOB`,`sex`,`email`,`username`,`password`,`agree`,`creation_date`,`usertype`,`access_level`,`validationID`) VALUES ('".$first_name."','".$last_name."','".$DOB."','".$sex."','".$email."','".$username."','".$password_md5."','".$agree."','".$creation_date."','".$user_type."','".$access_level."', '".$validation."')"; $insert_member_now= mysql_query($insert_member) or die(mysql_error()); $url = "thankyou.php?name=".$_POST['username']; header('Location: '.$url); Hi all, I've made a page the variables are being recieved and echo'd ok, however they are not being inserted into the database. below is the file with the insert statement. any help really appreciated. MsKazza Code: [Select] <?php // Database connect $con = mysql_connect("mysql1.myhost.ie","admin_book","root123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("book_test", $con); $orderid=$_GET['orderid']; //Parse Values from Coupon.php Form $orderid = mysql_real_escape_string(trim($_POST['orderid'])); $design = mysql_real_escape_string(trim($_POST['design'])); $childname = mysql_real_escape_string(trim($_POST['childname'])); $address = mysql_real_escape_string(trim($_POST['address'])); echo $orderid; echo $design; echo $childname; echo $address; $sql="INSERT INTO details (orderid, design, childname, address) VALUES ('$orderid','$design','$childname','$address')"; ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Digital Scribe Books</title> <link href="style.css" rel="stylesheet" type="text/css" /> <script type="text/javascript"> function MM_preloadImages() { //v3.0 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array(); var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++) if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}} } function MM_swapImgRestore() { //v3.0 var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc; } function MM_findObj(n, d) { //v4.01 var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) { d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);} if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n]; for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); if(!x && d.getElementById) x=d.getElementById(n); return x; } function MM_swapImage() { //v3.0 var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3) if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];} } </script> </head> <body onload="MM_preloadImages('images/buttons/home_over.png','images/buttons/books_over.png','images/buttons/cards_over.png','images/buttons/letters_over.png')"> <div id="snow"> <div id="wrapper"> <div id="header"> <div id="logo"><img src="images/digital_scripe.png" width="218" height="91" /></div> <div id="menu"><a href="index.php" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('Home','','images/buttons/home_over.png',1)"><img src="images/buttons/home_act.png" name="Home" width="131" height="132" border="0" id="Home" /></a><a href="books.php" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('Books','','images/buttons/books_over.png',1)"><img src="images/buttons/books_act.png" name="Books" width="131" height="132" border="0" id="Books" /></a><a href="cards.php" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('Cards','','images/buttons/cards_over.png',1)"><img src="images/buttons/cards_act.png" name="Cards" width="131" height="132" border="0" id="Cards" /></a><a href="letters.php" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage('Letters','','images/buttons/letters_over.png',1)"><img src="images/buttons/letters_act.png" name="Letters" width="131" height="132" border="0" id="Letters" /></a></div> </div> <div id="content"> <div id="info_bar"><br /><br /><br /> <p>Your personal order number is:</p><br /> <br /> <p>Please fill out the details of where you would like your order to be shipped to.</p> </div> <form action="card_paynow.php" method="POST" name="custdetails" id="custdetails"> <table width="60%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="19%">orderid</td> <td width="81%"><input name="orderid" type="hidden" value="<? echo $orderid; ?>"></td> </tr> <tr> <td>name</td> <td><input name="name" type="text" id="name"></td> </tr> <tr> <td>surname</td> <td><input name="surname" type="text" id="surname"></td> </tr> <tr> <td>address 1 </td> <td><input name="add1" type="text" id="add1"></td> </tr> <tr> <td>address 2 </td> <td><input name="add2" type="text" id="add2"></td> </tr> <tr> <td>town</td> <td><input name="town" type="text" id="town"></td> </tr> <tr> <td>county</td> <td><input name="county" type="text" id="county"></td> </tr> <tr> <td>postcode</td> <td><input name="postcode" type="text" id="postcode"></td> </tr> <tr> <td>number</td> <td><input name="phone" type="text" id="phone"></td> </tr> <tr> <td>email</td> <td><input name="email" type="text" id="email"></td> </tr> <tr> <td> </td> <td> </td> </tr> <tr> <td> </td> <td><input type="submit" name="Submit" value="Continue..."></td> </tr> <tr> <td> </td> <td> </td> </tr> </table> </form> </div> <div id="footer" class="clear"><div id="sign"><div id="sign_text">Personalised<br /> Books</div> </div></div> </div></div> </body> </html> Hello, ive got the right output from the code below, only my mysql query doesnt seem to be working as it should. Im not too great with mysql so please any help or suggestions would be great. I have tried the code but when I check my database nothing has been inserted. !?! Code: [Select] <?php include('db.php'); include('func.php'); ?><html><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Chained Select Boxes using PHP, MySQL and jQuery</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#wait_1').hide(); $('#drop_1').change(function(){ $('#wait_1').show(); $('#result_1').hide(); $.get("func.php", { func: "drop_1", drop_var: $('#drop_1').val() }, function(response){ $('#result_1').fadeOut(); setTimeout("finishAjax('result_1', '"+escape(response)+"')", 400); }); return false; }); }); function finishAjax(id, response) { $('#wait_1').hide(); $('#'+id).html(unescape(response)); $('#'+id).fadeIn(); } </script> </head> <body> <p> <form action="" method="post"> Name: <input type="text" name="Name" /><br /> Phone: <input type="text" name="Phone" /><br /> Email: <input type="text" name="Email" /><br /> Postcode: <input type="text" name="Postcode" /><br /> Web Address: <input type="text" name="Website" /><br /><br /> <select name="drop_1" id="drop_1"> <option value="" selected="selected" disabled="disabled">Select a Category</option> <?php getTierOne(); ?> </select> <span id="wait_1" style="display: none;"> <img alt="Please Wait" src="ajax-loader.gif"/> </span> <span id="result_1" style="display: none;"></span> <br /> </form> </p> <p> <?php if(isset($_POST['submit'])){ $drop = $_POST['drop_1']; $tier_two = $_POST['Subtype']; echo "You selected "; echo $drop." & ".$tier_two; } $Name = $_POST["Name"]; $Phone = $_POST["Phone"]; $Email = $_POST["Email"]; $Postcode = $_POST["Postcode"]; $Website = $_POST["Website"]; echo "<br>"; echo $Name; echo "<br>"; echo $Website; mysql_query ("INSERT INTO business (Name, Type, Subtype, Phone, Email, Postcode, Web Address) VALUES ('$Name', '$drop', '$tier_two' , '$Phone', '$Email', '$Postcode', '$Website')"); ?> Im not sure it makes a difference but, I am adding data into each column of my database with the exception of the 1st column named 'ID' which is set to auto_increment. I created this database Code: [Select] <?php $mysqli = mysqli_connect('localhost', 'admin', 'jce123', 'php_class'); if(mysqli_connect_errno()) { printf("connection failed: %s\n", mysqli_connect_error()); exit(); }else{ $q = mysqli_query($mysqli, "DROP TABLE IF EXISTS airline_survey"); if($q){echo "deleted the table airline_survey....<br>";} else{echo "damm... ".mysqli_error($mysqli);} $sql = "CREATE TABLE airline_survey ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, staff CHAR(10) NOT NULL, luggage CHAR(10) NOT NULL, seating CHAR(10) NOT NULL, clean CHAR(10) NOT NULL, noise CHAR(10) NOT NULL )"; $res = mysqli_query($mysqli, $sql); if($res === TRUE) { echo "table created"; } else { printf("Could not create table: %s\n", mysqli_error($mysqli)); } mysqli_close($mysqli); } ?> When I look at it it looks fine. I have a form that sends data to this script: Code: [Select] <?php $con = mysql_connect('localhost', 'admin', 'abc123'); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("php_class", $con); foreach ($_POST as $key => $value) { $staff = ""; $luggage = ""; $seating = ""; $clean = ""; $noise = ""; switch($key){ case "staff": $staff = $value; break; case "luggage": $luggage = $value; break; case "seating": $seating = $value; break; case "clean": $clean = $value; break; case "noise": $noise = $value; break; default: echo "we must be in the twilight zone"; } echo $staff."<br>"; [color=red] mysql_query("INSERT INTO airline_survey (staff, luggage, seating, clean, noise) VALUES ($staff, $luggage, $seating, $clean, $noise)");[/color] } ?> as you can see right before the insert query I test one of the variables to see if it has the string I'm expecting and it does. The problem is the script runs without giving me an error message but the data never gets inserted into the table. Hi 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. hi, i was having difficulty and i'm quite confused how to insert these values to the database before it will become as it is, based on this article: http://roshanbh.com.np/2008/01/populate-triple-drop-down-list-change-options-value-from-database-using-ajax-and-php.html what i did was putting/saving the values directly in the database (mysql). but now i want those values to be coming from the user's input:the country,state and city so the system will just get those values, store it to the database with the fields of each table having the same content like that from article above..i really need some help here.. This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=350408.0 I am having an issue trying to get products that I am entering through my admin panel to go into my database. I am thinking that the programmer of the script might have forgot some code possibly, but everything else does get inserted into the database regarding categories, manufactures etc. Here is the insert product php script. My db and functions are set to go to my database with website name/password etc.
<?php if(!isset($_SESSION['customer_email'])){ echo "<script> window.open('../checkout.php','_self'); </script>"; } $customer_email = $_SESSION['customer_email']; $get_customer = "select * from customers where customer_email='$customer_email'"; $run_customer = mysqli_query($con,$get_customer); $row_customer = mysqli_fetch_array($run_customer); $customer_id = $row_customer['customer_id']; $select_general_settings = "select * from general_settings"; $run_general_settings = mysqli_query($con,$select_general_settings); $row_general_settings = mysqli_fetch_array($run_general_settings); $product_vendor_status = $row_general_settings["new_product_status"]; ?> <script src="//cdn.tinymce.com/4/tinymce.min.js"></script> <script>tinymce.init({ selector:'#product_desc,#product_features' });</script> <div class="row"><!-- 2 row Starts --> <div class="col-lg-12"><!-- col-lg-12 Starts --> <div class="panel panel-default"><!-- panel panel-default Starts --> <div class="panel-heading"><!-- panel-heading Starts --> <h3 class="panel-title"> <i class="fa fa-money fa-fw"></i> Insert Product </h3> </div><!-- panel-heading Ends --> <div class="panel-body"><!-- panel-body Starts --> <form id="insert_product_form" method="post" enctype="multipart/form-data"><!-- form-horizontal Starts --> <div class="row"><!-- 2 row Starts --> <div class="col-md-9"><!-- col-md-9 Starts --> <div class="form-group" ><!-- form-group Starts --> <label> Product Title </label> <input type="text" name="product_title" class="form-control" required > </div><!-- form-group Ends --> <div class="form-group" ><!-- form-group Starts --> <label> Product Seo Description </label> <textarea name="product_seo_desc" class="form-control" maxlength="230" placeholder="Most search engines use a maximum of 230 chars for the description."></textarea> </div><!-- form-group Ends --> <div class="form-group" ><!-- form-group Starts --> <label> Product Url </label> <input type="text" name="product_url" class="form-control" required > <br> <p style="font-size:15px; font-weight:bold;"> Product Url Example : navy-blue-t-shirt </p> </div><!-- form-group Ends --> <div class="form-group"><!-- form-group Starts --> <label> Product Tabs </label> <ul class="nav nav-tabs"><!-- nav nav-tabs Starts --> <li class="active"> <a data-toggle="tab" href="#description"> Product Description </a> </li> <li> <a data-toggle="tab" href="#features"> Product Features </a> </li> <li> <a data-toggle="tab" href="#video"> Sounds And Videos </a> </li> </ul><!-- nav nav-tabs Ends --> <div class="tab-content"><!-- tab-content Starts --> <div id="description" class="tab-pane fade in active"><!-- description tab-pane fade in active Starts --> <br> <textarea name="product_desc" class="form-control" rows="15" id="product_desc"></textarea> </div><!-- description tab-pane fade in active Ends --> <div id="features" class="tab-pane fade in"><!-- features tab-pane fade in Starts --> <br> <textarea name="product_features" class="form-control" rows="15" id="product_features"></textarea> </div><!-- features tab-pane fade in Ends --> <div id="video" class="tab-pane fade in"><!-- video tab-pane fade in Starts --> <br> <textarea name="product_video" class="form-control" rows="15"></textarea> </div><!-- video tab-pane fade in Ends --> </div><!-- tab-content Ends --> </div><!-- form-group Ends --> <div class="form-group" id="product_weight"><!-- form-group Starts --> <label> Product Weight <small> (kg)</small> </label> <input type="text" name="product_weight" class="form-control"> </div><!-- form-group Ends --> <div class="form-group" id="product_price"><!-- form-group Starts --> <label> Product Price </label> <input type="text" name="product_price" class="form-control" required> </div><!-- form-group Ends --> <div class="form-group" id="product_psp_price"><!-- form-group Starts --> <label> Product Sale Price </label> <input type="text" name="psp_price" class="form-control"> </div><!-- form-group Ends --> </div><!-- col-md-9 Ends --> <div class="col-md-3"><!-- col-md-3 Starts --> <div class="form-group"><!-- form-group Starts --> <label> Select A Product Type </label> <select class="form-control" name="product_type"><!-- select manufacturer Starts --> <option value="physical_product"> (Physical Product) Simple Product </option> <option value="digital_product"> (Digital Product) Downloadable Product </option> <option value="variable_product"> (Variable Product) Advanced Product </option> </select><!-- select manufacturer Ends --> </div><!-- form-group Ends --> <div class="form-group"><!-- form-group Starts --> <label> Select A Manufacturer </label> <select class="form-control" name="manufacturer"><!-- select manufacturer Starts --> <option> Select A Manufacturer </option> <?php $get_manufacturer = "select * from manufacturers"; $run_manufacturer = mysqli_query($con,$get_manufacturer); while($row_manufacturer= mysqli_fetch_array($run_manufacturer)){ $manufacturer_id = $row_manufacturer['manufacturer_id']; $manufacturer_title = $row_manufacturer['manufacturer_title']; echo "<option value='$manufacturer_id'> $manufacturer_title </option>"; } ?> </select><!-- select manufacturer Ends --> </div><!-- form-group Ends --> <div class="form-group"><!-- form-group Starts --> <label> Product Category </label> <select name="product_cat" class="form-control" > <option> Select a Product Category </option> <?php $get_p_cats = "select * from product_categories"; $run_p_cats = mysqli_query($con,$get_p_cats); while ($row_p_cats=mysqli_fetch_array($run_p_cats)) { $p_cat_id = $row_p_cats['p_cat_id']; $p_cat_title = $row_p_cats['p_cat_title']; echo "<option value='$p_cat_id' >$p_cat_title</option>"; } ?> </select> </div><!-- form-group Ends --> <div class="form-group" ><!-- form-group Starts --> <label> Category </label> <select name="cat" class="form-control" > <option> Select a Category </option> <?php $get_cat = "select * from categories"; $run_cat = mysqli_query($con,$get_cat); while ($row_cat=mysqli_fetch_array($run_cat)) { $cat_id = $row_cat['cat_id']; $cat_title = $row_cat['cat_title']; echo "<option value='$cat_id'>$cat_title</option>"; } ?> </select> </div><!-- form-group Ends --> <div class="form-group" ><!-- form-group Starts --> <label> Product Image 1 </label> <input type="file" name="product_img1" class="form-control" required > </div><!-- form-group Ends --> <div class="form-group" ><!-- form-group Starts --> <label> Product Image 2 </label> <input type="file" name="product_img2" class="form-control"> </div><!-- form-group Ends --> <div class="form-group" ><!-- form-group Starts --> <label> Product Image 3 </label> <input type="file" name="product_img3" class="form-control"> </div><!-- form-group Ends --> <div class="form-group" ><!-- form-group Starts --> <label> Product Keywords </label> <input type="text" name="product_keywords" class="form-control"> </div><!-- form-group Ends --> <div class="form-group" ><!-- form-group Starts --> <label> Product Label </label> <input type="text" name="product_label" class="form-control"> </div><!-- form-group Ends --> </div><!-- col-md-3 Ends --> </div><!-- 2 row Ends --> <div class="form-group" id="product-stock-management"><!-- form-group Starts --> <label> Product Inventory Stock Management </label> <div class="panel panel-default"><!-- panel panel-default Starts --> <div class="panel-heading"><!-- panel-heading Starts --> <strong> Inventory - Stock Options </strong> </div><!-- panel-heading Ends --> <div class="panel-body"><!--panel-body Starts --> <div class="row"><!-- row Starts --> <div class="col-sm-6" id="stock-status"><!-- col-sm-6 Starts --> <div class="form-group"><!-- form-group Starts --> <label> Stock Status </label> <select class="form-control" name="stock_status" required><!-- select manufacturer Starts --> <option value="instock">In stock</option> <option value="outofstock">Out of stock</option> <option value="onbackorder">On backorder</option> </select><!-- select manufacturer Ends --> </div><!-- form-group Ends --> </div><!-- col-sm-6 Ends --> <div class="col-sm-6"><!-- col-sm-6 Starts --> <div class="form-group"><!-- form-group Starts --> <label> Enable stock management at product level? </label> <div class="radio"> <label> <input type="radio" name="enable_stock" value="yes" required> Yes </label> <label> <input type="radio" name="enable_stock" value="no" checked required> No </label> </div> </div><!-- form-group Ends --> </div><!-- col-sm-6 Ends --> </div><!-- row Ends --> <div class="row" id="stock-management-row"><!-- row Starts --> <div class="col-sm-6"><!-- col-sm-6 Starts --> <div class="form-group"><!-- form-group Starts --> <label> Stock Quantity </label> <input type="number" name="stock_quantity" value="0" class="form-control" required> </div><!-- form-group Ends --> </div><!-- col-sm-6 Ends --> <div class="col-sm-6"><!-- col-sm-6 Starts --> <div class="form-group"><!-- form-group Starts --> <label> Allow backorders? </label> <select class="form-control" name="allow_backorders" required><!-- select manufacturer Starts --> <option value="no">Do not allow</option> <option value="notify">Allow, but notify customer</option> <option value="yes">Allow</option> </select><!-- select manufacturer Ends --> </div><!-- form-group Ends --> </div><!-- col-sm-6 Ends --> </div><!-- row Ends --> </div><!--panel-body Ends --> </div><!-- panel panel-default Ends --> </div><!-- form-group Ends --> </form><!-- form-horizontal Ends --> <div class="form-group" id="variable_product_options"><!-- form-group Starts --> <label> Variable Product Options </label> <div class="panel panel-default"><!-- panel panel-default Starts --> <div class="panel-heading"><!-- panel-heading Starts --> <ul class="nav nav-tabs"><!-- nav nav-tabs Starts --> <li class="active"> <a data-toggle="tab" href="#product_attributes"> Product Attributes </a> </li> <li> <a data-toggle="tab" href="#product_variations"> Product Variations </a> </li> </ul><!-- nav nav-tabs Ends --> </div><!-- panel-heading Ends --> <div class="panel-body"><!--panel-body Starts --> <div class="tab-content"><!-- tab-content Starts --> <div id="product_attributes" class="tab-pane fade in active"><!-- product_attributes tab-pane fade in active Starts --> <form id="insert_attribute_form" method="post"><!-- form Starts --> <div class="row"><!-- row Starts --> <div class="col-sm-4"><!-- col-sm-4 Starts --> <div class="form-group"><!-- form-group Starts --> <label> Name: </label> <input type="text" name="attribute_name" class="form-control" required> </div><!-- form-group Ends --> </div><!-- col-sm-4 Ends --> <div class="col-sm-8"><!-- col-sm-8 Starts --> <div class="form-group"><!-- form-group Starts --> <label> Value(s): </label> <textarea name="attribute_values" class="form-control" placeholder="Enter some attributes by '|' separating values." required></textarea> </div><!-- form-group Ends --> </div><!-- col-sm-8 Ends --> </div><!-- row Ends --> <div class="form-group"><!-- form-group Starts --> <input type="submit" value="Insert Product Attribute" class="btn btn btn-primary"> </div><!-- form-group Ends --> </form><!-- form Ends --> <table class="table table-hover table-bordered table-striped"><!-- table table-hover table-bordered table-striped Starts --> <thead><!-- thead Starts --> <tr> <th>Attribute Name:</th> <th>Attribute Value(s):</th> <th>Actions:</th> </tr> </thead><!-- thead Ends --> <tbody><!-- tbody Starts --> <?php $random_id = 152; $select_product_attributes = "select * from product_attributes where product_id='$random_id'"; $run_product_attributes = mysqli_query($con,$select_product_attributes); while($row_product_attributes = mysqli_fetch_array($run_product_attributes)){ $attribute_id = $row_product_attributes["attribute_id"]; $attribute_name = $row_product_attributes["attribute_name"]; $attribute_values = $row_product_attributes["attribute_values"]; ?> <tr id="tr-attribute-<?php echo $attribute_id; ?>"> <td> <div class="edit" data-attribute="<?php echo $attribute_id; ?>"><?php echo $attribute_name; ?></div> <input type="text" id="attribute-name" class="input-edit form-control" data-attribute="<?php echo $attribute_id; ?>" value="<?php echo $attribute_name; ?>"> </td> <td> <div class="edit" data-attribute="<?php echo $attribute_id; ?>"><?php echo $attribute_values; ?></div> <input type="text" id="attribute-values" class="input-edit form-control" data-attribute="<?php echo $attribute_id; ?>" value="<?php echo $attribute_values; ?>"> </td> <td> <div class="btn-group"> <a href="#" class="edit-product-attribute btn btn-primary btn-sm" data-attribute="<?php echo $attribute_id; ?>"> <i class="fa fa-pencil"></i> Edit </a> <a href="#" class="save-product-attribute btn btn-success btn-sm" data-attribute="<?php echo $attribute_id; ?>"> <i class="fa fa-floppy-o"></i> Save </a> <a href="#" class="delete-product-attribute btn btn-danger btn-sm" data-attribute="<?php echo $attribute_id; ?>"> <i class="fa fa-trash-o"></i> Delete </a> </div> </td> </tr> <?php } ?> </tbody><!-- tbody Ends --> </table><!-- table table-hover table-bordered table-striped Ends --> </div><!-- product_attributes tab-pane fade in active Ends --> <div id="product_variations" class="tab-pane fade in"><!-- product_variations tab-pane fade in Starts --> <form id="product-variations-form" method="post" enctype="multipart/form-data"><!-- form Starts --> <div class="form-group row"><!-- form-group Starts --> <label class="col-sm-3 control-label"> Default Form Values: </label> <div class="col-sm-9"><!-- col-sm-10 Starts --> <div class="row" id="default_form_values"><!-- row default_form_values Starts --> </div><!-- row default_form_values Ends --> <span class="help-block"> These are the product attributes that will be pre-selected on the frontend. </span> </div><!-- col-sm-9 Ends --> </div><!-- form-group Ends --> <hr class="variation-hr"> <div class="form-group row"><!-- form-group Starts --> <label class="col-sm-1 control-label"> Actions: </label> <div class="col-sm-10"><!-- col-sm-10 Starts --> <select class="form-control" id="action_select"><!-- select manufacturer Starts --> <option value="add_variation"> Add A New Variation </option> <option value="create_variations_from_attributes"> Create New Variations From All Attributes </option> <option value="delete_all_variations"> Delete All Variations </option> </select><!-- select manufacturer Ends --> </div><!-- col-sm-10 Ends --> <div class="col-sm-1"><!-- col-sm-1 Starts --> <button type="button" id="go_button" class="btn btn-success form-control"> Go </button> </div><!-- col-sm-1 Ends --> </div><!-- form-group Ends --> <div class="product-variations-div"><!-- product-variations-div Starts --> </div><!-- product-variations-div Ends --> <hr class="variation-hr"> <div class="form-group"><!-- form-group Starts --> <input type="submit" value="Save Product Variations" class="btn btn btn-success"> </div><!-- form-group Ends --> </form><!-- form Ends --> <div class="ajax-response-div"></div> </div><!-- product_variations tab-pane fade in Ends --> </div><!-- tab-content Ends --> </div><!--panel-body Ends --> </div><!-- panel panel-default Ends --> </div><!-- form-group Ends --> <div class="form-group"><!-- form-group Starts --> <input type="submit" name="submit" value="Insert Product" form="insert_product_form" class="btn btn-primary form-control"> </div><!-- form-group Ends --> </div><!-- panel-body Ends --> </div><!-- panel panel-default Ends --> </div><!-- col-lg-12 Ends --> </div><!-- 2 row Ends --> <script> $(document).ready(function(){ //Product Stock Management Code Starts $("#stock-management-row").hide(); $("input[name='enable_stock']").click(function(){ var radio_value = $(this).val(); if(radio_value == "yes"){ $("#stock-status").hide(); $("#stock-management-row").show(); }else if(radio_value == "no"){ $("#stock-status").show(); $("#stock-management-row").hide(); } }); //Product Stock Management Code Ends //Change Product Type Function Code Starts function change_product_type(){ var product_type = $("select[name='product_type']").val(); if(product_type == "physical_product"){ $("#product_weight").show(); $("#product_price").show(); $("#product_psp_price").show(); $('#product_weight input,#product_price input,#product_psp_price input').prop("disabled", false); $("#product-stock-management").show(); $('#product-stock-management input,#product-stock-management select').prop("disabled", false); $("#variable_product_options").hide(); }else if(product_type == "digital_product"){ $("#product_weight").hide(); $("#product_price").show(); $("#product_psp_price").show(); $('#product_weight input,#product_price input,#product_psp_price input').prop("disabled", false); $("#product-stock-management").show(); $('#product-stock-management input,#product-stock-management select').prop("disabled", false); $("#variable_product_options").hide(); }else if(product_type == "variable_product"){ $("#product_weight").hide(); $("#product_price").hide(); $("#product_psp_price").hide(); $('#product_weight input,#product_price input,#product_psp_price input').prop("disabled", true); $("#product-stock-management").hide(); $('#product-stock-management input,#product-stock-management select').prop("disabled", true); $("#variable_product_options").show(); } } //Change Product Type Function Code Ends change_product_type(); $("select[name='product_type']").change(function(){ change_product_type(); }); //Load Product Attributes Function Code Starts function load_product_attributes(){ $.ajax({ method: "POST", url: "variable_product/load_product_attributes.php", data: { random_id: <?php echo $random_id; ?> }, success:function(data){ $("table tbody").html(data); $("table").removeClass("wait-loader"); } }); } //Load Product Attributes Function Code Ends //Insert New Product Attribute Code Starts $("#insert_attribute_form").submit(function(event){ event.preventDefault(); $("table").addClass("wait-loader"); $.ajax({ method: "POST", url: "variable_product/insert_product_attribute.php", data: $('#insert_attribute_form').serialize() + "&random_id=<?php echo $random_id; ?>", success: function(){ $("#insert_attribute_form").find("input[type=text],textarea").val(""); load_product_attributes(); } }); }); //Insert New Product Attribute Code Ends //Edit Product Attribute Code Starts $(".input-edit").hide(); $(".save-product-attribute").hide(); $(".edit-product-attribute").on('click', function(event){ event.preventDefault(); var attribute_id = $(this).data("attribute"); $(".edit").show(); $(".input-edit").hide(); $(".edit[data-attribute='" + attribute_id +"']").hide(); $(".input-edit[data-attribute='" + attribute_id +"']").show().focus(); $(".edit-product-attribute[data-attribute='" + attribute_id +"']").hide(); $(".save-product-attribute[data-attribute='" + attribute_id +"']").show(); }); //Edit Product Attribute Code Ends //Update Save Product Attribute Code Starts $(".save-product-attribute").on('click', function(event){ event.preventDefault(); var attribute_id = $(this).data("attribute"); $(".edit[data-attribute='" + attribute_id +"']").show(); $(".input-edit[data-attribute='" + attribute_id +"']").hide(); $(".edit-product-attribute[data-attribute='" + attribute_id +"']").show(); $(".save-product-attribute[data-attribute='" + attribute_id +"']").hide(); var attribute_name = $("#attribute-name[data-attribute='" + attribute_id +"']").val(); var attribute_values = $("#attribute-values[data-attribute='" + attribute_id +"']").val(); $("#attribute-name[data-attribute='" + attribute_id +"']").prev(".edit").text(attribute_name); $("#attribute-values[data-attribute='" + attribute_id +"']").prev(".edit").text(attribute_values); var random_id = <?php echo $random_id; ?>; $.ajax({ method: "POST", url: "variable_product/update_product_attribute.php", data: { random_id: random_id, attribute_id: attribute_id, attribute_name: attribute_name, attribute_values: attribute_values } }); }); //Update Save Product Attribute Code Ends //Delete Product Attribute Code Starts $(".delete-product-attribute").on('click', function(event){ event.preventDefault(); var attribute_id = $(this).data("attribute"); $("#tr-attribute-" + attribute_id).remove(); var random_id = <?php echo $random_id; ?>; $.ajax({ method: "POST", url: "variable_product/delete_product_attribute.php", data: { random_id: random_id, attribute_id: attribute_id } }); }); //Delete Product Attribute Code Ends //Load Product Variations Default Form Values Function Code Starts function load_variations_default_form_values(){ $.ajax({ method: "POST", url: "variable_product/load_default_form_values.php", data: { random_id: <?php echo $random_id; ?> }, success:function(data){ $("#default_form_values").html(data); } }); } //Load Product Variations Default Form Values Function Code Ends //Load Product Variations Function Code Starts function load_product_variations(){ $.ajax({ method: "POST", url: "variable_product/load_product_variations.php", data: { random_id: <?php echo $random_id; ?> }, success:function(data){ $(".product-variations-div").html(data); $(".product-variations-div").removeClass("wait-loader"); } }); } //Load Product Variations Function Code Ends //Click Product Variations Tab Code Starts $("a[href='#product_variations']").click(function(){ $(".product-variations-div").addClass("wait-loader"); load_variations_default_form_values(); load_product_variations(); }); //Click Product Variations Tab Code Ends //Save Update Product Variations Function Code Starts function save_update_product_variations(){ var form = document.getElementById("product-variations-form"); var form_data = new FormData(form); form_data.append("random_id", <?php echo $random_id; ?>); $.ajax({ method: "POST", url: "variable_product/update_all_variations.php", data:form_data, contentType: false, cache: false, processData:false, success: function(data){ $(".ajax-response-div").html(data); $(".product-variations-div").removeClass("wait-loader"); } }); } //Save Update Product Variations Function Code Ends //Product Variations Actions Go Button Code Starts $("#go_button").click(function(){ var action_select = $("#action_select").val(); if(action_select == "add_variation"){ $(".product-variations-div").addClass("wait-loader"); save_update_product_variations(); $(".product-variations-div").addClass("wait-loader"); $.ajax({ method: "POST", url: "variable_product/insert_product_variation.php", data: { random_id: <?php echo $random_id; ?> }, success: function(){ load_product_variations(); } }); }else if(action_select == "create_variations_from_attributes"){ var confirm_action = confirm("Are you sure you want to link all variations? This will create a new variation for each and every possible combination of variation attributes (max 50 per run)."); if(confirm_action == true){ $(".product-variations-div").addClass("wait-loader"); save_update_product_variations(); $(".product-variations-div").addClass("wait-loader"); $.ajax({ method: "POST", url: "variable_product/create_variations_from_attributes.php", data: { random_id: <?php echo $random_id; ?> }, success: function(data){ $(".ajax-response-div").html(data); load_product_variations(); load_variations_default_form_values(); } }); } }else if(action_select == "delete_all_variations"){ var confirm_action = confirm("Are you sure you want to delete all variations? This cannot be undone."); if(confirm_action == true){ $(".product-variations-div").addClass("wait-loader"); $.ajax({ method: "POST", url: "variable_product/delete_all_variations.php", data: { random_id: <?php echo $random_id; ?> }, success: function(){ load_product_variations(); load_variations_default_form_values(); } }); } } }); //Product Variations Actions Go Button Code Ends //Save Update Submit From Of Product Variations Code Starts $("#product-variations-form").submit(function(event){ event.preventDefault(); $(".product-variations-div").addClass("wait-loader"); save_update_product_variations(); load_variations_default_form_values(); }); //Save Update Submit From Of Product Variations Code Ends }); </script> <?php if(isset($_POST['submit'])){ $product_title = mysqli_real_escape_string($con, $_POST['product_title']); $product_seo_desc = mysqli_real_escape_string($con, $_POST['product_seo_desc']); $product_url = mysqli_real_escape_string($con, $_POST['product_url']); $product_cat = mysqli_real_escape_string($con, $_POST['product_cat']); $cat = mysqli_real_escape_string($con, $_POST['cat']); $manufacturer_id = mysqli_real_escape_string($con, $_POST['manufacturer']); $product_price = mysqli_real_escape_string($con, $_POST['product_price']); $product_desc = mysqli_real_escape_string($con, $_POST['product_desc']); $product_keywords = mysqli_real_escape_string($con, $_POST['product_keywords']); $psp_price = mysqli_real_escape_string($con, $_POST['psp_price']); $product_label = mysqli_real_escape_string($con, $_POST['product_label']); $product_type = mysqli_real_escape_string($con, $_POST['product_type']); $product_features = mysqli_real_escape_string($con, $_POST['product_features']); $product_video = mysqli_real_escape_string($con, $_POST['product_video']); $product_weight = mysqli_real_escape_string($con, $_POST['product_weight']); $stock_status = mysqli_real_escape_string($con, $_POST['stock_status']); $enable_stock = mysqli_real_escape_string($con, $_POST['enable_stock']); $stock_quantity = mysqli_real_escape_string($con, $_POST['stock_quantity']); $allow_backorders = mysqli_real_escape_string($con, $_POST['allow_backorders']); $status = "product"; $product_img1 = $_FILES['product_img1']['name']; $product_img2 = $_FILES['product_img2']['name']; $product_img3 = $_FILES['product_img3']['name']; $temp_name1 = $_FILES['product_img1']['tmp_name']; $temp_name2 = $_FILES['product_img2']['tmp_name']; $temp_name3 = $_FILES['product_img3']['tmp_name']; $allowed = array('jpeg','jpg','gif','png'); $product_img1_extension = pathinfo($product_img1, PATHINFO_EXTENSION); $product_img2_extension = pathinfo($product_img2, PATHINFO_EXTENSION); $product_img3_extension = pathinfo($product_img3, PATHINFO_EXTENSION); if(!in_array($product_img1_extension,$allowed)){ echo "<script> alert('Your Product Image 1 File Extension Is Not Supported.'); </script>"; $product_img1 = ""; }else{ move_uploaded_file($temp_name1,"../admin_area/product_images/$product_img1"); } if(!empty($product_img2)){ if(!in_array($product_img2_extension,$allowed)){ echo "<script> alert('Your Product Image 2 File Extension Is Not Supported.'); </script>"; $product_img2 = ""; }else{ move_uploaded_file($temp_name2,"../admin_area/product_images/$product_img2"); } } if(!empty($product_img3)){ if(!in_array($product_img3_extension,$allowed)){ echo "<script> alert('Your Product Image 3 File Extension Is Not Supported.'); </script>"; $product_img3 = ""; }else{ move_uploaded_file($temp_name3,"../admin_area/product_images/$product_img3"); } } $insert_product = "insert into products (vendor_id,p_cat_id,cat_id,manufacturer_id,date,product_title,product_seo_desc,product_url,product_img1,product_img2,product_img3,product_price,product_psp_price,product_desc,product_features,product_video,product_keywords,product_label,product_type,product_weight,product_vendor_status,status) values ('$customer_id','$product_cat','$cat','$manufacturer_id',NOW(),'$product_title','$product_seo_desc','$product_url','$product_img1','$product_img2','$product_img3','$product_price','$psp_price','$product_desc','$product_features','$product_video','$product_keywords','$product_label','$product_type','$product_weight','$product_vendor_status','$status')"; $run_product = mysqli_query($con,$insert_product); $product_id = mysqli_insert_id($con); if($run_product){ if($product_type != "variable_product"){ if($enable_stock == "yes" and $stock_quantity > 0){ $stock_status = "instock"; }elseif($enable_stock == "yes" and $allow_backorders == "no" and $stock_quantity < 1){ $stock_status = "outofstock"; }elseif($enable_stock == "yes" and ($allow_backorders == "yes" or $allow_backorders == "notify") and $stock_quantity < 1){ $stock_status = "onbackorder"; } $insert_product_stock = "insert into products_stock (product_id,enable_stock,stock_status,stock_quantity,allow_backorders) values ('$product_id','$enable_stock','$stock_status','$stock_quantity','$allow_backorders')"; $run_insert_product_stock = mysqli_query($con,$insert_product_stock); } $update_product_stock = "update products_stock set product_id='$product_id' where product_id='$random_id'"; $run_update_product_stock = mysqli_query($con,$update_product_stock); $update_product_attributes = "update product_attributes set product_id='$product_id' where product_id='$random_id'"; $run_product_attributes = mysqli_query($con, $update_product_attributes); $update_product_variations = "update product_variations set product_id='$product_id' where product_id='$random_id'"; $run_product_variations = mysqli_query($con, $update_product_variations); echo " <script> alert(' Your Product Has Been Inserted Successfully. '); window.open('index.php?products','_self'); </script> "; } } ?>
|