PHP - Trouble Inserting Array Variables Into Mysql
I am trying to insert values stored within two dimensional array into mysql database but it does not work as I would expect it. The locations in mysql are defined as char length of 2. When I print_r the array it shows:
Array( [0] => Array ( [0] => 04 [1] => 22 [2] => 27 [3] => 28 [4] => 39 [5] => 43 [6] => 47 )) but when I insert them into the mysql like this: Number1A='$MaxMillionsNumber[0][0]', Number1B='$MaxMillionsNumber[0][1]', Number1C='$MaxMillionsNumber[0][2]', Number1D='$MaxMillionsNumber[0][3]', Number1E='$MaxMillionsNumber[0][4]', Number1F='$MaxMillionsNumber[0][5]', Number1G='$MaxMillionsNumber[0][6]'; my values in mysql all show as Ar What am I doing wrong? Similar TutorialsI've got the following code: echo <<<myStringEcho <script src="$myPluginPath/jquery.dummy.js"></script> myStringEcho; The problem is that $myPluginPath already has a / character at the end, so I don't need to put it in above But, I can't just remove it, otherwise I'll get $myPluginPathjquery.dummy.js How can I insert and have no spaces? Thanks OM Hey Guys, I have to insert some data in MySQL but it wont work . Please have a look. <?php // to values are set to empty $vatsim=""; $ivao=""; // values from form in other page are set if(isset($_POST["pilotid"])) $pilotid=$_POST["pilotid"]; if(isset($_POST["network"])) $network=$_POST["network"]; if(isset($_POST["vid"])) $vid=$_POST["vid"]; if(isset($_POST["pilot"])) $pilot=$_POST["pilot"]; // if value is that copy data in this value, otherways in that value if ($network == "IVAO") { $ivao="$vid";} if ($network == "VATSIM") { $vatsim="$ivao";} // connect db include(dbconnect.inc.php); // first sql to update some data in one table $sql = "UPDATE `360283`.`jos_users` SET `IPS` = \'1\' WHERE `jos_users`.`id` = \'$pilotid\'"; $result1 = mysql_query($sql); // 2nd sql to insert some data in other table $sql2 = "INSERT INTO `360283`.`IPS_Pilots` (`ID`, `Name`, `Hours`, `Flights`, `LastFlight`, `IVAO`, `VATSIM`, `Enabled`, `Rating`) VALUES ('$pilotid', '$pilot', NULL, NULL, NULL, '$ivao', '$vatsim', '1', '0');"; $result2 = mysql_query($sql2); // sql to check if it was succesful $sql3 = "SELECT * FROM `IPS_Pilots` WHERE `ID` = '$pilotid' LIMIT 0, 30 "; $result3 = mysql_query($sql3); $num3 = mysql_numrows($result3); // echo succesfull or not if (!$num3) { echo "Sorry, but I failed to apply this pilot."; } else { echo "Pilot succesfully applied."; } ?> Thanks Hi Guys Clearly I still have lots to learn... I am trying to insert (using mysqli) multi-dimensional array values into the database, but when i do the value that gets stored ends up as "$Array[1][1]". Here's the test query i am running: Code: [Select] $sql = "INSERT INTO teams (company) VALUES ('$myarray[1][1]')"; $mysqli->query($sql); So do i need to break the data out of the multidimensional array for the insert? Or is there some syntax thing i've missed? Or worse still do i actually need to do: Code: [Select] $value1 = $myarray[0][0]; Any help would be very much appreciated! Drongo 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.
Attached Files
form.php 4.43KB
5 downloads So I've spent 2 days now searching the web on how to make my checkbox array on my form insert the value selected by the user into my database. Here is the code that I've written. All fields except for the checkbox array works fine. <?php virtual('/budgets/Connections/connAdmin.php'); ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $editFormAction = $_SERVER['PHP_SELF']; if (isset($_SERVER['QUERY_STRING'])) { $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); } if (isset($_POST['submit'])) { $workStyle = $_POST['art_photos']; // Setting up a blank variable to be used in the coming loop. $allStyles = ""; // For every checkbox value sent to the form. foreach ($workStyle as $style) { // Append a string called $allStyles with the current array element, and then add a comma and a space at the end. $allStyles .= $style . ", "; } // Delete the last two characters from the string. $allStyles = substr($allStyles, 0, -2); echo "<p>The resulting string is: <strong>$allStyles</strong></p>\r\n"; } if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) { $insertSQL = sprintf("INSERT INTO daily_budget (rundate, slug, reporter, budgetInfo, notes, `section`, deadline, art_photos sidebar, sBudget) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", GetSQLValueString($_POST['rundate'], "text"), GetSQLValueString($_POST['slug'], "text"), GetSQLValueString($_POST['reporter'], "text"), GetSQLValueString($_POST['budgetInfo'], "text"), GetSQLValueString($_POST['notes'], "text"), GetSQLValueString($_POST['section'], "text"), GetSQLValueString($_POST['deadline'], "text"), GetSQLValueString($_POST['art_photos'], "text"), GetSQLValueString($_POST['sidebar'], "text"), GetSQLValueString($_POST['sBudget'], "text")); mysql_select_db($database_connAdmin, $connAdmin); $Result1 = mysql_query($insertSQL, $connAdmin) or die(mysql_error()); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Budget Record</title> </head> <body> <?php if (isset($error)) { echo '<ul>'; foreach($error as $alert) { echo "<li class='warning'>$alert</li>\n"; } echo '</ul>'; } ?> <form action="<?php echo $editFormAction; ?>" method="POST" name="form1" id="form1"> <table align="center" width="60%" border="2" bgcolor="#FFFFFF"> <tr valign="baseline"> <td width="14%" align="right" nowrap="nowrap"><STRONG>Rundate:</STRONG></td> <td width="86%"> <input type="text" name="rundate" size="30" value="" id="jQueryUICalendar2"/> <script type="text/javascript"> // BeginWebWidget jQuery_UI_Calendar: jQueryUICalendar2 jQuery("#jQueryUICalendar2").datepicker(); // EndWebWidget jQuery_UI_Calendar: jQueryUICalendar2 </script></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><STRONG>Section:</STRONG></td> <td> <select name="section"> <option value=""></option> <option value="A1">A1</option> <option value="Pickup All">Pickup All</option> <option value="Region">Region</option> <option value="Atlantic">Atlantic</option> <option value="Business">Business</option> <option value="Features">Features</option> <option value="Sports">Sports</option> </select> </td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Slug:</strong></td> <td><span id="sprytextfield2"> <input type="text" name="slug" value="" size="32" /> <span class="textfieldRequiredMsg">REQUIRED</span></span><span style="color: #F00; font-weight: bold; font-size: 10px;"></span></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Budget Information:</strong></td> <td><span id="sprytextarea1"> <textarea name="budgetInfo" cols="50" rows="4"></textarea> <span class="textareaRequiredMsg">Required.</span></span><span style="color: #F00; font-weight: bold; font-size: 11px;"></span></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Notes:</strong></td> <td><input type="text" name="notes" value="" size="32" /></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Reporter:</strong></td> <td><span id="sprytextfield3"> <input type="text" name="reporter" value="" size="32" /> <span class="textfieldRequiredMsg">Required.</span></span><span style="color: #F00; font-weight: bold; font-size: 10px;"></span></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Deadline:</strong></td> <td><input type="text" name="deadline" size="30" value="Enter date" id="jQueryUICalendar1"/><script type="text/javascript"> // BeginWebWidget jQuery_UI_Calendar: jQueryUICalendar2 jQuery("#jQueryUICalendar1").datepicker(); // EndWebWidget jQuery_UI_Calendar: jQueryUICalendar2 </script> </td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Artwork:</strong></td> <td><label> <input type="checkbox" name="art_photos[]" value="factbox" id="art_photos_0" /> Factbox</label> <label> <input type="checkbox" name="art_photos[]" value="graphic" id="art_photos_1" /> Graphic</label> <label> <input type="checkbox" name="art_photos[]" value="photo" id="art_photos_2" /> Photo</label> <label> <input type="checkbox" name="art_photos[]" value="video" id="art_photos_3" /> Video</label> <br /></td> </tr> <tr> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"> <strong>Sidebar:</strong></td> <td valign="baseline"><span id="spryradio2"> <label> <input type="radio" name="sidebar" value="y" id="sidebar_0" /> Yes</label> <br /> <label> <input type="radio" name="sidebar" value="n" id="sidebar_1" /> No</label> <br /> <span class="radioRequiredMsg"><strong style="font-size: 11px">REQUIRED.</strong></span></span> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Sidebar Information:</strong></td> <td><input type="text" name="sBudget" value="" size="32" /></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"> </td> <td><input type="submit" value="Insert record" /></td> </tr> </table> <input type="hidden" name="MM_insert" value="form1" /> </form> <p> </p> <h3><a href="/new_budget/admin/manage_budgets.php"><strong>View your budget entry, make changes or delete your budget.</strong></a></h3> <script type="text/javascript"> <!-- jQuery("#jQueryUICalendar1").datepicker(); jQuery("#jQueryUICalendar2").datepicker(); var sprytextfield2 = new Spry.Widget.ValidationTextField("sprytextfield2", "none", {maxChars:15, validateOn:["change"]}); var sprytextarea1 = new Spry.Widget.ValidationTextarea("sprytextarea1", {validateOn:["change"]}); var sprytextfield3 = new Spry.Widget.ValidationTextField("sprytextfield3"); var spryradio2 = new Spry.Widget.ValidationRadio("spryradio2"); //--> </script> </body> </html> Hi All, First time posting here. I've googled the problem, but can't seem to find a response that's the same. All I want to do is have a list of id numbers and for each id number in the array, submit a MySQL query to retrieve information relating to the id number. When I execute the code below however, I end up with only the last item in the array being printed in the echo statement. Any clues? Thanks, Code: [Select] // get array of ids $ids = getIDs($ids); // loop through input list foreach ($ids as &$id) { getVarDetails($id); } function getVarDetails($local) { $con = mysql_connect('localhost:3306', 'root', '********'); if (!$con) { die('Could not connect: ' . mysql_error()); } // set database as Ensembl mysql_select_db("Ensembl", $con); $result = mysql_query("SELECT * FROM variations WHERE name = '$local' LIMIT 1"); $row = mysql_fetch_array($result) while($row = mysql_fetch_array($result)) { echo $row['name'] . " " . $row['id']; echo "<br />"; } // close connection mysql_close($con); } Hello, I'm having trouble inserting data into a MySQL table. The user has a form which is HEIGHT and WIDTH and NUMBER_OF_OBSERVATIONS. All these values are stored in the same table. NUMBER_OF_OBSERVATIONS does what it needs to and inserts its calculated results into the database, as does DATE_TIME. I've been trying for a couple of days to get this done, and I am having no luck in getting it sorted. Any help is greatly appreciated! Generator.php Code: [Select] $WIDTH = $_POST['WIDTH']; $HEIGHT = $_POST['HEIGHT']; $NUMBER_OF_OBSERVATIONS = $_POST['NUMBER_OF_OBSERVATIONS']; $db1 = new Number_Information(); $db1->openDB(); $OBSERVATION_ID = $db1->insert_Observation(); echo "<br /><br />Success. ID: <strong>$OBSERVATION_ID<strong>"; $db1->closeDB(); Number_Information.php Code: [Select] function insert_Observation() { //$Date_Now = datetime(); $sql = "INSERT INTO Observations (DATE_TIME, HEIGHT, WIDTH) VALUES (NOW(), '{$esc_HEIGHT}','{$esc_WIDTH}' )"; $result = mysql_query($sql, $this->conn); if (!$result) { die("SQL Insertion error: " . mysql_error()); } else { return mysql_insert_id($this->conn); } The table name is Observations Again - Any help is greatly appreciated! I have this simple form that registers schools. This year I have decide to upgrade and include a feature that checks if the school is already registered or not based on the imputed name. Here is the code (that is the only way I know how): mysql_connect("", "", "") or die(mysql_error( '' )); mysql_select_db("") or die(mysql_error( '' )); $query = "SELECT * FROM School_Registrations WHERE School_Name= '$_POST[SchoolName]' "; $result = mysql_query($query); if (mysql_numrows($result) > 0) { while($row = mysql_fetch_array($result)) echo" error code here";} else {mysql_query("INSERT INTO `database`.`School_Registrations` (all the variables here);") or die(mysql_error( '' )); echo "Success Code";} I am trying to incorporate this code somewhere into the 'else' statement but I have no luck. I am constantly getting some errors and when I fix one there is one more to take its place. I am lost. The last one I can not fix and I am not sure what it wants from me: Fatal error: Call to undefined function getPage() It works by itself without the if/else statement but not in the code listed above $url = 'http://www.otherpage.com/page.php?'; $url .= 'email='.urlencode($_POST['email']); $result2 = getPage('', $url, '', 15); function getPage($proxy, $url, $header, $timeout) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, $header); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_PROXY, $proxy); curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_REFERER, 'http://azsef.org'); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.8) Gecko/2009032609 Firefox/3.0.8'); $result2['EXE'] = curl_exec($ch); $result2['INF'] = curl_getinfo($ch); $result2['ERR'] = curl_error($ch); curl_close($ch); return $result2; } Can you tell me why doesn't it work? Thanks how do i insert two same values bearing variable into the same row though different column into a database? Insertion was successful but at the end I always end up getin an error for which I was not allowed a redirection...thanx error: Code: [Select] 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 ') VALUES('spaceman12', 'ja')' at line 1 I'm trying to create a script to use PDO prepared statements to enter data from a post form using functions to perform the PDO required statements. But, it's not working. When I execute it, it enters null in all the fields. I'm hoping someone can tell me why this is not working. I think the functions output what PDO is looking for. I'm not sure how to do this otherwise without writing a lot of code like $site_name= $_POST['site_name']; and entering all of that in the PDO statments. It seemed like it made sense to create the statements from the post array. My code is included below and after that is some output I used to monitor what is going on that shows the output of the functions in the script. Am I doing this all wrong. Is another approach that I haven't discovered? Thanks --Kenoli <?php if(isset($_POST['submit'])){ /** Establish DB connection. Not real data, of course. */ $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); /** Remove empty $_POST elements. */ $insert_array = array_filter($_POST); /** Whitelists input to identify columns to which changes are allowed */ $whitelist = array('site_name' =>'', 'site_address' =>'', 'description' =>'', 'surface' =>'', 'tio_contact' =>'', 'site_contact' =>'', 'contact_phone' =>'', 'contact_email' =>'', 'contact_date' =>'', 'comments' =>''); $insert_array = array_intersect_key($insert_array,$whitelist); /************/ /** Create query from $insert_array. */ foreach($insert_array as $key => $value) { $col .= $key . ', '; $val .= ':' .$key . ', '; } /** Remove ', " from end of each array. */ /* For use with update actions to prevent deleting data from fields that contain data. */ $col = substr_replace($col ,"",-2); $val = substr_replace($val ,"",-2); $sql = "INSERT INTO Sites ($col) VALUES ($val)"; /* The result is: INSERT INTO Sites (site_name, site_address, description, contact_phone) VALUES (:site_name, :site_address, :description, :contact_phone)*/ /************/ /** Prepared statement functions */ $stmt = $conn->prepare($sql); foreach($insert_array as $key => $value) { $param = ':' . $key; $stmt->bindParam($param, $$value); echo '$' . "stmt->bindParam($param, $$key)<br>"; // Monitor output } foreach($insert_array as $key => $value) { $$key = $value; echo "$$key = $value<br>"; // Monitor output } $stmt->execute(); // Execute insert ?> The result with dummy data: $insert_array
(
$stmt->bindParam(:site_name, $site_name)
$site_name = asdfasdf Everything looks right but NULLs are inserted in all fields.
$username = $_POST['uid']; $email = $_POST['mail']; $password = $_POST['pwd']; $passwordRepeat = $_POST['pwd-repeat']; $date = $_POST['date2']; $stream = $_POST['relationship']; $sql1 = "INSERT INTO users (uidUsers, emailUsers, pwdUsers, relationship) VALUES (?, ?, ?, ?);"; $sql2 = "INSERT INTO Family1 (username, application_filed, relationship) VALUES (?, ?, ?);"; $sql3 = "INSERT INTO Family2 (username, application_filed, relationship) VALUES (?, ?, ?);"; mysqli_query($sql1, $conn); mysqli_query($sql2, $conn); mysqli_query($sql3, $conn); $stmt = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($stmt, $sql2)) { header("Location: ../signup.php?error=sqlerror"); exit(); } else { mysqli_stmt_bind_param($stmt, "sss", $username, $date, $stream); $result = mysqli_stmt_get_result($stmt); if ($row = mysqli_fetch_assoc($result)) ($username==$_SESSION['uid'] and $stream =='nursing'); mysqli_stmt_execute($stmt); } if (!mysqli_stmt_prepare($stmt, $sql3)) { header("Location: ../signup.php?error=sqlerror"); exit(); } else { mysqli_stmt_bind_param($stmt, "sss", $username, $date, $stream); $result = mysqli_stmt_get_result($stmt); if ($row = mysqli_fetch_assoc($result)) ($username==$_SESSION['uid'] and $stream =='doctoral'); mysqli_stmt_execute($stmt); } if (!mysqli_stmt_prepare($stmt, $sql1)) { header("Location: ../signup.php?error=sqlerror"); exit(); } if (!mysqli_stmt_prepare($stmt, $sql1)) { header("Location: ../signup.php?error=sqlerror"); exit(); } else { $hashedPwd = password_hash($password, PASSWORD_DEFAULT); mysqli_stmt_bind_param($stmt, "ssss", $username, $email, $hashedPwd, $stream); mysqli_stmt_execute($stmt); header("Location: ../signup.php?signup=success"); exit(); I was wondering if someone could point me in the right direction. I have this code. They idea I had behind it is to insert values into different tables depending on variables being passed. So when user fills out a form and selects $stream="nursing" I want results to go to table 'users' and 'Family1', but not 'Family2' table. and if user selects $stream='doctoral' results should go to table 'users' and 'Family2', and not go to 'Family1' But with my query I get results go to both table and also users table. And there is no restriction to what users selects, variable $stream being passed no matter what it is. Is this the wrong way to go here? Did I completely mess up the logic? Hello everyone, I am having major issues trying to figure this one out. So here is the code.... $useranswer= ( $_POST["Text1"]); $query = "SELECT Answer FROM images_guess WHERE id=16"; $result = mysql_query($query); while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { echo "Answer :{$row["Answer"]} <br>"; echo "User Answer:$useranswer <br>"; } $result2 = $result. " "; $useranswer2 = $useranswer . " "; if ($result2==$useranswer2) echo "right"; else echo "wrong"; ?> Basically, I am taking whatever was put into "Text1" and finding out if it matches what was in the Answer row in my table. The two variables I used, $result and $useranswer are both working because they do print out on the next page. The problem is the If/else statement is not working with them. They are both text if that helps. Any advice would help a ton, i'm at a loss. Thanks! Any idea why this wont work? Think it has something to with how i'm passing the variables? $latinsk =$row['latinsk']; $ID =$row['id']; //-display the result of the array echo "<ul>\n"; echo "<li>" . "<p style='font-family:verdana;font-size:150%;'><a href='javascript:void()' onclick='window.location.href='search.php?id= '" . $ID . "'&latinsk= '" . $latinsk . "''; parent.scrollTo(0,0); return false'> " .$latinsk . " </a></li>\n</p>"; echo "</ul>"; Hi, I have this code to retrieve currency exchange rates from the ECB: Code: [Select] <?php $XMLContent=file("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"); //the file is updated daily between 2.15 p.m. and 3.00 p.m. CET foreach($XMLContent as $line){ if(preg_match("/currency='([[:alpha:]]+)'/",$line,$currencyCode)){ if(preg_match("/rate='([[:graph:]]+)'/",$line,$rate)){ //Output the value of 1EUR for a currency code echo'1€='.$rate[1].' '.$currencyCode[1].'<br/>'; //-------------------------------------------------- //Here you can add your code for inserting //$rate[1] and $currencyCode[1] into your database //-------------------------------------------------- } } } ?> I have a DB with 2 fields, one is for the exchange rate (rate) and the other for thecurrency name (currencyCode). My problem is that I don't know how to insert the $rate[1] and $currencyCode[1] in my DB. Thanks for your help. Hi, Does anyone have any idea how to insert an entire php or html pages into mysql once the page has being created with php? E.g. np1.php <form action="np2.php" method="post"> Name of New Page: <input type="text" name="newpage_name" /> <input type="submit" /> </form> np2.php <?php $newpage_name = $_POST[ 'newpage_name' ]; $newpage_initial = "Input Contents Here."; //echo $editor_data; $newpage_file = "test/" . $newpage_name . ".php"; $newpage_save = fopen($newpage_file, 'w'); fwrite($newpage_save, $newpage_initial); fclose($newpage_save); ?> I have managed to create a new file with php but I also want it when I click on the submit button, it will also auto save that new php file or html file into mysql. Regards Jas Thanks for reading my post, Can someone point me to the right direction here; Am trying to insert a record in a text area field into PHP/MYSQl. This time around, I am reading what the user entered into the textarea before inserting. Take a look at this: TEXTAREA -> row 1: BOY row 2: GIRL Can I make it two rows in my database as opposed to one? I don't have a problem inserting, just how to insert as multiple if there are two rows. Thanks in advance Hi guys I am using the code found here http://www.elated.com/articles/cms-in-an-afternoon-php-mysql/ with some alterations to try and insert data in a database via a php form, i have completed the example shown on that site and it works perfect, but I am now trying to adjust the code so that i have a user and admin section, but the form will not submit to the database. Here is the for my form, page know as editArticles: Code: [Select] <?php include "templates/include/header.php" ?> <div id="userHeader"> <h2><spanH1>Advertise!</spanH1> Place an advert for your book</h2> <p>You are logged in as <b><?php echo htmlspecialchars( $_SESSION['username']) ?></b>. <a href="user.php?action=logout"?>Log out</a></p> </div> <h1><?php echo $results['pageTitle']?></h1> <form action="user.php?action=newArticle" method="post"> <input type="hidden" name="articleId" value="<?php echo $results['article']->id ?>"/> <?php if ( isset( $results['errorMessage'] ) ) { ?> <div class="errorMessage"><?php echo $results['errorMessage'] ?></div> <?php } ?> <ul> <li> <label for="booktitle">Book Title</label> <input type="text" name="booktitle" id="booktitle" placeholder="Title of the book" required autofocus maxlength="100" value="<?php echo htmlspecialchars( $results['article']->booktitle )?>" /> </li> <li> <label for="author">Book Author</label> <input type="text" name="author" id="author" placeholder="Author of the book" required autofocus maxlength="50" value="<?php echo htmlspecialchars( $results['article']->author )?>" /> </li> <li> <label for="edition">Edition</label> <input type="text" name="edition" id="edition" placeholder="Edition" required autofocus maxlength="2" value="<?php echo ( $results['article']->edition )?>" /> </li> <li> <label for="category">Category</label> <input type="text" name="category" id="category" placeholder="Book Category E.G Buisness" required autofocus maxlength="30" value="<?php echo htmlspecialchars( $results['article']->category )?>" /> </li> <li> <label for="module">Module</label> <input type="text" name="module" id="module" placeholder="Module" required autofocus maxlength="30" value="<?php echo ( $results['article']->module )?>" /> </li> <li> <label for="price">Price</label> <input type="text" name="price" id="price" placeholder="Price" required autofocus maxlength="30" value="<?php echo ( $results['article']->price )?>" /> </li> <li> <label for="condition">Condition</label> <input type="text" name="condition" id="condition" placeholder="condition" required autofocus maxlength="30" value="<?php echo ( $results['article']->condition )?>" /> </li> <li> <label for="description">Description</label> <textarea name="description" id="description" placeholder="Description of the book including condition and associated modules" required maxlength="500" style="height: 15em;"> <?php echo htmlspecialchars( $results['article']->description )?></textarea> </li> <li> <label for="Image">Image</label> <input type="file" name="Image" id="Image" /> </li> <li> <label for="pdate">Sale Date</label> <input type="date" name="pdate" id="pdate" placeholder="YYYY-MM-DD" required maxlength="10" value="<?php echo $results['article']->pdate ? date( "Y-m-d", $results['article']->pdate ) : "" ?>" /> </li> </ul> <div class="buttons"> <input type="submit" name="saveChanges" value="Save Changes" /> <input type="submit" formnovalidate name="cancel" value="Cancel" /> </div> </form> <?php if ( $results['article']->id ) { ?> <p><a href="admin.php?action=deleteArticle&articleId=<?php echo $results['article']->id ?>" onclick="return confirm('Delete This Article?')">Delete This Article</a></p> <?php } ?> <?php include "templates/include/footer.php" ?> This is the form for the php, as you can see the form action is "new article" This is the code for the action new article Code: [Select] function newArticle() { $results = array(); $results['pageTitle'] = "New Article"; $results['formAction'] = "newArticle"; if ( isset( $_POST['saveChanges'] ) ) { // User has posted the article edit form: save the new article $article = new Article; $article->storeFormValues( $_POST ); $article->insert(); header( "Location: admin.php?status=changesSaved" ); } elseif ( isset( $_POST['cancel'] ) ) { // User has cancelled their edits: return to the article list header( "Location: admin.php" ); } else { // User has not posted the article edit form yet: display the form $results['article'] = new Article; require( TEMPLATE_PATH . "/admin/editArticle.php" ); } } As you can see the template is set to the above form page editArticle Below is the code for the class "article" which contains the insert function and other functions such as construct, the storeFormValues which can is used in the "newArticle" function, and of course the insert function Code: [Select] class Article { public $id = null; public $booktitle = null; public $author = null; public $edition = null; public $category = null; public $module = null; public $price = null; public $condition = null; public $description = null; public $image = null; public $pdate = null; public function __construct( $data=array() ) { if ( isset( $data['id'] ) ) $this->id = (int) $data['id']; if ( isset( $data['booktitle'] ) ) $this->booktitle = preg_replace ( "/[^\.\,\-\_\'\"\@\?\!\:\$ a-zA-Z0-9()]/", "", $data['booktitle'] ); if ( isset( $data['author'] ) ) $this->author = preg_replace ( "/[^\.\,\-\_\'\"\@\?\!\:\$ a-zA-Z0-9()]/", "", $data['author'] ); if ( isset( $data['edition'] ) ) $this->edition = $data['edition']; if ( isset( $data['category'] ) ) $this->category = $data['category']; if ( isset( $data['module'] ) ) $this->module = $data['module']; if ( isset( $data['price'] ) ) $this->price =(int) $data['price']; if ( isset( $data['condition'] ) ) $this->condition = $data['condition']; if ( isset( $data['description'] ) ) $this->description = $data['description']; if ( isset( $data['image'] ) ) $this->image = $data['image']; if ( isset( $data['pdate'] ) ) $this->pdate = (int) $data['pdate']; } public function storeFormValues ( $params ) { // Store all the parameters $this->__construct( $params ); // Parse and store the publication date if ( isset($params['pdate']) ) { $sdate = explode ( '-', $params['pdate'] ); if ( count($pdate) == 3 ) { list ( $y, $m, $d ) = $pdate; $this->pdate = mktime ( 0, 0, 0, $m, $d, $y ); } } } public function insert() { // Does the Article object already have an ID? if ( !is_null( $this->id ) ) trigger_error ( "Article::insert(): Attempt to insert an Article object that already has its ID property set (to $this->id).", E_USER_ERROR ); // Insert the Article $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD ); $sql = "INSERT INTO books ( booktitle, author, edition, category, module, price, condition, description, image, pdate ) VALUES ( :booktitle, :author, :edition, :category, :module, :price, :condition, :description, :image, FROM_UNIXTIME(:pdate) )"; $st = $conn->prepare ( $sql ); $st->bindValue( ":booktitle", $this->booktitle, PDO::PARAM_STR ); $st->bindValue( ":author", $this->author, PDO::PARAM_STR ); $st->bindValue( ":edition", $this->edition, PDO::PARAM_STR ); $st->bindValue( ":category", $this->category, PDO::PARAM_STR ); $st->bindValue( ":module", $this->module, PDO::PARAM_STR ); $st->bindValue( ":price", $this->price, PDO::PARAM_INT ); $st->bindValue( ":condition", $this->condition, PDO::PARAM_STR ); $st->bindValue( ":description", $this->description, PDO::PARAM_STR ); $st->bindValue( ":image", $this->image, PDO::PARAM_STR ); $st->bindValue( ":pdate", $this->pdate, PDO::PARAM_INT ); $st->execute(); $this->id = $conn->lastInsertId(); $conn = null; } I would truly appreciate if someone is able to figure out what is going wrong, btw i dont get any errors when i click the save it takes mw to the next page and show a message i have set saying the changes have been saved but it doesnt actually save to me database. If you have any questions or i need to explain more please let me know Thanks in advance Hello All, First, I'm new to php and I have spent a lot of time searching forums and google for the answer to my question with no luck, so if it's a topic already covered, PLEASE reply with a link or point me in the right direction. OK, I have a form that let's users upload multiple images. The upload portion works fine. What I can't figure out how to do is put the image name of each file that gets uploaded all into the same table record. I also need each file name to be put into it's own column in the table. For example, file1, file2 and file3 will get dumped into the same record and into it's respective column (uploaded_image1, uploaded_image2, uploaded_image3). I've included the working upload code and the code that inserts some of the information into the database (just not the image names). Code: [Select] echo "<textarea name=challenge rows=15 cols=60> </textarea><br/><br/>" echo "<textarea name=insight rows=15 cols=60> </textarea><br/><br/>" for($i=1; $i<=$max_no_img; $i++){ echo "Image $i <input type=file name='image[]' ><br/>"; } echo "<input type=submit value=Submit>"; Code: [Select] // Connect to DB $host = 'xxx'; $user = 'xxx'; $pass = 'xxx'; $db = 'xxx'; mysql_connect($host,$user,$pass) or die(mysql_error()); mysql_select_db($db) or die(mysql_error()); // Post Variables $challenge = $_POST['challenge']; $insight = $_POST['insight']; $filename=serialize($_POST['filename']); // Upload Images while(list($key,$value) = each($_FILES[image][name])) { if(!empty($value)) { $filename = $value; $add = "upimage/$filename"; copy($_FILES[image][tmp_name][$key], $add); chmod("$add",0777); } } // Insert into database $query = "INSERT INTO table ( challenge, insight, uploaded_image1, uploaded_image2, uploaded_image3,)". "values ( '$challenge', '$insight', '$filename' '$filename2' '$filename3')"; mysql_query($query) or die('Error, query failed : ' . mysql_error()); I know just enough about php that the reason the above wont work, is because $filename2 and $filename3 haven't been given a value. Unfortunately, I have no idea how to separate that information in the array. If anyone can point me in the right direction I'd be forever grateful! Thanks, Gary Hi guys, This is my first time to insert PDF into MySQL BLOB. Below is my form that i used Code: [Select] <?php <form enctype="multipart/form-data" name="frmUploadFile" action="ulf-exec.php" method="post"> <select name="title" id="title"> <option>xxx</option> <option>yyy</option> <option>zzz</option> </select> </label> <input name="des" type="text" class="dropdownlists1" id="des"></td> <input name="fileUpload" type="file" class="dropdownlists1" id="fileUpload" size="20" border=""></td> <input type="submit" name="button" id="button" value="Submit"> </form> ?> I have prepared my database based on the required but decided to test with echo just to confirm there's no issue with the code The action="ulf-exec.php" : Code: [Select] <?php function clean($str) { $str = @trim($str); if(get_magic_quotes_gpc()) { $str = stripslashes($str); } return mysql_real_escape_string($str); } //Sanitize the POST values $title = clean($_POST['title']); $des = clean($_POST['des']); $fileUpload = $_POST['fileUpload']; if(empty($des) || $fileUpload == "none") die("You must enter both a description and file"); $fileHandle = fopen($fileUpload, "r"); $fileContent = fread($fileHandle, $fileUpload_size); $fileContent = addslashes($fileContent); $date = date('d').'-'.date('m').'-'.date('y'); $time = date('h').':'.date('i').':'.date('s'); echo "<h1>File Uploaded</h1>"; echo "The details of the uploaded file are shown below:<br><br>"; echo "<b>File name:</b> $fileUpload_name <br>"; echo "<b>File type:</b> $fileUpload_type <br>"; echo "<b>File size:</b> $fileUpload_size <br>"; echo "<b>Uploaded to:</b> $fileUpload <br><br>"; echo "<a href='uploadfile.php'>Add Another File</a>"; ?> This is the error: Code: [Select] Warning: fopen() [function.fopen]: Filename cannot be empty in /ulf-exec.php on line 30 Warning: fread(): supplied argument is not a valid stream resource in ulf-exec.php on line 31 Hello I have a text list that looks like this: Code: [Select] ACACIA-Acacia spp.-Australia AMANITAS-Amanita muscaria-Siberia AYAHUASCA-Yage-Amazon Basin ... continues... i am trying to create a script that if i placed that text like that in a textarea and submitted the form it would explode each line one at a time by the "-" and add it into a mysql database (COMMON_NAME, GENUS_SPECIES, NATIVE_TO) I dont want to have to submit these one at a time and im sure this is very simple to do just im not understanding how to explode each line. maybe a code like; 1. counts the total number of lines and places it in a variable called lines 2. do while $lines > 0 3. for each $line explode by "-" 4. insert each piece of the exploded line into the database as (COMMON_NAME, GENUS_SPECIES, NATIVE_TO) as piece 0,1, & 2 5. after inserted subtract 1 from $lines or something similar to that effect. any help is greatly appreciated1 |