PHP - Creating Form In Php To Insert Table In Mysql Db
Need a little help with this code. I'm running Apache 2.21 / PHP 5.3.5 on Windows. This is a V6 application. I am running Windows 7. I am new, and trying to learn. What am I doing wrong in line 8 with the 'if' statement? The idea is to create a table in mySQL using a form interface.
Thank you in advance. Parse error: syntax error, unexpected '{' in C:\website\do_createtable.php on line 8 <? $db_name="booster"; $connection=mysql("localhost", "user", "password") or die (mysql_error()); $db=mysql_select_db($db_name, $connection) or die (mysql_error()); $sql="CREATE TABLE $_POST[table_name] ("; for ($i=0; $i < count($_POST[field_name]); $i++) { $sql .= $_POST[field_name][$i]." ".$_POST[field_type][$i]; if ($_POST[field_length][$i] != "" { $sql .= " (".$_POST[field_length][$i]."),"; } else { $sql .= ","; } } $sql=substr($sql,0,-1); $sql .= ")"; Similar TutorialsWindows 7, Apache 2.2.21 / PHP 5.3.5. What does the below error mean? I am new and fighting through this particular piece of code. Thank you in advance for your help. Warning: mysql() expects parameter 3 to be resource, string given in C:\website\do_createtable.php on line 3 <? $db_name="booster"; $connection=mysql("localhost", "USERNAME", "PASSWORD") or die (mysql_error()); $db=mysql_select_db($db_name, $connection) or die (mysql_error()); $sql="CREATE TABLE $_POST[table_name] ("; for ($i=0; $i < count($_POST[field_name]); $i++) { $sql .= $_POST[field_name][$i]." ".$_POST[field_type][$i]; if ($_POST[field_length][$i] != "") { $sql .= " (".$_POST[field_length][$i]."),"; } else { $sql .= ","; } } $sql=substr($sql,0,-1); $sql .= ")"; $result=mysql_query($sql,$connection) or die (mysql_error()); if ($result) { $msg="<P>".$_POST[table_name]." has been created!</P>"; } ?> <HTML> <HEAD> <TITLE>Create a Database Table: Step 3</TITLE> </HEAD> <BODY> <h1>Adding table to <? echo "$db_name"; ?>....</h1> <? echo "$msg"; ?> </BODY> </HTML> hello i have a db with name which populates a form dropdown list there are various variables like this in the form. the user selects their choices and then submits the form to a new db table at the moment it does not capture the dropdown data to the insert sql help please here is the code: =============================== <?php include ('connect.php'); // Insert any new image into database if(isset($_POST['xsubmit']) && $_FILES['imagefile']['name'] != "") { $fileName = $_FILES['imagefile']['name']; $fileSize = $_FILES['imagefile']['size']; $fileType = $_FILES['imagefile']['type']; $content = addslashes (file_get_contents($_FILES['imagefile']['tmp_name'])); $jeweltype = $_POST['jeweltype']; $jewelsize = $_POST['jewelsize_in']; $jewelcolour = $_POST['jewelcolour_in']; $jewelmaterial = $_POST['jewelmaterial_in']; $jewelgender = $_POST['jewelgender_in']; if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); } // Checking file size if ($fileSize < 150000) { mysql_query ("INSERT into jewel_images (name,size,type,content,jeweltype,jewelsize,jewelcolour,jewelmaterial,jewelgender) " . "values ('$fileName','$fileSize','$fileType','$content','$jeweltype','$jewelsize','$jewelcolour','$jewelmaterial','$jewelgender')"); } else { $err = "The Image file to too large!"; } } // Find out about latest image $gotten = mysql_query("select * from jewel_images order by row_id desc"); $row = mysql_fetch_assoc($gotten); $bytes = $row['content']; // If this is the image request, send out the image if ($_REQUEST['pic'] == 1) { header("Content-type: $row[type];"); print $bytes; } ?> <html> <head> <title>Upload an image to a database</title> </head> <body> <font color="#FF3333"><?php echo $err ?></font> <table> <form name="Upload" enctype="multipart/form-data" method="post"> <tr> <td>Upload <input type="file" name="imagefile"><br /> Jewelery Type: <select> <?php $sql="SELECT jeweltype FROM jeweltypes"; $result =mysql_query($sql); while ($data=mysql_fetch_assoc($result)){ ?> <option value ="jeweltype" ><?php echo $data['jeweltype'] ?></option> <?php } ?> </select> <br /> Jewelery Size: <select> <?php $sql="SELECT jewelsize FROM jewelsizes"; $result =mysql_query($sql); while ($data=mysql_fetch_assoc($result)){ ?> <option value ="jewelsize" ><?php echo $data['jewelsize'] ?></option> <?php } ?> </select> <br /> Jewelery Colour: <select> <?php $sql="SELECT jewelcolour FROM jewelcolours"; $result =mysql_query($sql); while ($data=mysql_fetch_assoc($result)){ ?> <option value ="jewelcolour_in" ><?php echo $data['jewelcolour'] ?></option> <?php } ?> </select> <br /> Jewelery Material: <select> <?php $sql="SELECT jewelmaterial FROM jewelmaterials"; $result =mysql_query($sql); while ($data=mysql_fetch_assoc($result)){ ?> <option value ="jewelmaterial_in" ><?php echo $data['jewelmaterial'] ?></option> <?php } ?> </select> <br /> Jewelery Gender: <select> <?php $sql="SELECT jewelgender FROM jewelgenders"; $result =mysql_query($sql); while ($data=mysql_fetch_assoc($result)){ ?> <option value ="jewelgender_in" ><?php echo $data['jewelgender'] ?></option> <?php } ?> </select> <br /> <input type="submit" name="xsubmit" value="Upload"> </td> </tr> <tr> <td>Latest Image</td> </tr> <tr> <td><img src="?pic=1"></td> </tr> </form> </table> </body> </html> 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 Im trying to insert some values automatically into a table once the form loads, but Im getting an error. Here is the code Code: [Select] <?php $aid = $_GET['aid']; $sd = $_GET['sd']; ?> <style> #message {margin:20px; padding:20px; display:block; background:#cccccc; color:#cc0000;} </style> <div id="message">Your notification has been submitted.</div> <div style="text-align:center "> <?php $connection = mysql_connect("localhost", "username", "password"); mysql_select_db("articles", $connection); $query="INSERT INTO broken_links (articleid, article) VALUES ('$aid', '$sp')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "Submitted"; mysql_close($con) ?> <table border="0" cellpadding="3" cellspacing="3" style="margin:0 auto;" > <input type="submit" id="Login" value=" Thank you. Please press to close " onclick="tb_remove()"></td> </tr> </table> </div> Any help will be appreciated HI. Im new to database. I didnt know how to use bridge table. In my bridge table i have SubjectID and studentID, PK from student table and subject table. In my subject table have SubjectID, SubjectName and SubjectLecturer while in my student table have studentID,,studentName,IC,studentFac,studentPhone, studentEmail,pswd,studentAddress. I didnt know where is the wrong part because when i click my form which is enroll button, this enroll page blank Can someone check my coding ? Help ?
<!DOCTYPE HTML> <html> <head> <?php error_reporting(0); session_start(); if (!isset($_SESSION['studentID'])) { $_SESSION['studentID'] = $_POST['studentID']; $_SESSION['pswd'] = $_POST['pswd']; } include("connect.php"); $sql = "SELECT * FROM student WHERE studentID='".$_SESSION['studentID']."' AND pswd='".$_SESSION['pswd']."'"; $result = mysql_query($sql); $row = mysql_num_rows($result); if ($row == 0) { echo "Login fail Try again <a href='http://bytes.com/'>here</a>"; ?> <meta http-equiv="refresh" content="0;userlogin.php" /> <?php } else { $row = mysql_fetch_assoc($result); } ?> <meta charset="UTF-8"> <title>E-Education portal</title> <link href="http://bytes.com/style.css" rel="stylesheet" type="text/css"> </head> <body> <div id="header"></ div> <?php if(isset($_POST["submit"])) { session_start(); include("connect.php"); $SubjectID = $_POST['SubjectID']; $SubjectName = $_POST['SubjectName']; $SubjectLecturer = $_POST['SubjectLecturer']; $Subject= "SELECT SubjectID FROM Subject WHERE SubjectID='$SubjectID'"; $queryssubject=mysql_query($subject) or die(mysql_error); $record=mysql_num_rows($querysubject); if($record==1) { header ('Location: studentSubject.php'); } else if($record<1) { if(substr($subjectID)) { $insertIntoSubject= "INSERT INTO Subject ('SubjectID', 'SubjectName', 'SubjectLecturer') VALUES ('$SubjectID','$SubjectName','$SubjectLecturer')"; $result1=mysql_query($insertIntoSubject) or die(mysql_error()); $insertIntobridge="INSERT INTO `bridge`(`SubjectID`, `studentID`) VALUES ('$SubjectID', '$studentID')"; $result2=mysql_query($insertIntobridge)or die(mysql_error()); $insertIntostudent="INSERT INTO student (`studentID`, `studentName`, `IC`, `studentFac`, `studentPhone`, `studentEmail`, `pswd`, `studentAddress') VALUES ('$studentID', '$studentName', '$IC', '$studentFac', '$studentPhone', '$studentEmail', 'abc123', '$studentAddress')"; $result3=mysql_query($insertIntostudent)or die(mysql_error()); if ($result1 && $result2 && $result3) { header ('Location: studentSubject.php'); } } else echo 'insert error'; } else { echo "<script type='text/javascript'> alert('Data Updated!') location.href='homestudent.php' </script>"; } mysql_close($conn); } ?> Hey yall! I'm working on a new site idea and I've run across a problem that I know is simple enough but I'm stumped. It's in the signup form What I want to do is insert the new user into the 'Login' table and get the user id that was just created and use that to create a table with the user id in the name. Here is what I have: // now we insert user into 'Login' table mysql_real_escape_string($insert = "INSERT INTO `Login` (`UID`, `pass`, `HR`, `mail`, `FullName`) VALUES ('{$_POST['username']}', '{$_POST['pass']}', '{$_POST['pass2']}', '{$_POST['e-mail']}', '{$_POST['FullName']}')"); mysql_query($insert) or die( 'Query string: ' . $insert . '<br />Produced an error: ' . mysql_error() . '<br />' ); $error="Thank you, you have been registered."; setcookie('Errors', $error, time()+20); // Get user ID mysql_real_escape_string($checkID = "SELECT * FROM Login WHERE `mail` = '{$_POST['e-mail']}'"); while ($checkIDdata = mysql_fetch_assoc($checkID)) { $userID = $checkIDdata; // now we create table 'Transactions" for the user mysql_real_escape_string($create = "CREATE TABLE `financewatsonn`.`Transactions_{$userID}` ( `ID` INT( 20 ) NOT NULL AUTO_INCREMENT COMMENT 'Transaction ID', `name` VARCHAR( 50 ) NOT NULL COMMENT 'Name/Location', `amount` VARCHAR( 50 ) NOT NULL COMMENT 'Amount', `date` VARCHAR( 50 ) NOT NULL COMMENT 'Date', `category` VARCHAR( 50 ) DEFAULT NULL COMMENT 'Category', `delete` INT( 1 ) NOT NULL DEFAULT '0', UNIQUE KEY `ID` ( `ID` ) ) ENGINE = MYISAM DEFAULT CHARSET = utf8 COMMENT = 'User ID {$userID}'"); mysql_query($create) or die( 'Query string: ' . $create . '<br />Produced an error: ' . mysql_error() . '<br />' ); } I know in 'Get user ID' that I need to get the ID but I'm not sure how to get that information. i get the error Quote Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource at 166 which is the while line under Get user ID Hi to All, I am performing calculation which i echo it in the input form to insert it to DB table The calculation works fine when i submit the form but the it does not correct calculation to the DB. it seems that the isert to database is done before the calculation and I can't figure a way around it. Because i'm submitting to the same page, the calculation populate in the input form correctly but it insert Zero to the database table instead of correct calculation populated in the input field to DB table You could see from the line 114 to 116 that, i'm performing some calculations and echo it at line 128 and line 128 in the input form value field. Please any help on how to do this...All the function in the code is in another file and it works fine...so the only program is that the calculated value is not inserted as expected Here is the code <?php include 'core/initForMainLogPage.php'; if(isset($_GET['empId']) && !empty($_GET['empId'])){ //delete employee here $empId=$_GET['empId']; grabEmpId($empId); } ?> <?php if(logged_in()){ $data=user_dataManager('username'); $usernameData=$data['username']; }else{ header('Location: index.php'); } ?> <?php include 'includes/adminHeadAll.php';?> <header> <?php include 'includes/managerMenu.php';?> </header> <div class="container"> <br/> <h3>Pay Employee</h3> <?php $error=array(); $errorAll=''; $leave=""; if(isset($_POST['empId']) && isset($_POST['name']) && isset($_POST['date']) && isset($_POST['basicSalary']) && isset($_POST['leave']) && isset($_POST['salaryPerDay']) && isset($_POST['leaveDeduct']) && isset($_POST['netSalary'])){ $empId=htmlentities(mysql_real_escape_string($_POST['empId'])); $name=htmlentities(mysql_real_escape_string($_POST['name'])); $date=htmlentities(mysql_real_escape_string($_POST['date'])); $basicSalary=htmlentities(mysql_real_escape_string($_POST['basicSalary'])); $leave=htmlentities(mysql_real_escape_string($_POST['leave'])); $salaryPerDay=htmlentities(mysql_real_escape_string($_POST['salaryPerDay'])); $leaveDeduct=htmlentities(mysql_real_escape_string($_POST['leaveDeduct'])); $netSalary=htmlentities(mysql_real_escape_string($_POST['netSalary'])); //checking for the validity of data entered if(empty($leave) || empty($date)){ $error[]='Pleave leave or date field is empty.'; }else{ if(preg_match('/[0-9]/',$leave)==false){ $error[]='Leave should only contain numbers'; } if(empId($empId)===false){ $error[]="This employee is not recoganize by the system and can not be paid,he may need to register first."; } } if(!empty($error)){ $errorAll= '<div class="error"><ul><li>'.implode('</li><li>',$error).'</li></ul></div>'; }else{ //this funciton insert into database payrollData($name,$empId,$date,$basicSalary,$leave,$salaryPerDay,$leaveDeduct,$netSalary); echo '<p class="pa">Payment made successfully. <a href="employees-salary-report.php">See Payment Records</a></p>'; } }//end isset ?> <div class="tableWrap"> <form action="" method="post" > <div class="styletable"><table cellpadding="" cellspacing="" border="0"> <?php $query=mysql_query("SELECT empId,name,level,company.compId,company.levelOne,company.levelTwo, company.levelThree,company.levelFour,company.levelFive FROM employee JOIN company ON company.compId=1 WHERE empId='$empId' LIMIT 1"); while($row=mysql_fetch_array($query)){ $empId=$row['empId']; $name=$row['name']; $levelEmp=$row['level']; $levelOne=$row['levelOne']; $levelTwo=$row['levelTwo']; $levelThree=$row['levelThree']; $levelFour=$row['levelFour']; $levelFive=$row['levelFive']; if($levelEmp==1){ $levelPay=$levelOne; }elseif($levelEmp==2){ $levelPay=$levelTwo; }elseif($levelEmp==3){ $levelPay=$levelThree; }elseif($levelEmp==4){ $levelPay=$levelFour; }elseif($levelEmp==5){ $levelPay=$levelFive; } //making calculations here $basicSalary=$levelPay * 30; $leaveDeduct=$leave * $levelPay; $netSalary=$basicSalary - $leaveDeduct; } ?> <tr><td>Employee ID: </td><td><input type="text" name="empId" readonly="readonly" value="<?php if(isset($empId)){echo $empId;}?>"></td></tr> <tr><td>Employee: </td><td><input type="text" name="name" readonly="readonly" value="<?php if(isset($name)){ echo $name;}?>"></td></tr> <tr><td>Date: </td><td><input type="text" id="Date" class="picker" name="date"></td></tr> <tr><td> Basic Salary: </td><td><input type="text" name="basicSalary" readonly="readonly" value="<?php echo $basicSalary;?>"></td></tr> <tr><td> No. Of Absent: </td><td><input type="text" name="leave" class="input" value=""></td></tr> <tr><td> Salary Per Day:</td><td><input type="text" name="salaryPerDay" readonly="readonly" value="<?php echo $levelPay;?>"></td></tr> <tr><td> Deduction For Absentee:</td><td><input type="text" name="leaveDeduct" readonly="readonly" value="<?php echo $leaveDeduct;?>"></td></tr> <tr><td> Net Salary:</td><td><input type="text" name="netSalary" readonly="readonly" value="<?php echo $netSalary;?>"></td></tr> <tr><td> </td><td><input type="submit" value="Submit Pay" class="submit" name="pay"></td></tr> </table></div> </form> <?php ?> </div> <br /> <?php echo $errorAll; ?> <p>Manage the monthly salary details of your employee along with the allowances, deductions, etc. by just entering their leave</p> </div> <?php include 'includes/footerAll.php';?> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/jquery-ui.js"></script> <script type="text/javascript" src="js/ui.js"></script> </body> </html> What gets put in for the values is my problem. I have tried every way I can think of but I get errors in the code or I don't get the row inserted. Can anyone give me a code sample using $ variables, preferably a multi-line list? I would have to fix up my code to show you what I am trying as it is in between tries now. I have to be doing something wrong and may have to put together a simple test script but a working example would be better. Everything I look at on the web shows "xxxxx xxxx" examples not $variables. Thanks in advance. How can i use single quote for values? $qry='insert into tablename values('a','b');'; Hello guys, im using this code atm and it's working, but the new rows created are put in the end of the table. I want them to stack up from the beginning pushing older rows down. What should i do to make that work? <?php $con = mysql_connect("localhost","*****","*******"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("ananaz_se", $con); $sql="INSERT INTO stuff (adult, namn, url) VALUES ('$_POST[adult]','$_POST[namn]','$_POST[url]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 row added"; mysql_close($con) ?> Hi, I'm a researcher (and complete coding noob), and am planning a longitudinal study that requires e-mail follow-up with subjects taking an initial survey. For purposes of ethics/anonymity due to sensitive survey data, I'd like the acquired e-mails to be saved uncoupled from the survey responses; this is simple to deal with, and I use a basic PHP e-mail form, which injects the email address in a table in MySQL in a different server than the one used for the survey. The issue is that the e-mails are saved in the MySQL database in order of injection, thus it is still theoretically possible for me to link the e-mails back to the survey responses (which have a time stamp that I cannot remove). Ideally I would like not to be able (at all) to link the e-mails to the survey responses, and one way to do that (since I don't save the e-mail injection timestamps in MySQL) might be to have the e-mails saved in MySQL in a random order. Not sure if this is possible, and not even sure if this would be via PHP or MySQL side of things. The server is on godaddy and uses Starfield interface for MySQL but I cannot find an option for random insert/saving of table items (emails). They are saved in order of injection. Any solution for this? Thanks, Hi,
I created a form that inserts first - last name, address, and email address into a mysql databse table.
The record inserts correctly - No problems here.
The problem is I only want to insert the data if the email and address doesn't exist.
I set it up for just the email right now to try to get this to work but have failed.
When the form is submitted and the record exists it inserts the record anyway and sends the email which it's not suppose to do.
The form is suppose to after submitting -
1. validate
2. insert only if the record doesn't exist
3. send the email.
Here's the code
<?php $to = "email@email.com"; if(isset($_POST['submit'])) { // VALIDATION if(empty($_POST['firstName'])) { $errorfirstName .= "First Name Required"; } if(empty($_POST['lastName'])) { $errorfirstName .= "Last Name Required"; } if(empty($error)) # No error go ahead and email it. { $to = "$to"; $subject = 'the form'; $msg .="<html><head> <meta http-equiv='Content-Type' content='text/html; charset=utf-8' /> <title>The Form</title> </head> <body> <table> <tr> <td>Email sent for confirmation</td> </tr> </table> </body> </html>"; $mail($to, $subject, $headers, $msg); if(!$result) { $error = "<div id='errors'>There was an unknown error </div>"; } else { include('connection.php'); $firstName = mysqli_real_escape_string($con, $_POST['firstName']); $lastName = mysqli_real_escape_string($con, $_POST['lastName']); $address = mysqli_real_escape_string($con, $_POST['address']); $email = mysqli_real_escape_string($con, $_POST['email']); $email = $_POST['email']; $sql = "SELECT * FROM table WHERE `email` = '{$email}'"; $result = mysql_query($sql); if ( mysql_num_rows ( $result ) > 0 ) { $error = "Email Exists."; } else { $error = "Email does not exist. Insert it!!!"; $sql="INSERT INTO table (firstName, lastName, address, email) VALUES ('$_POST[firstName]','$_POST[lastName]','$_POST[address]', '$_POST[email]')"; } if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error($con)); } mysqli_close($con) { } } } } ?> <!-- Form --> <html> <head></head> <body> <section> <form method="POST" action="theform" name="for" onsubmit="return validateForm(this)"> <?php if(!empty($error)) { echo "$error"; } ?> This where the inputs would go not going to include them because not having an issue with the form </form> </section> </body> </html> Edited by barkly, 26 October 2014 - 06:54 PM. I am not sure if the title is correct; I tried my best.
I'm a PHP/MySQL beginner and I really need some help.
I have a small script that I am using for sending SMS. I recently added a phonebook. The problem with the phonebook right now is that it's available to all users, i.e. they can all update and delete all rows. What I would like to do is make it so that each user can update and delete only their own contacts.
I have a table call contacts. Inside that table there is first name, last name, company and phonenumber.
How can I accomplish this with PHP & MySQL?
CREATE TABLE IF NOT EXISTS `contacts` ( `contact_id` int(10) NOT NULL AUTO_INCREMENT, `firstname` varchar(255) NOT NULL, `lastname` varchar(255) NOT NULL, `company` varchar(255) NOT NULL, `cell_no` text NOT NULL, PRIMARY KEY (`contact_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ; CREATE TABLE IF NOT EXISTS `users` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `users_name` varchar(30) NOT NULL, `uname` varchar(30) NOT NULL, `u_pass` varchar(60) NOT NULL, `utype` varchar(30) NOT NULL, `timezone` varchar(30) NOT NULL, `uapi_user` varchar(30) NOT NULL, `uapi_pass` varchar(60) NOT NULL, PRIMARY KEY (`user_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=20 ; <?php if (isset($_POST['submit'])){ //form has been submitted1 $firstname = trim($_POST['firstname']); $lastname = trim($_POST['lastname']); $company = trim($_POST['company']); $cellno = trim($_POST['cell_no']); if($firstname == ''){ echo '<div class="alert alert-danger">First Name is not Valid!</div>'; exit; }elseif($lastname == ''){ echo '<div class="alert alert-danger">Last Name is not Valid!</div>'; exit; }elseif($company == ''){ echo '<div class="alert alert-danger">Company is not Valid!</div>'; exit; }elseif($cellno == ''){ echo '<div class="alert alert-danger">Cellphone Number is not Valid!</div>'; exit; }else{ $query = "Select cell_no from contacts where cell_no = '".$cellno."' "; $result = mysql_query($query); if (!mysql_num_rows($result)) { $sql = "INSERT INTO contacts(firstname, lastname, company, cell_no) values('{$firstname}','{$lastname}', '{$company}', '{$cellno}')"; $result = mysql_query($sql); confirm_query($result); //echo '<div class="alert alert-success">Successfully added.</div>'; //exit; ?> <script type="text/javascript"> window.location = "contact_list.php"; </script> <?php } else{ echo '<div class="alert alert-danger">Username. already exist!.</div>'; echo '<p><a href="new_contact.php" class="btn btn-success"> Back </a></p>'; exit; }} }else{ $firstname = ""; $lastname = ""; $company = ""; $cellno = ""; } ?> Hi again all, Why does the foreach loop im doing, put the array values from collection, into seperate table rows rather than 1 row per whole array? <?php class registration{ public $fields = array("username", "email", "password"); public $data = array(); public $table = "users"; public $dateTime = ""; public $datePos = 0; public $dateEntryName = "date"; public $connection; function timeStamp(){ return($this->dateTime = date("Y-m-d H:i:s")); } function insertRow($collection){ //HERE foreach($this->fields as $row => $value){ mysql_query("INSERT INTO $this->table ($value) VALUES ('$collection[$row]')"); } mysql_close($this->connection->connectData); } function validateFields(){ $this->connection = new connection(); $this->connection->connect(); foreach($this->fields as $key => $value){ array_push($this->data, $_POST[$this->fields[$key]]); } $this->dateTime = $this->timeStamp(); array_unshift($this->data, $this->dateTime); array_unshift($this->fields, $this->dateEntryName); foreach($this->data as $value){ echo "$value"; } $this->insertRow($this->data); } } $registration = new registration(); $registration->validateFields(); ?> I end up with 3 rows row 1: username row 2: email row 3 : password rather than row 1:username email password. Hi. I'm making a private webpage for my self where i can post news, games, music titles and movies. I'm made it so that i can post and delete them from my page. Also i wanted to have the option to edit them. So i made a action that shows me a list og the posts in each category. And then i want the option to hit UPDATE, and then it should open the form with the info's from MySQL. I've made those two options as the following: Code: [Select] elseif ( $action == "EditNews" ) { // EDIT NEWS START if ( !$_GET['id'] ) { ?> <div id="content"> <?php $sql = mysql_query("SELECT * FROM news") or die(mysql_error()); while ( $row = mysql_fetch_assoc($sql) ) { echo "<a href=\"?page=Admin&action=UpdateNews&id=" . $row['news_id'] . "\">Update</a> | " . $row['subject'] . "<br>"; } echo "</div>"; } else { $type = $_GET['type']; $id = $_GET['id']; } // EDIT NEWS END } elseif ( $action == "UpdateNews" ) { // UPDATE NEWS START if ( !$_POST['submit'] ) { $id = $_GET['id']; $sql = mysql_query("SELECT * FROM news WHERE news_id='$id'") or die(mysql_error()); $user_id = $_SESSION['uid']; $subject = $_row['subject']; $body = nl2br($_row['body']); ?> <div id="content"> <form action="?page=Admin&action=EditNews" method="post"> <div id="">Subject</div> <div id=""><input id="input" type="text" name="subject"></div> <div id="">Message</div> <div id=""><textarea id="input" name='body' cols='15' rows='4'></textarea></div> <div id=""><input id="submit" class="input" type="submit" name="submit" value="Post News"></div> </form> </div> <?php } else { ?> <div id="content">Not Working!</div> <?php } // UPDATE NEWS END } - I know i miss something, but i've tried to get to the point, where i only have the form as blank, and need some help from there. I hope someone can help me with my problem. MOD EDIT: [code] . . . [/code] tags added. Alright so I am trying to code a very simple form that adds a user to my SQL database with certain information filled in and certain information kept hidden with default values in a form. My index.php file is as follows (not all of the code but just the form part): <?PHP $submitMessage = $_GET['value']; if ($submitMessage == success) { echo '<div class="congratulations"><font color="#84d20c"><strong>Congratulations:</strong></font> The user has been added.</div>'; }else if($submitMessage == NULL){ }else if($submitMessage == fail){ echo '<div class="error"><font color="#d3430c"><strong>Error:</strong></font> An error occurred please check the error details below:</div>'; echo 'ERROR DETAILS:'; echo mysql_error(); } ?> <h1><i>Add User</i></h1> <p>This page is where you would manually add a user to the donations databases (for example you or a member of the community with elevated status that does not need to pay).</p> <br/> <form enctype="multipart/form-data" action="scripts/admin_save_sm_db.php" method="post"> <input name="authtype" value="steam"/><br /><br /> <h3><i>STEAM ID:</i></h3> <input name="identity" value="STEAM_0:X:XXXXXXXX"/><br /> <div class="form_help">Steam ID of the player you wish to add. Must be in the format STEAM_0:X:XXXXXXXX</div><br /> <input name="flags" value="o"/><br /><br /> <input name="name" value="Donator"/><br /><br /> <input name="immunity" value="0"/><br /><br /> <h3><i>Your Email Address</i></h3> <input name="user_email"/><br /> <div class="form_help">Your Email Address for security purposes.</div><br /> <input name="Submit" type="submit" value="Submit" class="form_submit" /> </form> My admin_save_sm_db.php file is as follows: <?php session_start(); if(!isset($_SESSION["username"])) { header('Location: login.php'); exit; } @require("../sm_admin_db.php"); $authtype = $_POST['authtype']; $identity = $_POST['identity']; $flags = $_POST['flags']; $name = $_POST['name']; $immunity = $_POST['immunity']; $user_email = $_POST['user_email']; $link = @mysql_connect(_HOST,_USER,_PASS); @mysql_select_db(_DB); $sql = @mysql_db_query(_DB,"INSERT INTO "._TBL." (`authtype`, `identity`, `flags`, `name`, `immunity`, `user_email`) VALUES (NULL, '$authtype', '$identity', '$flags', '$name', '$immunity', '$user_email')"); $okay = @mysql_affected_rows(); if($okay > 0) { header( "Location: ../index.php?value=success" ); } else { header( "Location: ../index.php?value=fail" ); } @mysql_close($link); ?> And finally my sm_admin_db.php file is as follows: <?PHP //host loaction define("_HOST", "localhost", TRUE); //database username define("_USER", "thatsact_admin", TRUE); //database username`s password define("_PASS", "*********", TRUE); //database name define("_DB", "thatsact_sadadmins", TRUE); //database table name change this to install multiple version on same database define("_TBL", "sm_admins", TRUE); //This is the email that you will recieve emails when someone signs up. define("_EMAIL", "admin@tag-clan.com", TRUE); ?> All of this together does not work and gives the echo error code, however the mysql_error() string does not return anything. Nothing is inserted into the database. Can I get some help on where I went wrong and please keep in mind I am VERY new to php and didn't write most of this script so just tell me what to edit and exactly how to do it please. Thanks in advance. It's about making a form for a web page. Which is better? Using table or divs? Which do you use? <form action='a.php' method='post'> <table> ............. </table> </form> <form action='a.php' method='post'> <div> ............. </div> </form> HI first timer here so please forgive me if this is in the wrong section. Anyway, here goes. I have 2 tables Table 1 Levels LevelID LevelName Table 2 Members MemberID FirstName LastName Birthdate LevelID I have a form that has the LevelID populated from table 1 with a query. When I enter all my data and hit submit the data gets written to the members table. However, the LevelID is written as 0 for each and everyone record that I have entered. So the question is what am I missing? As mentioned I am very new at this so any help would be greatly appreciated. Please see below for my code. Thanks in advance <?php require_once 'dblogin1.php'; $db_server = mysql_connect($db_hostname, $db_username, $db_password); if (!$db_server) die("Unable to connect to MySQL: " . mysql_error()); mysql_select_db($db_database) or die("Unable to select database: " . mysql_error()); $sql = "SELECT\n" . "levels.LevelID,\n" . "levels.LevelName\n" . "FROM\n" . "levels\n"; $result = mysql_query($sql) or die(mysql_error()); $options=""; while($row = mysql_fetch_array($result)){ $LevelId=$row["LevelID"]; $LevelName=$row["LevelName"]; $options.="<OPTION VALUE=\"$LevelID\">".$LevelName.'</option>'; } ?> <style type="text/css"> <!-- body p { color: #F00; } --> </style> <table width="500" border="1" align="center" cellpadding="0" cellspacing="1" > <tr> <td> <form name="form1" method="post" action="insert_ac.php"> <table width="100%" border="1" cellspacing="1" cellpadding="3"> <tr> <td colspan="3"><div align="center"> <p><strong>Myers Player Registration Form</strong></p> </div></td> </tr> <tr> <td>First Name</td> <td><div align="center">:</div></td> <td><input name="firstname" type="text" id="firstname"></td> </tr> <tr> <td>Last Name</td> <td><div align="center">:</div></td> <td><input name="lastname" type="text" id="lastname"></td> </tr> <tr> <td>Birthdate (yyyy-mm-dd)</td> <td><div align="center">:</div></td> <td><input name="birthdate" type="text" id="birthdate"> </td> </tr> <tr> <td>Level</td> <td><div align="center">:</div></td> <td><select name="LevelID"> <OPTION VALUE="0">Choose <?php echo $options?> </select></td> </tr> </form> </td> </tr> </table> Not sure exactly what my problem is here, but i have looked at this at least a hundred times and I just can't figure out what is going on. Everything works great except for the sending the email part. It displays the error "There was a problem sending the mail". The form field checking works fine, the insert into mysql works fine - - but it won't send the email. I have tried using double quotes and single quotes for the email information ($to, $subject, etc...) I have even eliminated the form data from the email information and it still doesn't send. I am hopelessly stuck at this point Any ideas?? Code below: <html> <body bgcolor = 'blue'> <div align = 'center'> <h1>test FORM</h1> </div> <p> <?php If ($_POST['submit']) //if the Submit button pressed { //collect form data $fname = $_POST['FName']; $lname = $_POST['LName']; $email = $_POST['Email']; $tel = $_POST['Tel']; $mess = $_POST['Mess']; $errorstring = ""; if (!$fname) $errorstring = $errorstring."First Name<br>"; if (!$lname) $errorstring = $errorstring."Last Name<br>"; if (!$email) $errorstring = $errorstring."Email<br>"; if ($errorstring !="") echo "<div align = 'center'><b>Please fill out the following fields:</b><br><font color = 'red'><b>$errorstring</b></font></div>"; else { $fname = mysql_real_escape_string($fname); $lname = mysql_real_escape_string($lname); $email = mysql_real_escape_string($email); $tel = mysql_real_escape_string($tel); $mess = mysql_real_escape_string($mess); $con = mysql_connect("localhost","user","password"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("mec", $con); $sql="INSERT INTO formtest (FName, LName, Title, Tel, Email, Mess) VALUES ('$fname','$lname','$title','$tel','$email','$mess')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } $to = 'myemailaddress'; $subject = 'test form'; $message = 'Hello'; $headers = 'From Me'; $sent = mail($to, $subject, $message, $headers); if($sent) {print "Email successfully sent";} else {print "There was an error sending the mail";} mysql_close($con); } } ?> <p> <form action= 'testmecform.php' method= 'POST'> <table width = '640' border = '0' align = 'center'> <tr> <td align = 'right'><b>First Name</b></td> <td><input type = 'text' name = 'FName' value = '<?php echo $fname; ?>' size = '25'></td> <td><div align = 'right'><b>Telephone</b></div></td> <td><input type = 'text' name = 'Tel' value = '<?php echo $tel; ?>' size = '25'></td> </tr> <tr> <td align = 'right'><b>Last Name</b></td> <td><input type = 'text' name = 'LName' value = '<?php echo $lname; ?>' size = '25'></td> <td> </td> <td> </td> </tr> <tr> <td align = 'right'><b>Email</b></td> <td><input type = 'text' name = 'Email' value = '<?php echo $email; ?>' size = '25'></td> <td> </td> <td> </td> </tr> <tr> <th colspan = '4'><b>Please enter any additional information he </b></th> </tr> <tr> <th colspan = '4'><textarea name = 'Mess' cols = '50' rows = '10'><?php echo $mess; ?></textarea></th> </tr> <tr> <th colspan = '4'><b>Please make sure all information is correct before submitting</b></th> </tr> <tr> <th colspan = '4'><input type = 'submit' name = 'submit' value = 'Submit Form'></th> </tr> </table> </form> </body> </html> |