Jump to content

Search the Community

Showing results for tags 'insert'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. I am finding that if I have "0"(zero) value in form select option, it won't select this option or submit data. If I change this value to any other number to text, it will work. Is there a way to fix this? I have to have an option where I am able to choose to submit "0" value to the database table. <option value="0" <?php if(empty($_POST['special'])) {} else { if($_POST['special'] == 0) { echo 'selected'; } } ?> >None</option>
  2. Hi there guys, I've a little problem with inserting a file name into a database table. I can't see wich is the problem. The code is bellow and i think the problem is at INSERT INTO part. <?php $path = "./cv/"; $valid_formats = array("doc", "pdf"); if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") { $name = $_FILES['photoimg']['name']; $size = $_FILES['photoimg']['size']; if(strlen($name)) { list($txt, $ext) = explode(".", $name); if(in_array($ext,$valid_formats)) { if($size<(20480*20480)) // Image size max 20 MB { $actual_image_name = time().$id.".".$ext; $tmp = $_FILES['photoimg']['tmp_name']; if(move_uploaded_file($tmp, $path.$actual_image_name)) { mysqli_query($mysqli,"INSERT INTO formular_client (client_cv = '$actual_image_name')"); } else echo "failed"; } else echo "Image file size max 20 MB"; } else echo "Invalid file format.."; } } ?> <input type="file" name="photoimg" id="photoimg" />
  3. Hi, I'm quite new to OOP PHP and i'm trying to make a dynamic insert function , i've followed an example on Stackoverflow to do so since its my first try at making something dynamic.http://stackoverflow.com/a/13333344/3559635 It works but im still quite confused about the two foreach loops , and if possible could someone explain that part to me please and or is there an easier more clean way to do this for a new guy like me? Im sending my POST values from the index.php <?php include("Database.php"); $db = new Database(); var_dump($db); $table = "users"; $whitelist = array('username', 'password'); $data = array_intersect_key($_POST, array_flip($whitelist)); if(isset($_POST['username']) AND ($_POST['password'])) { $db->postTesting($data, $table); } else { echo "Please fill in everything!"; } Database.php <?php class Database { private $connection; private $typedb = "mysql"; private $host = "127.0.0.1"; private $dbname = "oopphp"; private $username = "root"; private $password = ""; public function __construct() { try{ $this->connection = new PDO($this->typedb. ":host=".$this->host. ";dbname=".$this->dbname, $this->username, $this->password); $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $this->connection; } catch(PDOException $e) { throw new Exception("Connection failed: ".$e->getMessage()); } } public function postTesting($data, $table) { try{ //var_dump($table, $data); $columns = ""; $holders = ""; foreach ($data as $column => $value) { //var_dump($column); //var_dump($value); $columns .= ($columns == "") ? "" : ", "; $columns .= $column; $holders .= ($holders == "") ? "" : ", "; $holders .= ":$column"; //var_dump($columns); //var_dump($holders); } $sql = "INSERT INTO $table ($columns) VALUES ($holders)"; //return $sql; $stmt = $this->connection->prepare($sql); //var_dump($stmt); foreach ($data as $placeholder => $value) { $stmt->bindValue(":$placeholder", $value); //var_dump($stmt); //var_dump($placeholder); //var_dump($value); } //var_dump($sql); //var_dump($stmt); $stmt->execute(); } catch(PDOException $rError) { throw new Exception("Registering Failed: ".$rError->getMessage()); } } } Im seriously confused about this part. foreach ($data as $column => $value) { //var_dump($column); //var_dump($value); $columns .= ($columns == "") ? "" : ", "; $columns .= $column; $holders .= ($holders == "") ? "" : ", "; $holders .= ":$column"; //var_dump($columns); //var_dump($holders); } Thanks in advance for the help
  4. Hi, The following code was written by someone else. It allows me to upload images to a directory while saving image name in the mysql table. I also want the code to allow me save other data (surname, first name) along with the image name into the table, but my try is not working, only the images get uploaded. What am I missing here? if(isset($_POST['upload'])) { $path=$path.$_FILES['file_upload']['name']; if(move_uploaded_file($_FILES['file_upload']['tmp_name'],$path)) { echo " ".basename($_FILES['file_upload']['name'])." has been uploaded<br/>"; echo '<img src="gallery/'.$_FILES['file_upload']['name'].'" width="48" height="48"/>'; $img=$_FILES['file_upload']['name']; $query="insert into imgtables (fname,imgurl,date) values('$fname',STR_TO_DATE('$dateofbirth','%d-%m-%y'),'$img',now())"; if($sp->query($query)){ echo "<br/>Inserted to DB also"; }else{ echo "Error <br/>".$sp->error; } } else { echo "There is an error,please retry or check path"; } } ?> joseph
  5. Hello I have this multi dimensional array which needs to be inserted to the database table. [business] => Array ( [title] => Email Marketing [URL] => email-marketing [category] => 3 [region] => 2 ) [description_] => Array ( [text] => Some desc ) [logo_] => Array ( [blob] => mainlogo.png ) [location_] => Array ( [text] => Array ( [0] => Lemara Main Office [1] => Themi branch [2] => Sinoni branch ) [priority] => Array ( [0] => 1 [1] => 2 [2] => 3 ) ) [photo_] => Array ( [path] => Array ( [0] => lemaraphoto.png [1] => themiphoto.png [2] => sinoniphoto.png ) ) [video_] => Array ( [path] => Array ( [0] => lemaravideo.mp4 [1] => themivideo.mp4 [2] => sinonivideo.mp4 ) ) [product_] => Array ( [p_id] => Array ( [0] => product photo [1] => product 3 photo [2] => Product 2 photo ) [text] => Array ( [0] => product desc [1] => product 3 desc [2] => product 2 desc ) [expire] => Array ( [0] => product expire [1] => product 3 expire [2] => Product 2 expire ) [title] => Array ( [0] => product [1] => Product 3 [2] => Product 2 ) ) [service_] => Array ( [p_id] => Array ( [0] => Service 2 photo [1] => service 3 photo [2] => service photo ) [text] => Array ( [0] => service 2 desc [1] => service 3 desc [2] => service desc ) [expire] => Array ( [0] => Service 2 expire [1] => service 3 expire [2] => service expire ) [title] => Array ( [0] => Service 2 [1] => service 3 [2] => service ) ) ) That's the data. The database table, the table field and the corresponding value to be inserted in to the database. I'm using CodeIgniter any help would be appreciated. I have managed to make it wotk in this format [[business] => Array ( [title] => Email Marketing [URL] => email-marketing [category] => 3 [region] => 2 ) [description_] => Array ( [text] => Some desc ) [logo_] => Array ( [blob] => mainlogo.png ) ] I used this code to do it function add_bz($data){ $this->db->trans_start(); $er=0; foreach($data as $table => $sql){ if($table==="business"){ $this->db->insert($table, $sql); $id = $this->db->insert_id(); } else { array_merge($sql, array('idd' => $id)); $this->db->insert($table, $sql);} } $this->db->trans_complete(); if ($this->db->trans_status() === FALSE){print "Transaction Fails";return FALSE;} return TRUE; } Thanks in advance.
  6. Hi, I am trying to create an admin page for a local Gym Club to allow an Administrator to be able to update club prices which then show on different screens on the site. I have been able to display the "Prices Admin" page which basically reads a MySQL database table (pricelist), display the description, member price and non-member price and allows the user to update any of these fields. My problem is that when I try writing the data back to the database with the "UPDATE" statement it fails, what I mean is that nothing updates. I have at the moment commented out the actual update statement and put in a "file_put_contents" command" to try and work out what is in the various fields before the UPDATE is run. I find that the display/INPUT works perfectly well but when I do a foreach on the $record array variable I am getting strange results. I may not have explained this very well but here are the relevant sections of my code; // Display and Input section <div id="admin-area"> <br><br> <a class="admin-left">ADMIN (Class Screen Text & Prices)</a> <br> <div class="admin"> <form name="prices" class="pure-form pure-g " action="?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post"> <fieldset> <textarea id="price-data" name="price-data" rows="5" cols="90"> <?php print(htmlentities($data)) ?> </textarea> <br><br> <label class="pure-u-1-3"> </label> <label class="pure-u-1-3"> <b>Members</b> </label> <label class="pure-u-1-3"> <b>Non-Members</b> </label> <?php $i = 0; while($i < $count) { ?> <input class="pure-u-1-3" id="price_label" type="text" name="records[$i][detail]" value="<?= htmlentities($records[$i]['detail'])?>" maxlength="40" /> <input class="pure-u-1-3" id="price_member" type="text" name="records[$i]" value="<?= htmlentities($records[$i]['price_member'])?>" maxlength="10" placeholder="Member Price" /> <input class="pure-u-1-3" id="price_non" type="text" name="records[$i][nonmember]" value="<?= htmlentities($records[$i]['price_nonmember'])?>" maxlength="10" placeholder="Non Member Price" /> <br> <?php $i++; } ?> <div> <br> <input class="button-input" id="submit" type="submit" name="update" value="Update" /> </div> </fieldset> </form> </div> </div> This results in 11 records displayed on the screen correctly. // In the update section I have removed the actual UPDATE and just used the "put_file_contents()" to show what is in the records array. <?php if (isset($_POST['update'])) { if($_POST['update']=='Update') { file_put_contents('codetest.txt', "File Count - " . $count . "\n", FILE_APPEND); $i = 0; foreach ($_POST[records] as $row) { file_put_contents('codetest.txt', $i . " " . $row['detail'] . " " . $row['member'] . " " . $row['nonmember'] . "\n", FILE_APPEND); $i++; } When run the contents in the codetest.txt is; File Count - 11 0 Party: Airtrack 40.00 30.00 The strange thing here is that the $i = 0 is the first record but the $row['detail'], $row['member'] and $row['nonmember'] details of "Party: Airtrack", 40.00, 30.00 are from record 11 ie the last record. If you want to see the UPDATE code I have been using please let me know and I will post it up here. Any help would be appreciated here. Ian
  7. Hello there, I'm really new at PHP and I've been reading several beginner tutorials so please accept my apologies for any stupid questions I may ask along the way. I've gotten as far as installing XAMPP, set up a database plus PHP form and I'm struggling to figure out how to insert values from an array into my database. I've learnt the code in one particular way (see beginner tutorials) so I was wondering if you could help me keeping this in mind. I know there'll be a million better ways to do what I'm doing but I fear I will be bamboozled with different code or differently structured code. Anyway the tutuorials I'm reading don't see to cover how I can insert an array of values into my database, just singular values. In the attached file, I have 10 rows of 2x text inputs (20 text inputs total). Each row allows the user to enter a CarID and CarTitle. I've commented out the jQuery which validates the inputs so I can build a rudimentary version of this validation with PHP. I thought that because the line $sql="INSERT INTO carids_cartitles (CarID, CarTitle) VALUES ($id, $title)"; is inside the foreach, means that for each pair of values from the form it'd insert to the database. It doesn't do this. If I enter two or more CarIDs and CarTitles, only one pair of values gets saved to the database. I'm sorry if I haven't explained this well enough, any questions please let me know. Many thanks for your help in advance. form.php
  8. hi guys so i have this add contacts page and the form is divided into 3 different froms 1) primary contact 2)spouse 3)child and the child form data is inserted as array into database because in the primary contact part of the form there is a "Children ?" with yes and no radio button and if yes a drop down list is enabled where if user chooses say 2 then there would be 2 child form that appears. and since theres 2 children then in the database a new row and data will be added accordingly. image attached to be clearer. i got it inserted into database but in the specified field it says array: |child_name|dob|house_add1|mobile|office|email| inserted: |array|array-array-array|array|array|array|array| query: "INSERT INTO child VALUES('','".$childsalutations." $childfname $childlname',' ".$cday."-".$cmonth."-$cyear ','$childline1','$childline2','$childm','$childoff','$childemail')" in a stackoverflow question(not my own question) someone says: information stating arrays need to be split, before inserting into the table. does that mean something like this?: $cday = ($_POST['cday']); $cmonth = ($_POST['cmonth']); $cyear = ($_POST['cyear']); $childsalutations = ($_POST['child-salutations']); $childfname = ($_POST['child-fname']); $childlname = ($_POST['child-lname']); $childline1 = ($_POST['child-line1']); $childemail = ($_POST['child-email']); $childm = ($_POST['child-mobile']); $childoff = ($_POST['child-office']); $info = array('c_name' => $childsalutation $childfname $childlname, 'c_dob' => $cday-$cmonth-$cyear, 'c_line1' => $childline1, 'c_mobile' => $childm, 'c_office' => $childoff, 'c_email' => $childemail) just in case u wanted to c the html child form(warning its abit long,very!): <table class="prime"> <tbody> <br> <tr><td style="font-size:20px;font-weight:bold">Child <span id="number"></span></td></tr> <tr> <td>Salutation :</td> <td><select name="child-salutations[]" id="child-salutations"> <option value="" disabled selected>Salutations</option> <option value="Datin">Datin</option> <option value="Datin Paduka">Datin Paduka</option> <option value="Dato Paduka">Dato Paduka</option> <option value="Dato'">Dato'</option> <option value="Dato' Seri">Dato' Seri</option> <option value="Datuk">Datuk</option> <option value="Datuk Seri">Datuk Seri</option> <option value="Dr.">Dr.</option> <option value="Haji">Haji</option> <option value="Hajjah">Hajjah</option> <option value="HM">HM</option> <option value="HRH">HRH</option> <option value="Miss">Miss</option> <option value="Mrs.">Mrs.</option> <option value="Mr.">Mr.</option> <option value="Pehin">Pehin</option> <option value="Professor">Professor</option> <option value="Raja">Raja</option> <option value="Tan Sri">Tan Sri</option> <option value="Tengku">Tengku</option> <option value="Tuanku">Tuanku</option> <option value="Tun">Tun</option> <option value="Tunku">Tunku</option> <option value="Ungku">Ungku</option> </select> </td> </tr> <tr><td colspan="2"><label class="label" style="color:Red">*If a person has many salutations, choose the highest form of salutation</label></td></tr> <tr><td>First Name :</td><td><input type="text" name="child-fname[]" id="child-fname" class="style" /></td> <td>Last Name :</td><td><input type="text" name="child-lname[]" id="child-lname" class="style" /></td></tr> <tr> <td>Date of Birth : </td> <td> <select name="cday[]"> <option value=""selected disabled>Day</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="cmonth[]"> <option value="" selected disabled>Month</option> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> Year : <input type="text" name="cyear[]" maxlength="4" size="4" class="year"> </td> </tr> <tr><td>Where do they live ?</td><td colspan="3"><input type="radio" name="living[]" id="living-me" class="living-me"/>With Me<input type="radio" name="living[]" id="living-other" class="living-other"/>With Other Parent<input type="radio" name="living[]" id="living-own" class="living-own"/>Own</td></tr> <tr><td>House Address</td></tr> <tr><td>Line 1 :</td><td><input type="text" name="child-line1[]" id="child-line1" size="20" class="style" /></td> <td>Mobile No :</td><td><input type="text" name="child-mobile[]" id="child-mobile" class="style" /></td></tr> <tr><td>Office No :</td><td><input type="text" name="child-office[]" id="child-office" class="style" /></td> <td>Email Address : </td><td><input type="email" name="child-email[]" id="email" class="style" /></td></tr> </tbody> </table>
  9. Hi guys. I currently have the following: $UserID1 $TeamID1 $Points1 Where the value goes from 1 to 24, I need to insert all of these in to their own rows in a database how would I be best off doing that? Would I be able to use a foreach statement whereby the number increases? Or is there another way that doesn't involve doing 24 inserts? Thanks in advance!
  10. I have my form created, and want to link it to an insert.php file where I can save data to database. Normally, I would have done it like this: <form method="post" action="insert.php"> Although, I have done my form a different way than usual to help security precautions(Reference: http://www.w3schools.com/php/php_form_complete.asp) <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> Name: <input type="text" name="name" value="<?php echo $name;?>"> <span class="error">* <?php echo $nameErr;?></span> <br><br> E-mail: <input type="text" name="email" value="<?php echo $email;?>"> <span class="error">* <?php echo $emailErr;?></span> <br><br> Website: <input type="text" name="website" value="<?php echo $website;?>"> <span class="error"><?php echo $websiteErr;?></span> <br><br> Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea> <br><br> Gender: <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male <span class="error">* <?php echo $genderErr;?></span> <br><br> <input type="submit" name="submit" value="Submit"> </form> My form's action attribute is filled with php code already, so where do I link to my insert.php file now? Can I still put a file name next to the php code that is already there? Can I do it like this, adding an onclick attribute that links to insert.php file?: <input type="submit" name="submit" value="Submit" onclick="insert.php">
  11. Here is the code for both the connection file and the main body of script. I assure you the passwords and actual names do match as I have done other tests before hand. register.php <?php $title = "Register"; include 'includes/header.php'; if($_SERVER['REQUEST_METHOD'] == 'POST') { require 'includes/connection.php'; //create FALSE figures $username = $password = FALSE; //trim all data $trimmed = array_map('trim', $_POST); $errors = array(); //check username if(preg_match ('/[A-Za-z0-9]{2,20}/', $trimmed['username'])) { $username = mysqli_real_escape_string($dbc, $trimmed['username']); } else { $errors[] = 'Enter a username'; } //check password if(preg_match ('/[A-Za-z0-9]{4,20}/', $trimmed['password'])) { $username = mysqli_real_escape_string($dbc, $trimmed['password']); } else { $errors[] = 'Enter a password'; } //variables not == FALSE if($username && $password) { $q = "SELECT user_id FROM users WHERE username='$username'"; $r = mysqli_query ($dbc, $q) OR trigger_error("Query: $q\n<br />MYSQL Error: ". mysql_error($dbc)); if(mysqli_num_rows($r) == 0) { $q = "INSERT INTO users (username, password, registration_date) VALUES ('$username', SHA1('$password'), NOW() )"; $r = mysqli_query ($dbc, $q) OR trigger_error("Query: $q\n<br />MYSQL Error: ". mysql_error($dbc)); } if(mysqli_affected_rows($dbc) == 1) { echo "success"; //header('Location: database.php'); } } else { foreach ($errors as $msg) { echo " - $msg<br />\n"; } } } ?> <form action="register.php" method="POST"> <input type="text" name="username" value="<?php if(isset($trimmed['username'])) echo $trimmed['username']; ?>" placeholder="Username"/> <input type="password" name="password" value="<?php if(isset($trimmed['username'])) echo $trimmed['password']; ?>" placeholder="Password"/> <input type="submit" class="button1" name="Sign Up" /> </form> connection.php <?php $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = 'password'; $db = 'ze'; $dbc = mysqli_connect($dbhost, $dbuser, $dbpass) OR die ('Could not connect. MYSQL:' .mysql_error() ); mysql_select_db($db); Whenever I run this it does not seem to want to work, and also outputs no errors. I probably cant see something and need a second opinion.
  12. I'm having issues converting to MySQLI, can someone take a look for me. Thanks, salestatusupdateplusone.php
  13. Hi guys, I have written this code to insert shopping items in a database but recently when user adds an item, item code is inserted as 0, I have also my php error on but still cant not figure out why and this happens to both add-product and service posts. It inserts everything else correctly except product or service no Any advise or help is appreciated <?php include_once('includes/header.php'); ?> <?php $get_car_reg = mysql_real_escape_string($_GET['car']); $get_car_reg = mb_strtoupper($get_car_reg); $get_invoice = mysql_real_escape_string($_GET['invoice']); if (isset($_POST['delete'])) { $delete_current_item = mysql_real_escape_string($_POST['delete_me']); $delete = mysql_query("DELETE FROM items WHERE id='$delete_current_item'"); header("Location:generate_invoice.php?car=$get_car_reg&invoice=$get_invoice"); } if (isset($_POST['sp'])) { $final_total = mysql_real_escape_string($_POST['final_total']); $final_discount = mysql_real_escape_string($_POST['final_discount']); $final_invoice_sub = mysql_real_escape_string($_POST['final_sub_total']); $final_vat = mysql_real_escape_string($_POST['final_vat']); $final_total = $final_total - $final_discount; $select_current = mysql_query("SELECT * FROM invoices WHERE invoice_no='$get_invoice'"); if (mysql_num_rows($select_current) >= 1) { $update = mysql_query("UPDATE invoices SET invoice_no='$get_invoice', sub_total='$final_invoice_sub', vat='$final_vat', total='$final_total', discount='$final_discount' WHERE invoice_no='$get_invoice'"); } else { $insert = mysql_query("INSERT INTO invoices (invoice_no, sub_total, vat, total, discount) VALUES ('$get_invoice','$final_invoice_sub','$final_vat','$final_total','$final_discount')"); } if ($insert || $update) { header("Location: print.php?car=$get_car_reg&invoice=$get_invoice"); } } ?> <h2>Invoice</h2> <h3>Car Reg: <?php echo"$get_car_reg"; ?></h3> <? if (empty($get_car_reg) || empty($get_invoice)) { header("Location: create-customer.php"); } else { if (isset($_POST['add-product'])) { $item_price = mysql_real_escape_string($_POST['item_price']); $new_product_no = mysql_real_escape_string($_POST['product_no']); if (empty($new_product_no) || $new_product_no = '0') { echo"<div class='alert alert-error'>You need to select an item</div>"; } else { $insert = mysql_query("INSERT INTO items (invoice_no, item_no, item_type, price) VALUES ('$get_invoice','$new_product_no','Product','$item_price')"); echo"$new_product_no is"; // header("Location:generate_invoice.php?car=$get_car_reg&invoice=$get_invoice"); } } else { if (isset($_POST['add-service'])) { $item_price = mysql_real_escape_string($_POST['item_price']); $new_service_no = mysql_real_escape_string($_POST['service']); if (empty($new_service_no) || $new_service_no = '0') { echo"<div class='alert alert-error'>You need to select an item</div>"; } else { $insert = mysql_query("INSERT INTO items (invoice_no, item_no, item_type, price) VALUES ('$get_invoice','$new_service_no','Service', '$item_price')"); header("Location:generate_invoice.php?car=$get_car_reg&invoice=$get_invoice"); } } } } ///$query="SELECT sum(price) FROM Fuel"; ?> <div class="left-column"> <form class="form" action="" method='POST'> <div class="control-group"> <label>Select Service</label> <div class="controls"> <select name="service"> <option value="0">Select one</option> <?php $select_services = mysql_query("SELECT * FROM services"); while ($row = mysql_fetch_array($select_services)) { $service_name = $row['service_name']; $service_price = $row['service_price']; $service_no = $row['service_no']; echo"<option value='$service_no'>$service_name</option>"; } ?> </select></div></div> <input type="hidden" name="item_price" value="<?php echo"$service_price"; ?>"> <button type="submit" name="add-service" class="btn btn-primary">Add</button> </form> <hr/> <form class="form" action="" method="post"> <div class="control-group"> <label>Select Products</label> <div class="controls"> <select name="product_no"> <option value="0">Select one</option> <?php $select_products = mysql_query("SELECT * FROM products"); while ($row = mysql_fetch_array($select_products)) { $product_sku = $row['sku']; $product_price = $row['price']; $product_name = $row['product_name']; echo"<option value='$product_sku'>$product_name</option>"; } ?> </select></div></div> <input type="hidden" name="item_price" value="<?php echo"$product_price"; ?>"> <button type="submit" name="add-product" class="btn btn-primary">Add</button> </form> <hr/> </div> <div class="right-column"> <table class="table"> <thead> <tr> <th>#</th> <th>Item Type</th> <th>Item Name</th> <th>Item No</th> <th>Price</th> <th>Remove</th> </tr> </thead> <tbody> <tr> <?php $select = mysql_query("SELECT * FROM items WHERE invoice_no='$get_invoice'"); while ($row = mysql_fetch_array($select)) { $current_item_id = $row['id']; $current_item_type = $row['item_type']; $current_item_no = $row['item_no']; $current_item_price = $row['price']; $select_item_name = mysql_query("SELECT * FROM services WHERE service_no='$current_item_no'"); if (mysql_num_rows($select_item_name) == 1) { while ($row = mysql_fetch_array($select_item_name)) { $current_item_name = $row['service_name']; } } /// else { $select_item_name = mysql_query("SELECT * FROM products WHERE sku='$current_item_no'"); if (mysql_num_rows($select_item_name) == 1) { while ($row = mysql_fetch_array($select_item_name)) { $current_item_name = $row['product_name']; } } /// } echo" <tr> <td>$current_item_id</td> <td>$current_item_type</td> <td>$current_item_name</td> <td>$current_item_no</td> <td>&pound$current_item_price</td> <td><form method='post' action=''><input type='hidden' name='delete_me' value='$current_item_id'><input type='submit' class='btn btn-danger' name='delete' value='Delete'></form></td> </tr> "; } ?> </tbody> </table> <form method="post" action=""> <table class="table"> <thead> <tr> <th>Discount</th> <th>Subtotal</th> <th>Total</th> </tr> </thead> <tbody> <tr> <td><input type="text" name='final_discount' placeholder='2.99' class='input input-mini'/></td> <td><?php $subtotal = mysql_query("SELECT sum(price) FROM items WHERE invoice_no='$get_invoice'"); $invoice_sub = mysql_fetch_array($subtotal); echo"&pound$invoice_sub[0]"; ?> </td> <td><?php $vat_q = mysql_query("SELECT * FROM company_config WHERE id='1'"); while ($row = mysql_fetch_array($vat_q)) { $vat = $row['vat_percentage']; } $total_vat = $vat * $invoice_sub[0] / 100; $total = $total_vat + $invoice_sub[0]; echo"&pound$total"; ?></td> </tr> </tbody> </table> <input type='hidden' name='final_total' value='<?php echo"$total"; ?>'> <input type='hidden' name='final_sub_total' value='<?php echo"$invoice_sub[0]"; ?>'> <input type='hidden' name='final_vat' value='<?php echo"floor($total_vat)"; ?>'> <div class='btn-group'> <button class='btn btn-primary' name='sp' type='submit'>Save & Print</button> </div> </form> </div> <?php include_once('includes/footer.php'); ?>
  14. Insert function not working like the select functions are.. :~ I have a functions file that contains a number of mysqli_query query's that other php pages successfully call, including the page in question. For round numbers I have 10 functions total. Of the 10, 9 are select query's, 1 is an insert. All of the select query's work including 2 on the page in question. These 2 query's populate 2 drop down menus in a form. When I submit the form I am $_POST ing all the fields to another PHP file that parses the data, calls the insert function -> sends the values, then sends an e-mail using PHPMailer.. When I call the Insert query (submit the form), I am returned "Error updating databaseNo database selected" Error. All of the php pages have an include statement on top pointing to a connection file. IF I put a DB connection string inside the insert function, per below, the insert function works when called.. There's gotta be something basic I'm missing with how I have my stuff setup.. Does anybody have advice? Or I guess I could have everything on one page / file.... mysql_connect("server", "user", "pass") or die('Can\'t connect because:' .mysql_error()); mysql_select_db ("database"); thanx
  15. I am having trouble getting a simple form to submit data to a database. I have followed an example in a PHP/MySQL book (Welling and Thomson) and created a simple form to update a DVD collection. Right now I just have a form started and am just trying to get it to INSERT records into my database. It is making a connection to the database, but it returns my Error stating that the record could not be added. While all of my code is very basic,I am just trying to get an understanding as to how it is working... I have looked in MySQL through command prompt and the database exists, but records are not being added. I can add records to the table through CMD prompt. I will post my code for the database and my two php files for inserting records. Database: create database movie_info; use movie_info; create table movies (movieid int unsigned not null auto_increment primary key, title char(50) not null, movieyear char(4) not null, genre char(25) not null, subgenre char(25), director char(30), actor1 char(30), actor2 char(30), actor3 char(30), discs char(2), season char(2), comments char(200) ); Form: function input_form(){ ?> <form method="post" action="insert_movie.php"> <table bgcolor="#cccccc"> <tr> <td colspan="2">Enter a new DVD:</td> <tr> <td>Title:</td> <td><input type="text" name="title"/></td></tr> <tr> <td>Year:</td> <td><input type="text" name="year"/></td></tr> <tr> <tr> <td>Genre:</td> <td><input type="text" name="genre"/></td></tr> <tr> <tr> <td>Sub-Genre:</td> <td><input type="text" name="subgenre"/></td></tr> <tr> <tr> <td>Director:</td> <td><input type="text" name="director"/></td></tr> <tr> <tr> <td>Actor:</td> <td><input type="text" name="actor1"/></td></tr> <tr> <tr> <td>Actor:</td> <td><input type="text" name="actor2"/></td></tr> <tr> <tr> <td>Actor:</td> <td><input type="text" name="actor3"/></td></tr> <tr> <tr> <td>Number of discs:</td> <td><input type="text" name="discs"/></td></tr> <tr> <tr> <td>Season:</td> <td><input type="text" name="season"/></td></tr> <tr> <tr> <td>Comments:</td> <td><input type="text" name="comments"/></td></tr> <tr> <td colspan="2" align="center"> <input type="submit" value="Submit"/></td></tr> <tr> </table></form> <?php } and the INSERT code: <?php require_once('movie_functions.php'); //require_once('db_functions.php'); do_html_header('Moviebase'); @$title = $_POST['title']; @$year = $_POST['year']; @$genre = $_POST['genre']; @$subgenre = $_POST['subgenre']; @$director = $_POST['director']; @$actor1 = $_POST['actor1']; @$actor2 = $_POST['actor2']; @$actor3 = $_POST['actor3']; @$discs = $_POST['discs']; @$season = $_POST['season']; @$comments = $_POST['comments']; if (!$title || !$year || !$genre) { echo "You have not entered all of the required details. <br />" ."Please go back and try again.<br /><br />" ."<a href='movies.php'>Go Back</a>"; exit; } @$db = new mysqli('localhost', 'root', '********', 'movie_info'); if (mysqli_connect_errno()) { echo "Error: Could not connect to database. Please try again later."; exit; } $query = "INSERT INTO movies VALUES (NULL, '".$title."', '".$year."', '".$genre."', '".$subgenre."', '".$director."', '".$actor1."', '".$actor2."', '".$actor3."', '".$discs."', '".$season."', '".$comments."')"; $result = $db->query($query); if ($result) { echo $db->affected_rows." has been inserted into the database."; //input_form(); } else { echo "An error has occurred. The item was not added."; //for testing echo "<br />Result: ".$result; echo "<br />".$title; echo "<br />".$year; echo "<br />".$genre; echo "<br />".$subgenre; echo "<br />".$director; echo "<br />".$actor1; echo "<br />".$actor2; echo "<br />".$actor3; echo "<br />".$discs; echo "<br />".$season; echo "<br />".$comments; //input_form(); } $db->close(); footer(); ?> This all will return all variable values (except $result), so it seems like $result is empty. Any help in understanding this would be greatly appreciated, Thanks!
  16. I am a newbie and I am in need of some help. Currently, I have a email being piped to a program via cpanel "forwarder" advance tap. The parsing seeems to be doing its function but I cannot get it to insert the data into the table. HEre is hte code prior to insert. Can someone help me understand how to write this correct. The idea is that for every new alert extract the date, then insert in to the table. yOU help would be appreciated! $sql = "INSERT INTO `LOG_TABLE` (`Type`, `Symbol`, `Score`, `Timestamp`) VALUES "; foreach($alerts as $alert) { preg_match("!^Alert[1-9]+ \((MRI|QT)\):<br />(.*?)$!i", trim($alert), $m); $stocks = explode(", ", trim($m[2])); foreach($stocks as $stock) { list($symbol, $score) = explode(":", $stock); $sql .= "('".$m[1]."', '".$symbol."', '".$score."', FROM_UNIXTIME(now()), "; } } $sql = trim($sql, " ,"); if ( ! empty($sql) ) mysqli_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASS); mysqli_select_db(DB); mysqli_query($sql)or die(mysql_error()); } exit(0);
  17. Hello, i have a table i have to fill out with info regarding other tables, is a join possible or do i have to make 2 queries? This is what i have right now. $date = date("Y-m-d H:i:s"); $sql = "INSERT INTO tblpaqueteria ( sender_id, reciever_id, AddTime, Estatus, ubicacion, tipo,slocalidad_id,rlocalidad_id ) VALUES ( '{$_POST['id_send']}', '{$_POST['id_rec']}', '{$date}', '0' , '0', '{$_POST['tipo_paq']}',0,0 )"; $res = mysql_query($sql,$this->conn); return $sql; What i need now is to change some of my insert into dynamic ones, i have to enter into "slocalidad_id" and into "ubicacion" the "id" of a table called localidad, and this id is being referenced from a table called "usuarios" (users) where "$_POST['id_send']" where localidad_id marks the id i need to insert into tblpaqueteria. I am not sure if I explained myself correctly so ill try and make an example. usuarios So for my sql above, without joins i would be receiving from POST id_send = 2 and from id_rec 11 so my query should insert this $sql = "INSERT INTO tblpaqueteria ( sender_id, reciever_id, AddTime, Estatus, ubicacion, tipo,slocalidad_id,rlocalidad_id ) VALUES ( '{$_POST['id_send']}', '{$_POST['id_rec']}', '{$date}', '0' , '2', '{$_POST['tipo_paq']}',2,4 )"; notice the numbers "2" and "4" being inserted, those are the ones i don't know how to enter dynamically, i think its a join, but i don't know how to use them in an insert. Thanks a lot
  18. I can connect to database but when I try to insert row using submit button in PHP, it does run without any error and does nothing, pls help me out....... if($_POST[query]!="") { $n1=$_POST['fname']; $n2=$_POST['number']; $n3=$_POST['email'].$_POST['domain1'].$_POST['domain2']; $n4=$_POST['category']; $n5=$_POST['query']; $year=Date("Y"); $month=Date("m"); $day=Date("d"); $now=$year."-".$month."-".$day; $sql=("INSERT INTO table_name (Name,Number,Email,Category,Query,Date) VALUES('$n1','$n2','$n3','$n4','$n5','$now')") or die(mysql_error()); if (!mysql_query($sql,$connect)) { die('Error: ' . mysql_error($connect)); }else{echo $n1." ".$n2." ".$n3." ".$n4." ".$n5." ".$now;} echo "1 record added"; }
  19. Hi friends I'm trying to insert a string into a mysql database. The form of my string is this "1.32G3.33G0.67G1.66G0.88G9G14.56" I select "text" as Type. I put my string on variable $myString="1.32G3.33G0.67G1.66G0.88G9G14.56"; No i'm trying to insert this string to mu database using this code: mysql_query("INSERT INTO myDataBase (stringData) VALUES ('$myString'"); Nothing... What is wrong? Waiting for ideas. Thank you
  20. I have the following code set up to insert data into my table. This is just a test to see if it will work before I go further into development. I know I'm able to connect to my data as I have a message appear when that happens, but it won't insert data into the table for some reason. $phoneNumber = "0786352373"; $firstName = "jennifer"; $lastName = "dunne"; $profilePicture = ""; $photo = ""; $video = ""; $text = "text is here yes yes eys"; $call = "call is here yes yes eys"; $activity = "this is jennifers activity"; $latitude = "-50.889473"; $longitude = "3.845738"; $date = "23/05/2012"; $time = "13:29"; $sql = "INSERT INTO member (phoneNumber, firstName, lastName, profilePicture, photo, video, text, call, activity, latitude, longitude, data, time) "; $sql .= "VALUES ('$phoneNumber', '$firstName', '$lastName', '$profilePicture', '$photo', '$video', '$text', '$call', '$activity', '$latitude', '$longitude', '$data', '$time')"; if (!mysqli_query($sql, $con)) { die('Error: ' . mysqli_error()); } else { echo "Comment added"; } mysqli_close($con); I do get an error message come up, but all it says is the following and doesn't shine light on the situation at all. Error: I'm very new to mysql and always seem to struggle with it but want to get over my fear of it. :-)
  21. Hey all this is my first time posting and was wondering if I could get some help and see what I am doing wrong. // I've tried my best to find my answer through google searches and after days of working on this I finally decided to ask for some guidence. // Project: I am trying to make a web based form that will take information about my comic books and input them into a mysql database. Info: I have got the code for the html input page all done and have it sending the $_POST[''] variables to another script that will actually input the data into the database. / In addition this app is only available to me and won't be facing the public world so I have left out the checks on the data since most of it is controled variables from the form. Problem: After I input the 7 values into the html form and submit them the script never inputs the data. I have echoed out the $_POST[''] variables to make sure they were being passed correctly and well they are. Question: It's a multi part question / a.) Can anyone see what I am doing wrong in my INSERT statement and mysqli_query b.) Is there a better way? I saw PDO but couldn't really wrap my head around it. c.) what could or should I be using to see what mysql is telling me when the INSERT statement runs to see if Its a problem on the other side. What I've done/tried: Seems like too much too say... lol but I've verified the user permissions for the DB and the user I'm connecting with and it has full rights on DB / Multiple INSERT statements but none of em work. / I've tried moving the table into a separate database scheme (still no go) / I've tried different ways of selecting the DB outside of the connection params as well as in the connection params with no favorable result. / I tried using the string that mysql workbench creates to input values the same as the php code to input values and that didn't work. Code: [comic_form.php] $comic_db = mysqli_connect("foo", "bar", "foobar", "comic_info_db"); if(!$comic_db){ echo "Connection to DB Failed"; } else { echo "Connect to DB Established"; } // Variables From Web Form $idcomic_db = $_POST['idcomic_db']; $publisher = $_POST['publisher']; $comic_name = $_POST['comic_name']; $comic_num = $_POST['comic_num']; $comic_cover = $_POST['comic_cover']; $price_paid = $_POST['price_paid']; $quantity = $_POST['quantity']; $sql_insert = "INSERT INTO `comic_db` (idcomic_db, publisher, comic_name, comic_num, comic_cover, price_paid, quantity) VALUES ('$idcomic_db', '$publisher', '$comic_name', '$comic_num', '$comic_cover', '$price_paid', '$quantity')"; $db_con = mysqli_query($sql_insert, $comic_db); $error = mysqli_error($db_con); In that same script I also have echoed the variables as well as the sql_insert string and this is what I get. I did this just to see what variables were being passed as well as the string that was being created. Dunno if there is a better way to do it. 1 Marvel Comics The Superior Spider-Man 1 original 3.99 1 INSERT INTO `comic_db`.`comic_db` (`idcomic_db`, `publisher`, `comic_name`, `comic_number`, `comic_cover`, `price_paid`, `quantity`) VALUES ('0', 'Marvel Comics', 'The Superior Spider-Man', '1', 'original', '3.99', '1') I've also included a screen shot of the table params from mysql. if it helps I also am using PHP Version 5.3.10-1ubuntu3.6 Sorry if this is lengthy thought more info would be better Thanks for the help
  22. Hi am Newbie when it comes to PHP and MySQL. Over the past week weeks I have been overwhelmed with PHP, MySQL and WampSERVER. Initially the script was working for about 20 columns when I was adding new columns to my database using PHP it lost connection with MySQL. I started from scratch but its not helping. I get no errors and I don't know what I am doing wrong. If anyone can help I would appreciate it very much. If I insert data manually through MySQL it works fine. Any advise is helpful. ConnectingToMysql.php
  23. Hello there; i'd like to make it possible to write all the inputs i write with this text fields but make it in a single row (on a textarea), and make it possible to add multiple "events" in my website instead of one! For example: FIRST ROW IN TEXTAREA: Date - Local Team - Away Team - RatioLocal - Draw - RatioAway - SportID - League SECOND ROW IN TEXTAREA: Date - Local Team - Away Team - RatioLocal - Draw - RatioAway - SportID - League This would be a textarea example: 2013/04/03 21:00 Bolivar The Strongest 2.20 3.20 2.88 1 LFP 2013/04/03 21:00 La Paz Oriente Petrolero 4.33 3.50 1.73 1 LFP 2013/04/03 21:00 Wilstermann Universitario 1.91 3.40 3.60 1 LFP Here are the files i use; you will get my idea as soon as you see them Agregar.php: http://pastebin.com/xeTyjrX8 Config.php: http://pastebin.com/Tyb8SXuQ Please if you need more information ask me about it! Thanks a lot for your help!
  24. I have extensively searched the web for this but haven't found anything that can help! At the moment I have three loops: // loop 1 finds the answers if(isset($_POST['qanswer'])){ ($question = $_POST['qanswer']); for($i=0; $i < count($question); $i++) { echo "POSTED ANSWERS" . $question[$i] . "<br/>"; } } else { echo '<p style="color: Red">No Answers POSTED!</p>'; } // loop 2 finds the comments if(isset($_POST['canswer'])){ ($comment = $_POST['canswer']); for($i=0; $i < count($comment); $i++) { echo "POSTED COMMENTS" . $comment[$i] . "<br/>"; } } else { echo '<p style="color: Red">No Comments POSTED!</p>'; } // loop 3 combines the answers and comments for($x = 0; $x < count($comment); $x++){ if(isset($question[$x])){ $question[$x] = $question[$x] . ' ' . $comment[$x]; } } $result = $question; // saves the answers and comments as a string ($result) Each comment[$i] is the same key and $question[$i]. Inserting into the table i have: $query = "INSERT INTO audit_data (Q4101, Q4102, Q4103, Q4104, etc...) VALUES '$result[0]','$result[1]','$result[2]','$result[3]','$result[4]', etc...)"; mysqli_query($link, $query) or die(mysqli_error($link)." Q=".$query); 1) is this the best way to go about this? 2) It is nearly working, i can get the $question and $comment into the first columns for instance: $result[0] to result[10] but if i try to insert further on in the table say $result[40] to $result[50] i only get the $question values and no $comment values. I have looked at array_map and preg_match on the manual but not sure how or which one to use. I don't want the table normalized and i am aware of injection problems.
  25. Hello, I´m trying to insert data from a form into a mysql table using mysqli and php. I use the code below to connect to the database: $host = "myhost"; $db = "a5066994_tutors"; $user = "a5066994_tutors"; $pass = "mypassword"; $connection = mysqli_connect("$host", "$user", "$pass", "$db"); if ($connection->errno) { printf("Connect failed: %s\n", $connection->error); exit(); and the code below to insert: $stmt = $connection->prepare("INSERT INTO tutorials (Author, Website, Title, Body1, Body2, Body3, Body4, Subtitle1, Subtitle2, Subtitle3, Subtitle4, Category, WTitle, Userid) VALUES ('$author','$website', '$title', '$text1', '$text2', '$text3', '$text4', '$s1', '$s2', '$s3', '$s4', '$cat', '$wtitle', '$userid') "); And it results in this error: Call to a member function execute() on a non-object I have also tried doing a var dump of the connection, which results in: object(mysqli)#1 (0) { } and a var dump of the statement, which results in: bool(false) Any help would be great, thank you!
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.