PHP - Php Form Post And Database Insert
Ok .I tried to look for the problem for about 1 hour but I can't see what's wrong whit the following code:
In firebug the post values appear correctly like so:id=116&usern=asdawe&com=qweqw&page=116&submit=submit and the inserc() function works correctly because i tried it whit a array of data created by my; Code: [Select] <?php if(isset($_POST['submit'])) { $comment = new comment; $comment->storeform($_POST); $comment->insertc(); } ?> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST"> <input type="hidden" name="id" value="<?php echo $result['article']->id ?>"/> <ul> <li> <input type="text" name="usern" id="usern" /> </li> <li> <textarea name="com" id="com" COLS=40 ROWS=6></textarea> </li> <input type="hidden" name="page" value="<?php echo $result['article']->id ?>" /> <input type="submit" name="submit" value="submit" /> </ul> </form> Code: [Select] <?php class comment{ public $id = null; public $usern = null; public $com = null; public $page = null; public function __construct($data=array() ) { if( isset($data['id']) ) $this->id= (int)$data['id']; if( isset($data['usern']) ) $this->usern= preg_replace ( "/[^\.\,\-\_\'\"\@\?\!\:\$ a-zA-Z0-9()]/", "", $data['usern'] ); if( isset($data['com']) ) $this->com= preg_replace ( "/[^\.\,\-\_\'\"\@\?\!\:\$ a-zA-Z0-9()]/", "", $data['com'] ); if( isset($data['page']) ) $this->page= (int)$data['page']; } public function storeform ( $params ) { // Store all the parameters $this->__construct( $params ); } public function insertc() { $con = new PDO(DBN,DB_USER,DB_PASS); $sql = "INSERT INTO comments (usern,com,page) VALUES (:usern,:com,:page)"; $st =$con->prepare($sql); $st->bindValue( ":usern", $this->usern, PDO::PARAM_STR ); $st->bindValue( ":com", $this->com, PDO::PARAM_STR ); $st->bindValue( ":page", $this->page, PDO::PARAM_INT ); $st->execute(); $this->id = $con->lastInsertId(); $con = null; } } ?> Similar TutorialsHi Folks,
Firstly I am new, I have read several topics here and learned a lot, I would class myself as 'slightly better than basic', but my knowledge is mostly gained from reading code.
I am making a simple POST form for work, the data gets inserted into MySQL, nice and easy, I can make it work if I write out the statement completely, BUT I need to make a new form, it will have HUNDREDS of input fields, I really don't want to write the code, and I figured programmatically is a good way to go anyway as forms change and new forms may be required, so I set about building a function to completely handle my post data, bind it to a statement and insert it into a table, I have scrapped it a half dozen times already because something fundamentally doesn't work, but I am very close! The function can write the statement, but I need to bind the POST values before I can insert, something going wrong here and I would appreciate some help, I have a feeling it's a problem with an array, but anyway I will show you what I have, give you some comments as to my reasoning, and hopefully you can help me with the last bit
public function getColumnNames($table){ $sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = :table"; try { $stmt = $this->dbh->prepare($sql); $stmt->bindValue(':table', $table, PDO::PARAM_STR); $stmt->execute(); $output = array(); while($row = $stmt->fetch(PDO::FETCH_ASSOC)){ $output[] = $row['COLUMN_NAME']; } $all = array($output); $a1 = array_slice($output, 1); // I don't want column 1, it contains the ID, its auto incremented. $a2 = array_slice($a1, 0, -3); // I don't want the last 3 columns as they have default values $selected = array($a2); // contains all the columns except those excluded by array_slice, columns now match all of the input fields on the form foreach ($selected as $row){ $fields = "`" . implode('`, `', $row) . "`"; // I'm making `fields` here, $bind = ":" . implode(', :', $row); // And making :values here } return array ( "raw" => $all, "fields" => $fields, "bind" => $bind ); } catch(PDOException $pe) { trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR); } } public function addRecord(){ $col = array(); $col = $this->getColumnNames("table"); $raw = array($col['raw']); $fields = array($col['fields']); $bind = array($col['bind']); $columnList = implode('`, `', $fields); $paramList = implode(', ', $bind); $sql = "INSERT INTO `{$this->dbtable}` ($columnList) VALUES ($paramList)"; return $sql; // this returns something like: INSERT INTO `table` (`field1`, `field2`, `field3`) VALUES (:field1, :field2, :field3)";perfect I thought, now I just need to bind the values from $_POST... then I get stuck. Edited by luke3, 08 January 2015 - 12:10 PM. 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. Hello, I wrote a script where i can enter a stock symbol and it get saved in my database. This works, but when i enter the stock symbol i would like to also get the current stock price get saved into the database. The link for the stock price (i.e. AAPL): http://quote.yahoo.com/d/quotes.csv?s=AAPL&f=l1&e=.csv How do i programm this in the script below? Besides above, notice that "AAPL" in the link above has to be a varaible, which changes where i for example type in "GS". Form: Quote <html> <body> <form action="portfolio/insert_buy.php" method="post"> Symbol: <input type="text" name="symbol"><br /> <input type="submit" value=" Submit"> </form> </body> </html> PHP-script Quote <?php $conn = mysql_connect("xxx","xxx","xxx"); $db = mysql_select_db("xxx",$conn); $sql="INSERT INTO portfolio (symbol) VALUES ('$_POST[symbol]')"; if (!mysql_query($sql,$conn)) { die('Error: ' . mysql_error()); } echo "1 record added"; mysql_close($conn); ?> I hope someone can help me out, thanks! I almost have it but I am missing something. The form is being sent and the row is being created but there is not data. It is blank. I know it is something simple I am missing but I cannot figure it out
If anyone can look at my code below and tell me what I am missing to make the inputed info be seen, I would sure appreciate it.
<?php include_once('class/class_email.php'); // contact to database $connect = mysql_connect("localhost", "admin", "password") or die ("Error , check your server connection."); mysql_select_db("database"); $fname = $_POST['fname']; $lname = $_POST['lname']; $email = $_POST['email']; $company = $_POST['company']; $telephone = $_POST['telephone']; $comments = $_POST['comments']; $EID = $_POST['eid']; extract ($_POST); // Pick up the form data and assign it to variables // $id = intval($id); $fname = strip_tags($fname); $lname = strip_tags($lname); $email = strip_tags($email); $company = strip_tags($company); $telephone = intval($telephone); $query="INSERT INTO users(`id`, `fname`, `lname`, `email`,`company`,`telephone`) VALUES('$id','$fname','$lname','$email','$company','$telephone')"; echo $query; mysql_query($query) or die(mysql_error()); echo mysql_error(); $SQL_GetEquipment = "SELECT * FROM `new_equip` WHERE `id`='$EID' LIMIT 1;"; $result = mysqli_query($connect,$SQL_GetEquipment); $row = mysqli_fetch_assoc($result); $EmailBody = "$fname $lname has requested a quote from NAPE on Item $EID\n Information on quote request: \n Name: $fname $lname \n Email: $email \n Company: $company \n Number: $telephone \n Comments: $comments \n \n Information Requested for: {$row['itemname']}\n The URL to {$row['itemname']} is: http://www.mydomain.com.com/new-product.php?Item=$EID \n Click to send a quote now:\n http://www.mydomain.com.com/Admin/send-quote.php?id=$EID "; $e = new email(); //First value is the URL of your server, the second the port number $e->set_server( 'mail.mydomain.com.com', 26); //First value is your username, then your password $e->set_auth('noreply@mydomain.com', '112233'); //Set the "From" setting for your e-mail. The Name will be base64 encoded $e->set_sender( 'Quote Requested', 'noreply@mydomain.com' ); //for one recipient //$send_to = array('myemail@mydomain.com','myemail2@mydomain.com'); $send_to = ('myemail@gmail.com'); //you may also specify multiple recipients by creating an array like this: //$send_to = array('foo1@localhost.local', 'foo2@localhost.local', 'foo3@localhost.local'); $subject = 'Quote Request from NAPE'; $body = "$EmailBody"; if( $e->mail($send_to, $subject, $body, $headers) == true ) { //message was received by the smtp server //['last'] tends to contain the queue id so I like to save that string in the database echo 'last: '.htmlspecialchars($e->srv_ret['last']).''; }else{ //something went wrong echo 'all: '.nl2br(htmlspecialchars($e->srv_ret['all'])).''; echo 'full:'.nl2br(htmlspecialchars($e->srv_ret['full'])).''; } ?> Hey all, I'm very new to php and am having an issue writing to my database with a passed value and info taking from a form and am lost as to what to do. The $comm_id is the value I am getting from another php page that I am passing in the link from the other page. I need to insert that value, the session variable, and the $cmt value, which is taken from the user input from the form. As it stands now, when I run this, the $comm_id and $u_id insert and the $cmt is blank, BUT $cmt is echoing on the screen with the proper value. Any tips or direction would be great as i've been trying to sort this out for days now and i'm stumped. <?php $host='localhost'; $user='username'; $password='password'; $dbname='db_a'; session_start(); $id_link=mysql_connect($host,$user,$password); mysql_select_db($dbname, $id_link); $comm_id = $_GET['commId']; $u_id = $_SESSION['userId']; echo $comm_id; echo $u_id; $cmt = $_POST["comm"]; mysql_query("insert into Comments values($u_id, $comm_id,'$cmt');"); echo $cmt; ?> <FORM ACTION="test.php" METHOD="POST"> <input type="text" name="comm"> <input type="SUBMIT"> </FORM> Hello: Did my first post last week and am new to PHP. Making the jump from Classic ASP into PHP. I got some good advice last time. I have a feedback form I have been using, and it works fine for sending results to the website owner. How can I add to it so it will first add all the data to mySQL database, and then email the results to the site owner? Also, I hear about SQL injection attacks a lot - is my current code safe from that? This is what I have: contact.php Code: [Select] ... <form method="post" name="myform" action="sendmail.php"> Full Name: <input type="text" name="FullName" /> Address: <input type="text" name="Address" /> City: <input type="text" name="City" /> State: <input type="text" name="State" /> Zip: <input type="text" name="Zip" /> Phone: <input type="text" name="Phone" /> Email: <input type="text" name="Email" /> Website: <input type="text" name="Website" /> Comments: <textarea cols="43" rows="6" name="Comments"></textarea> <input type="submit" /><br /> </form> ... sendmail.php Code: [Select] <?php $FullName = $_REQUEST['FullName'] ; $Address = $_REQUEST['Address'] ; $City = $_REQUEST['City'] ; $State = $_REQUEST['State'] ; $Zip = $_REQUEST['Zip'] ; $Phone = $_REQUEST['Phone'] ; $Email = $_REQUEST['Email'] ; $Website = $_REQUEST['Website'] ; $Comments = $_REQUEST['Comments'] ; mail( "info@website.com", "Contact Request", "Full Name: $FullName\nAddress: $Address\n City: $City\n State: $State\n Zip: $Zip\n Phone: $Phone\n Email: $Email\n Website: $Website\n Comments: $Comments\n", "From: $Email" ); header( "Location: http://www.website.com/thanks.php" ); ?> Any help or coding examples would be most appreciated! Thanks! Hi everyone, I'm new to this group and new to php. I have created a multi-part form that allows the user the option to add multiple input fields to a form to upload images. Here is the form structu Code: [Select] <form action="Scripts/processreports2.php" method="post" enctype="multipart/form-data" name="report_form" target="uploader" class="reportfrm"> <fieldset> <legend>Upload your images</legend> <ol id="add_images"> <li> <input type="file" class="input" name="files[]" /> </li> <li> <input type="file" class="input" name="files[]" /> </li> <li> <input type="file" class="input" name="files[]" /> </li> </ol> <input type="button" name="addFile" id="addFile" value="Add Another Image" onclick="window.addFile(this);"/> </fieldset> <p>* indicates a required field.</p> <input name="submit" type="submit" id="submit" value="Send Info!" /> </form> Through php a maximum of three input fields are fed into an array that checks to make sure that the uploaded files are images and not some other type of file. The uploading porition of this script works. Now I am trying to get the values of the input fields as a string and insert them into the database as one record. Let's say the user has three files they want to upload. I have managed to get the files as a string ie; file1.jpg, file2.jpg, file3.jpg but what is happening is that I am getting three separate records with file1.jpg, file2.jpg, file3.jpg in them. If the user has only two files to upload then I get two separate records with file1.jpg and file2.jpg in them. (Hope that makes sense). I want one record. I have been struggling with this since Monnday and while every day I get closer, this is as close as I can get. Below is the php code. #connect to the database mysql_connect("localhost", "root", ""); mysql_select_db("masscic"); //Upload Handler to check image types function is_image($file) { $file_types = array('jpeg', 'gif', 'bmp'); //acceptable file types if ($img = getimagesize($file)){ //echo '<pre>'; //print_r($_FILES); used for testing //print_r($img); used for testing if(in_array(str_replace('image/', '', $img['mime']), $file_types)) return $img; } return false; } //form submission handling if(isset($_POST['submit'])) { //file variables $fname = $_FILES['files']['name']; $ftype = $_FILES['files']['type']; $fsize = $_FILES['files']['size']; $tname = $_FILES['files']['tmp_name']; $ferror = $_FILES['files']['error']; $newDir = '../uploads/'; //relative to where this script file resides for($i = 0; $i < count($fname); $i++) { //echo 'File name ' . $fname[$i] . ' has size ' . $fsize[$i]; used for testing if ($ferror[$i] =='UPLOAD ERR OK' || $ferror[$i] ==0) { if(is_image($tname[$i])) { //append the tmp_name($tname) to the file name ($fname) and upload to the server move_uploaded_file($tname[$i], ($newDir.time().$fname[$i])); echo '<li><span class="success">'.$fname[$i].' -- image has been accepted<br></span></li>'; }else echo '<li><span class="error">'.$fname[$i].' -- is not an accepted file type<br></span></li>'; } if (is_array($fname)) $files = implode(', ',$fname); //else $files = $fname; $sqlInsert = mysql_query("INSERT INTO files (file_names) VALUES('$files')") or die (mysql_error()); } } when i remove the action from the form it submits the post correctly if not it goes to the action url withoutposting Code: [Select] <form action="https://www.sandbox.paypal.com/cgi-bin/webscr" target="_top" method="post"> <input type="hidden" name="cmd" value="_s-xclick"> <input type="hidden" name="hosted_button_id" value="wwww"> <?php <input type="hidden" name="item_name" id="item_name" value="<?php echo $md5c;?>"> <input type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/btn_paynowCC_LG.gif" border="0" name="submit" alt="Submit Form"> <img alt="" border="0" src="https://www.sandbox.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1"> </form> <?php if(isset($_POST['submit_x']) || isset($_POST['submit_x'])) { //$Subscription_id = mysql_real_escape_string($md5c); $PropertyID = mysql_real_escape_string($rowData['ID']); $User_ID = mysql_real_escape_string($rowData['User_ID']); $item_name=mysql_real_escape_string($_POST['item_name']); //$query = 'INSERT INTO SP_subscriptions(id,) values("'.$item_name.'")'; $query = 'INSERT INTO SP_subscriptions(id,PropertyID,User_ID) values("'.$item_name.'","'.$PropertyID.'","'.$User_ID.'")'; $success = mysql_query($query); echo $query; } else echo 'POST nada'; var_dump($_POST); var_dump($query); ?> Hi - I have an HTML form which is dynamically produced using CodeIgniter / PHP and presents products a customer has ordered. When the customer has finished changing his quantities they must now submit the form. My problem is that my form will contain many of the same named fields for example, 'Product ID', or 'Product Name' or 'quantity'. So now when it gets processed a typical post array like product id could look like this: Code: [Select] Array ( [0] => 28 [1] => 24 [2] => 101 [3] => 23 [4] => 17 ) Of course I get an error: Quote Severity: Notice Message: Array to string conversion Filename: mysql/mysql_driver.php I really need some advice on how I should pre-process the various POST arrays so I can get them into my DB. A very grateful student of PHP ! Thanks Hey Guys. I am working with a form that shows the grand total on the checkout page. The value of the grand total is inside a hidden field. When click on submit, the _POST array doesn't get back the last value of the grand total. I need to hit the button twice to get the last value. The weird thing is when I echo the value of the grand total it display the latest value, but not with the POST array
For example. If the grand total is $10.00 and I click on submit. It will show the POST['grand_total'] as empty. If I click on submit again it will show the grand total of $10.00.
Below is my code that I am working with. Any help would be really appreciated.
if(isset($_POST['submit'])) { /* Doesn't show if i put it after if($_POST['submit'] */ if(isset($_POST['grand_total'])) { echo $_POST['grand_total']; } } //A bunch of other html/php code. Another class calculates the subtotal assigns it the variable $subtotal $cart_totals = new cartTotals($subtotal, $discounted_amount,$post_values->tip); // Cart class is shown below /* Doesn't show if i put it before if($_POST['submit'] */ if(isset($_POST['grand_total'])) { echo $_POST['grand_total']; } echo "<input name='grand_total' type='hidden' value='$cart_totals->grand_total' />"; // Shows the grand total after second from submission echo "$cart_totals->grand_total"; // Shows grand total after the first submissionCart Totals Class class cartTotals { public $subtotal; public $sales_tax; public $tip; public $grand_total; public $discount_amount; public $href_page; public $invalidCouponMessage; const TEST_ENVIORMENT = FALSE; /** * [ Function gets constructed in the order summary where the [$discount_amount= ""] arg does need to be passed. * But does get passed in when called on the checkout.php page. Therefore we set the default value to an empty string.] * @param [float] $subtotal [subtotal get passed in from the parent class coreCartFunction] * @param string $discount_amount [The class checkCouponCode calculates this discount amount based on the * subtotal and the discount amount. It gets instantiated on the clients side and passed is this construction function. * This is all done on the checkout page.] */ /*The way the construct function works is by invoking all the methods the passed arguments When the methods get invoked the do all the work and set the properties its values. The properties then get echoed out on the client side. */ function __construct($subtotal="", $discount_amount= "", $tip=""){ $this->subTotal($subtotal, $discount_amount);//SubTotal method takes the discount amount and subtracts it from the subtotal. $this->salesTax($subtotal, $discount_amount); $this->tip = $tip; $this->grandTotal(); } private function subTotal($subtotal,$discount_amount) { $rounded_subtotal = round($subtotal-$discount_amount,2); $money_format_subtotal = money_format('%i',$rounded_subtotal); $this->subtotal = $money_format_subtotal; } private function salesTax($subtotal, $discount_amount =""){ $sales_tax = (STORE_SALES_TAX)?(float)STORE_SALES_TAX:8.875; $sales_tax =(($this->subtotal)*$sales_tax)/100; $sales_tax = round($sales_tax,2); $this->sales_tax = $sales_tax; } public function Tip() { //global $post_values; //$last_tip_selected = $post_values->tip > 0 ? $post_values->tip : "" ; $tip_output = "<select id='tip' name='tip'>"; for($tip=0.00; $tip<=11.75; $tip+=0.25){ if( $tip == "2") {$selected = " selected";} else {$selected ="";} $formatted_tip = money_format('%i',$tip); $tip_output .= "<option {$selected} id='selected_tip' value='$formatted_tip'>"."$".$formatted_tip ."</option>".PHP_EOL; } $tip_output .= "</select>"; return $tip_output; } private function grandTotal(){ $grand_total = round($this->sales_tax+$this->subtotal+$this->tip,2); $grand_total_formatted = money_format('%i',$grand_total); $this->grand_total = $grand_total_formatted; } hi ..
hit little snag Ive got html <form name="formx" method="POST" action="connect.php" class='ajaxform'> and about 4 varibles in that form .. now how to properly
query table users so i can find out which prefix correspond with that user
Insert into table "upis" in this case that prefix with 3 variables..
everything in single,.. in this case connect.php file
I know how to do QUERY and INSERT INTO but i don't know how to connect with 2 different tbl or db and do the query and input of data.. every time I put 2 of them together .. never works out..
this is example.. i dont know is this right way to do it .. When i click my submit button i am posting the following. Array ( [submitStaffOrder] => [staffMember] => Array ( [0] => 2 [1] => ANYCHEF1 ) [date] => Array ( [0] => 2020-02-18 [1] => 2020-02-18 ) [startTime] => Array ( [0] => 11:01 [1] => 10:10 ) [finishTime] => Array ( [0] => 11:01 [1] => 10:01 ) [delExisting] => Array ( [0] => [1] => toDel ) ) I would like to update/insert if delExisting is blank and delete if it has toDel in there. I have the following but i am pretty sure the if is not working. $date = $_POST['date']; $stime = $_POST['startTime']; $ftime = $_POST['finishTime']; $del = $_POST['delExisting']; $staff = $_POST['staffMember']; $stmt = $conn -> prepare(" INSERT IGNORE INTO ssm_staff_order (job_id, staff_id, staff_start_time, staff_finish_time, staff_start_date, staff_finish_date) VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE staff_start_time = VALUES(staff_start_time), staff_finish_time = VALUES(staff_finish_time); "); $delstmt = $conn -> prepare(" DELETE FROM ssm_staff_order WHERE staff_id = ? AND job_id = ? AND staff_start_date = ? "); foreach ($staff as $key => $staffId) { if ($del == '') { $start = $date[$key].' '.$stime[$key]; $finish = $date[$key].' '.$ftime[$key]; $stmt -> bind_param('isssss', $jid, $staffId, $start, $finish, $date[$key], $date[$key]); $stmt -> execute(); } if ($del == 'toDel') { $delstmt -> bind_param('sis', $staffId, $jid, $date[$key]); $delstmt -> execute(); } } } Can i do what i am trying to do or am i way off here?
I struggle with arrays Edited February 24, 2020 by Adamhumbughello 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); ?> I want to remove the HTTP:// or HTTPS:// from the insert into the DB. The Viewer may put just www, or copy the entire URL with the HTTP:// or HTTPS://
I tried using the preg-replace but couldn't seem to get it to work.
Any other recommendation?
Thanks in advance,
Mike
Hi guys, Was wondering if you could help. Apart from using a form are the other ways to POST to a mysql database? e.g. using clicking a link or so. I know this should be easy... I have several text input boxes where I enter data to be sent to one column of my database. Code: [Select] [while($row = mysql_fetch_array( $result )) { $i=1; if ($row['game_id']='$i') { echo "<tr>"; echo "<td>"; echo $row['date']; echo "</td><td>"; echo $row['team_name']; echo "</td><td>"; echo $row['owner']; echo "</td><td>"; echo "<input type='text' size='4' name='result[]'>"; echo "</td></tr>"; Not every box has a value so my array will end up with several numbers and several "blanks". I echoed the array using Code: [Select] $result = ("$_POST[result]"); and all the values are returned as expected. Now I need to UPDATE the "pt_spread" column in the database inserting all the values (even the blank values). I tried the following but can't get it to actually post anything into the database. Code: [Select] <?php header("Location: admin_main_entry.php"); include("opendatabase.php"); $result = ("$_POST[result]"); foreach ($result as $spread) { $sql = " UPDATE schedule SET pt_spread = '$spread' WHERE week_id = '$weekID'" ; mysql_query($sql); } mysql_close($con) ?>Can anyone show me the correct way to do this? Thanks. how do I make the $image piece so that it inserts "images/$image.php" into the database? VALUES('$name', '$id', '$image','$event')"; 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>'; } }
Code: [Select] <?php $con = mysql_connect("localhost", "root", ""); $name = $_GET['jente_navn']; $name = mysql_real_escape_string($name); $ip = $_SERVER['REMOTE_ADDR']; mysql_select_db("name", $con); if ( preg_match("/^[^a-z]|[^A-Z]+/i", $name) ) { die ("Feil: Kan bare bruke gyldige tegn"); }else{ $sql = 'SELECT * FROM banned WHERE name= \'' . $name . '\' OR ip= \'' . $ip . '\''; $result = mysql_query($sql); if( mysql_num_rows($result) ){ print "That Name, or your ip adress is. BANNED!"; } } $sql = "INSERT INTO girl ('girl','accepted','ip') VALUES ('$name', '0', '$ip');"; if ( mysql_query($sql, $con) ){ mysql_close($con); header('http://localhost/takk.php'); }else{ mysql_close($con); header('http://localhost/error.php'); } ?> I don't get any errors, but it still doesn't post the name in the database, even though the name doesn't exist or ain't banned. :s |