PHP - Looping Inside Sql Insert Statement
I have a bunch of checkboxes I am pulling from a database, like so.
Code: [Select] <?$true_query = mssql_query("SELECT * FROM checkbox_datbase ORDER BY ID ASC"); while ($true_row = mssql_fetch_assoc($true_query)) { $eth_id = $true_row['ID']; $eth_name = $true_row['Value']; echo "<input type=\"checkbox\" name=\"eth_$eth_id\" value=\"1\" class=\"input\" id=\"Ethnic_01\"/>$eth_name <br />"; } ?>How do I put these into a database that I have settup where it needs to match up with a userid. I am trying to do this, and can get it to look correctly by echoing out the various parts, but I can't put while loops into a variable, right? So how would I get all of this into one line in my $sql variable? Code: [Select] echo "INSERT INTO new_database (UserId,"; $true_query = mssql_query("SELECT * FROM checkbox_datbase ORDER BY ID ASC"); while ($true_row = mssql_fetch_assoc($true_query)) { $eth_id = $true_row['ID']; $eth_eth_id = $_POST['eth_' . $eth_id . '']; echo " $eth_id, "; } echo "DateUpdated) VALUES ('$user_ID', "; $true_query = mssql_query("SELECT * FROM checkbox_datbase ORDER BY ID ASC"); while ($true_row = mssql_fetch_assoc($true_query)) { $eth_id = $true_row['ID']; $eth_eth_id = $_POST['eth_' . $eth_id . '']; echo "'$eth_eth_id', "; } echo "'$currenttime')"; This echoes something that looks like this INSERT INTO user_ethnicity (UserId, 1, 2, 3, 4, 5, 6, 7, 8, DateUpdated) VALUES ('', '', '', '', '', '', '', '', '', '2012-01-23 13:24:18 PM') , which I need the actual statement to be $sql = "INSERT INTO user_ethnicity (UserId, 1, 2, 3, 4, 5, 6, 7, 8, DateUpdated) VALUES ('259', '', '', '1', '', '1', '', '', '', '2012-01-23 13:24:18 PM')"; Can anyone help me with this? Similar TutorialsHi, I was wondering why this won't work, i am INSERTING an array of authors like so in a table, see insertAuthor() method below: <?php class People { public function insertAuthor(){ $authArray = array(); array_push($authArray, mysql_real_escape_string($_POST['author'])); //Check if Pname exists foreach($authArray as $author): $query = "SELECT * FROM People WHERE Pname = '".$author."'"; $result = mysql_query($query); if(mysql_num_rows($result) > 0): $row = mysql_fetch_array($result); $Pid = $row['Pid']; //If exists Get their Pid and insert into PeopleCon $sql = "INSERT INTO PeopleCon(Pid, PCorder, PCdateadded, PCdeleted) VALUES (".$Pid.", (select MAX(PCorder) + 1), now(), 0)"; $result = mysql_query($sql); else: //Else Get MAX Pid $query = "SELECT MAX(Pid) as max FROM People"; $result = mysql_query($query); $max = mysql_fetch_array($result); $Pid = $max['max']; //Insert into People $sql = "INSERT INTO People (Pname, Pdateadded, Pdeleted) VALUES ('".$author."', now(), 0)"; $result = mysql_query($sql); //Insert into PeopleCon $sql = "INSERT INTO PeopleCon(Pid, PCorder, PCdateadded, PCdeleted) VALUES (".$Pid.", (select MAX(PCorder) + 1), now(),0)"; $result = mysql_query($sql); endif; endforeach; } } ?> However what i need to do is, check to see if an Author exists, if so INSERT into a table called PeopleCon, if the Author does NOT exist i need to INSERT into 2 different tables, People and PeopleCon... The reason i have the 2 tables is because People simply holds the persons personal details, but PeopleCon holds details linking to different tables. But this query does not work, i know there are better methods of getting this to work.. I do this in the front end: if(isset($_POST['add_author'])): People::insertAuthor(); endif; Is this possible? I would appreciate any help. Just want to get this working Thanks Kind regards Billy I'm having issues with the following: Code: [Select] <?php session_start(); $_SESSION['username']=$_POST['username']; $_SESSION['password']=$_POST['password']; if($_SESSION['username']=="username" && $_SESSION['password']=="password"){ if($_GET['product']=="add"){ $content.=' <p><label>Product Name:</label> <input type="text" name="product_name" size="30" /> <label>Product Price:</label> <input type="text" name="product_price" size="5" /> </p> <p><label>Product Category:</label> <input type="text" name="product_category" size="30" /></p> <p><label>Product Link:</label> <input type="text" name="product_link" size="30" /></p> <p><label>Product Image:</label> <input type="text" name="product_image" size="30" /></p> <p><label>Product Tag:</label> <input type="text" name="product_tag" size="30" /></p> <p><label>Product Keywords:</label> <input type="text" name="keyword" size="30" /></p> <p><label>Product Features:</label><br /> <textarea name="product_features" rows="10" cols="60"></textarea> </p> <p><label>Product Pros:</label><br /> <textarea name="product_pros" rows="5" cols="30"></textarea> </p> <p><label>Product Cons:</label><br /> <textarea name="product_cons" rows="5" cols="30"></textarea> </p> <p><label>Product Description:</label><br /> <textarea name="product_description" rows="10" cols="60"></textarea> </p> <p><label>Product Notes:</label><br /> <textarea name="product_notes" rows="5" cols="30"></textarea> </p> '; $logout='<div><a href="./acp_admincp.php?log-out">Log-Out</a></div>'; } elseif($_GET['product']=="view"){ } else{ $content.=' <a href="./admincp.php?product=add">Add New Product</a> <br /> <a href="./admincp.php?product=view">View Products</a> '; } } elseif(isset($_GET['log-out'])){ session_start(); session_unset(); session_destroy(); header("Location: ./admincp.php"); } else{ $content=' <form action="./admincp.php" method="post"> <p><label>Username:</label> <input type="text" name="username" size="30" />'; $content.='</p> <p><label>Password:</label> <input type="password" name="password" /></p>'; $content.='<p><input type="submit" value="Submit" name="Submit" /></p> </form>'; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <base href="http://ghosthuntersportal.com/" /> <title>Ghost Hunter's Portal - Admin Control Panel</title> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="verify-v1" content="" /> <meta name="keywords" content="ghost, hunters, hunter, ghosts, spirit, spirits, paranormal, investigation, investigator, investigators, k2, emf, meter, kii" /> <meta name="description" content="Ghost Hunters Potal. Parnormal research equipment store." /> <meta name="author" content="Andrew McCarrick" /> <meta name="robots" content="index, follow" <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body> <img src="./logo.png" alt="Ghost Hunter's Portal Admin Control Panel" /> <br /> <div style="color: #AA44AA; font-size: 26px; margin-top: -30px; margin-left: 125px;">Admin Control Panel</div> <?php echo $logout; echo $content; ?> </body> </html> I can log-in, and get to the page with the two links on it. However, once I click one of the links it falls back to the log-in page, and it ends up being a never ending loop. It's doing this: Log-In --> Page with links ---> Log-In page again Should be doing this: Log-In --> Page with links --> Add Product page or View Products page I can never get into the the actual sub page. Just to be clear, the address bar actually shows product=add or product=view, but it still shows the log-in page. Hi, I would like to know how to write Insert data into a table statement where some of the data is coming from another table? I tried using Insert select statement but did not work. Here is what I am trying.... 1.........$sql = "INSERT INTO table1(id,fname, lname, gender, add1, add2, city, state, zip, country, email, phone, cellphone,employment,employmentinfo,dob, photo1,info) VALUES('$id','$fname','$lname','$gender','$add1','$add2','$city','$state','$zip','$country','$email','$phone','$cellphone','$employment','$employmentinfo','$dob','" . $image['name'] . "','$info') SELECT table2.id from table2 where table2.id=$id"; 2..........$sql = "INSERT INTO table1(id,fname, lname, gender, add1, add2, city, state, zip, country, email, phone, cellphone,employment,employmentinfo,dob, photo1,info) VALUES((SELECT id FROM table2 WHERE table2` WHERE username='".$_POST['username']."'),'$fname','$lname','$gender','$add1','$add2','$city','$state','$zip','$country','$email','$phone','$cellphone','$employment','$employmentinfo','$dob','" . $image['name'] . "','$info')"; I would appreciate your help. Thanks Smita Hello guys im new to php i been coding for like a week now, i need some help here i have been stuck for like 6 hours XD,is it possible to write an IF Statement inside an echo? //this is what i want to do // echo a table and a delete button // and if you click on the delete button it echoes out "DELETED" echo " <table width='528px'> <tr> <td> </td> <td> <center><font size='5'>$tittle</font></center><br> </td> </tr> <tr> <td> </td> <td> $message </td> </tr> <tr> <td> </td> <td> <font size='1'>Posted By:<font color='green'>$author</font> on <font color='gray'>$date</font> at <font color='gray'>$time</font></font> <input id='delete' name='delete' type='submit' value='Delete' > if ($_POST['delete']) { echo "DELETED"; } <td> </td> </tr><br><br> </table> "; I am trying to create a daily event listing. The list will have Day & Date as the heading. Then it will list the events ORDERED BY the time. First thing I'd like to do is skip or not show the days that do not have an event. Ex. Monday, January 23, 2012 7am event 8am event 6pm event since Tuesday has no events, I'd like tuesday to not be in the list, but if the next tuesday has an event It'll need be visible. Tuesday, January 24, 2012 (No events) Wednesday, January 25, 2012 9am event 12 pm event 8pm event The 2nd thing I'd like to do is If a particular day and time has more than one event, I'd like the time to show once and then list the events. ex. Monday, January 23, 2012 7am event event event 8am event 6pm event Here's the code: since the listing is for a range of 7 days I've only included 3 days worth of code. I've include the mysql_statements for pulling the information as well as the php code to show how it's being rendered and placed. HTML excluded. Code: [Select] <?php //TODAY $today2 = date('l, F j, Y');//php to format date $today_rehearsals = mysql_query(" SELECT Id, date, time, title, campus, room, ministry, category FROM events LEFT JOIN dates on events.dateId=dates.dateId LEFT JOIN time ON events.timeId=time.timeId LEFT JOIN campus ON events.campusId=campus.campusId LEFT JOIN rooms ON events.roomId=rooms.roomIdLEFT JOIN ministries on events.ministryId=ministries.ministryId LEFT JOIN category on events.categoryId=category.categoryIdWHERE ministry='music' AND date='$today' OR category='music' AND date='$today' ORDER By date, time") //////DAY ONE $day1= mktime(0,0,0, date("m"), date("d")+1, date("Y")); //php to get current date and add 1 day $day_1 = date("l, F j, Y", $day1); //php to format date $day1_rehearsal = mysql_query("SELECT Id, date, time, title, campus, room, ministry, category FROM events LEFT JOIN dates ON events.dateId=dates.dateIdLEFT JOIN time ON events.timeId=time.timeId LEFT JOIN campus ON events.campusId=campus.campusId LEFT JOIN rooms ON events.roomId=rooms.roomId LEFT JOIN ministries ON events.ministryId=ministries.ministryId LEFT JOIN category ON events.categoryId=category.categoryId WHERE ministry='music' AND date=CURDATE()+1 OR category='music' AND date=CURDATE()+1 ORDER BY time" ) or die(mysql_error()); /////DAY 2 $day2= mktime(0,0,0, date("m"), date("d")+2, date("Y")); //php to get current date and add 2 days $day_2 = date("l, F j, Y", $day2); //php to format date $day2_rehearsal = mysql_query("SELECT Id, date, time, title, campus, room, ministry, category FROM events LEFT JOIN dates ON events.dateId=dates.dateIdLEFT JOIN time ON events.timeId=time.timeId LEFT JOIN campus ON events.campusId=campus.campusId LEFT JOIN rooms ON events.roomId=rooms.roomId LEFT JOIN ministries ON events.ministryId=ministries.ministryId LEFT JOIN category ON events.categoryId=category.categoryId WHERE ministry='music' AND date=CURDATE()+2 OR category='music' AND date=CURDATE()+2 ORDER By time")or die(mysql_error()); ////TODAY echo "$today2"; //renders Today's date while($row = mysql_fetch_array( $today_rehearsals )){ $time=date_create($row['time']);//grab time for db $for_time=date_format($time, 'g:i a');//format time for viewing on page echo "$for_time"; echo $row['title']; echo $row['campus'] . " " . $row['room']; } ////day1 echo "$day_1"; //renders day_1's (tomorrow's) date while($row = mysql_fetch_array( $day1_rehearsal )){ $time=date_create($row['time']);//grab time for db $for_time=date_format($time, 'g:i a');//format time for viewing on page echo "$for_time"; echo $row['title']; echo $row['campus'] . " " . $row['room']; } ////day2 echo "$day_2"; //renders day_2's (day after tommorrow) date while($row = mysql_fetch_array( $day2_rehearsal )){ $time=date_create($row['time']);//grab time for db $for_time=date_format($time, 'g:i a');//format time for viewing on page echo "$for_time"; echo $row['title']; echo $row['campus'] . " " . $row['room']; } MOD EDIT: code tags fixed . . . After it goes through the while loop its supposed to take the ID of the first one in the loop and find out its awardType and then with the awardType variable go through the the if statement. After it displays it the code that fits the awardType variable then it gets the second item in the while loop and then with the ID of the second item takes it back to get the awardType and then goes back through the if statement again. I'm not sure what I'm doing wrong. As of right now all its doing is displaying its awardName and a blank dropdown. Code: [Select] <?php session_start(); // Access the existing session // Include the database page require ('../../inc/dbconfig.php');l $userID = $_SESSION['userID']; $statusQuery = " SELECT * FROM statuses"; $statusResult = mysqli_query ( $dbc, $statusQuery ); // Run The Query $awardQuery = " SELECT awards.ID, awards.awardName, awards.awardType FROM awards"; $awardResult = mysqli_query ( $dbc, $awardQuery ); // Run The Query $row = mysqli_fetch_array ( $awardResult, MYSQL_ASSOC ); $awardType = $row[ 'awardType' ]; $charactersQuery = " SELECT characters.ID, characters.characterName FROM characters ORDER BY characters.characterName"; $charactersResult = mysqli_query ( $dbc, $charactersQuery ); // Run The Query $matchQuery = " SELECT eventSegments.ID, eventSegments.segmentTitle FROM eventSegments INNER JOIN events ON eventSegments.eventID = events.ID WHERE DATE_FORMAT(events.bookingDate,'%Y') = DATE_FORMAT(curdate(),'%Y')"; $matchResult = mysqli_query ( $dbc, $matchQuery ); // Run The Query ?> Code: [Select] <fieldset> <legend>Nominees</legend> <?php mysqli_data_seek( $awardResult, 0 ); while ( $row = mysqli_fetch_array ( $awardResult, MYSQL_ASSOC ) ) { ?> <?php if ($awardType == 'Singular') { ?> <div class="field required"> <label for="charactersDrop"><?php echo $row['awardName']; ?></label> <select class="dropdown" name="charactersDrop" id="charactersDrop" title="Characters Drop"> <option value="">- Select -</option> <?php while ( $row = mysqli_fetch_array ( $charactersResult, MYSQL_ASSOC ) ) { print "<option value=\"".$row['ID']."\">".$row['characterName']."</option>\r"; } ?> </select> <input type="button" value="Add Character" class="" onclick="HandlerCharacters()"/> <ul id="characterList"> </ul> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <? } else { ?> <div class="field required"> <label for="events"><?php echo $row['awardName']; ?></label> <select class="dropdown" name="events" id="events" title="Events for <?php echo date("Y") ?>"> <option value="">- Select -</option> <?php while ( $row = mysqli_fetch_array ( $matchResult, MYSQL_ASSOC ) ) { print "<option value=\"".$row['ID']."\">".$row['segmentTitle']."</option>\r"; } ?> </select> <input type="button" value="Add Match" class="" onclick="AddMatch()"/> <ul id="matchList"> </ul> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <?php } ?> <?php } ?> I am wondering if it is possible to create 2 queries, and use 1 while statement? Something like: Code: [Select] while (($row = mysql_fetch_array($rs_getevent)) && ($row = mysql_fetch_array($rs_getevent2))) { Is something like this possible? Hi everyone. i'm trying to write an if statement for several scenerios 1. if the date entered in '$DateDue' is overdue, meaning greater than todays date, then display the word 'Late'. 2. if the date entered in '$DateDue' is not yet past, meaning its greater than todays date, then display the word 'ok'. 3. if the date entered in '$DateDue' is within a week of todays date, then display the word 'warning' the code snippet below is my partial script. it runs perfectly without embedding the 'php if statement' on the first td row. So my problems a 1. how to embed a php if statement in table results and 2. have OK, LATE or WARNING to be displayed based on if $DateDue expires or not. there are no errors in the code below, it just echos the line '<?php if ($DataDue > CURDATE()) {echo "OK";} elseif ($DateDue < CURDATE()) {echo "LATE";} else {echo "Warning";}?>' instead of displaying OK, LATE or Warning. I'd appreciate any assistance you could provide. thanks. Code: [Select] // echo out the contents of each row into a table echo "<tr>"; echo '<td nowrap><?php if ($DataDue > CURDATE()) {echo "OK";} elseif ($DateDue < CURDATE()) {echo "LATE";} else {echo "Warning";}?>' . mysql_result($result, $i, 'DateDue') . '</td>'; echo '<td nowrap>' . mysql_result($result, $i, 'Description') . '</td>'; echo '<td nowrap>' . mysql_result($result, $i, 'CompanyName') . '</td>'; echo "</tr>"; I have the following code which gets staff working on a selected day and their start and finish times. The code then lists out the day for every 15min of time for each staff member. During the loop of each staff member I then check an appointment table to see if a user has any appointments, and lists the booked time slots, if no appointments lists user as available for all the time slots. My problem is when a user has appointments it only shows the booked times and not the available times. I know the problem lies here else if ($inc<$resSTART && $inc>$resEND) { and the complete code that is from is here // convet to US format $input="$month/$day/$year"; // readable date $readDATE="$day/$month/$year"; // convert for mysql date $sqlDATE="$year-$month-$day"; // get day of the week $weekday=date(l, strtotime($input)); echo $weekday."<br/>"; // get working staff from staff table $staffSQL=mysql_query("SELECT * FROM staff WHERE ".$weekday." != 'off' AND onLEAVE='no' AND ACTIVE='yes' ORDER BY staffID ASC"); // return results putenv("TZ=Australia/Adelaide"); while ($staff=mysql_fetch_array($staffSQL)) { $name=$staff['staffNAME']; $avail=$staff[$weekday]; $staffID=$staff['staffID']; list($first, $last)=explode(" ", $name); list($in, $out)=explode("-", $avail); $firstTIME="$sqlDATE $in:00"; $lastTIME="$sqlDATE $out:00"; echo "$first is available between $avail on $weekday<br/>"; $in2=strtotime($firstTIME); $out2=strtotime($lastTIME); $stop=$out2-900; echo $in2." - time start - $firstTIME<br/>"; echo $out2." - time finish - $lastTIME<br/>"; for ($inc=$in2;$inc<=$stop;$inc+=900) { $existSQL=mysql_query("SELECT * FROM appointment WHERE date='$sqlDATE' AND staffID='$staffID'"); if (mysql_num_rows($existSQL)>=1) { while ($appointV=mysql_fetch_array($existSQL)) { $resSTART=$appointV['dateTIME']; $length=$appointV['totalTIME']; $resEND=$resSTART+($length*60); if ($inc>=$resSTART && $inc<=$resEND) { echo "Appointment time is ".date("g.i a", $inc)." <font color='red'><< $first BOOKED</font><br/>"; } else if ($inc<$resSTART && $inc>$resEND) { echo "Appointment time is ".date("g.i a", $inc)." <font color='green'><< $first AVAILABLE</font><br/>"; } } } if (mysql_num_rows($existSQL)==0) { echo "Appointment time is ".date("g.i a", $inc)." <font color='green'><< $first AVAILABLE</font><br/>"; } } } any ideas how to restructure that if statement to work properly would be very much appreciated I have a simple INSERT statement that isn't inserting anything into one of the columns: coin_name I've gone over everything and can't figure out why. All other columns get data. HTML form passes everything fine. Is there a good way to debug this? I've triple checked everything and there are no type-o's that I see. Driving me mad... $query = "INSERT INTO Coin (coin_name, coin_value, coin_condition, year_minted, face_value, purchase_price) VALUES ('$coin_name', '$coin_value', '$coin_condition', '$year_minted', '$face_value', '$purchase_price');"; Hey guys! Im trying to setup an IF statement on my home page. Its purpose is to show EITHER a login form and state your not logged in if it cannot find a stored cookie OR if it does find a stored cookie it will NOT show the HTML form and state you are logged in. I have it mostly working apart from the fact Im not sure how to insert a HTML form into PHP IF statement and make it work. Since I dont want the user to see the login form when they are already logged in. Here is a link to the php script: http://pastebin.com/aenq4gbE Here is link to the live page: http://jfbsystems.co.uk/secure Any help or ideas would be much appreciated! JellyFishBoy Hello, guys. I am experiencing some problems with an INSERT statement in this page. It simply won't write to the database! I added echo at the bottom to check my variables and they print the values just fine. I checked the database, table and datafield names and everything is correct, plus I don't have any issues with the other 25 tables of my database. I'm using XAMPP btw... Any help would be appreciated! Code: [Select] <!DOCTYPE html> <html> <head> <meta content="text/html; charset=utf-8" http-equiv="content-type"> <title>Doctors</title> <link rel="stylesheet" href="style.css" media="screen" /> </head> <body > <?php session_start(); $inc_code=$_SESSION['incident']; $doc_code=$_REQUEST['doctor_code']; $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } $mdb = "registry_db"; mysql_select_db($mdb, $con); mysql_query("SET NAMES 'utf8'", $con); ?> <div id="myform"> <p> <h2>Doctor in charge</h2> </p> <?php $sql="INSERT INTO doctors_per_incident(Incident_code, doctor_code) VALUES ('$inc_code', '$doc_code')"; echo "1 record added"." ".$inc_code." ".$doc_code; mysql_close($con); ?> </div> </body> </html> I am new to PHP and am currently learning the ropes. I have writen some code to insert a line into a mySQL database. I have created 3 fields in the mySQL database and am passing values two them. I can use a declared variable to pass information to the filed ID (Index filed in mySQL) but if I use a variable to pass purely text values the database is not updated. mysql_query( "INSERT INTO $tbl_name (category_Name, ID, test) VALUES ($category, $internalId, $category2)" ); If I replace the variables with specific text, the rows are added successfully. mysql_query( "INSERT INTO $tbl_name (category_Name, ID, test) VALUES ('werwerwer', $internalId, 'werrr')" ); It must be something stupid, I am sure. Full code below ob_start(); $host="localhost:8888"; // Host name $username=""; // Mysql username $password=""; // Mysql password $db_name="expenses"; // Database name $tbl_name="expense_category"; // Table name $category="test3"; $internalId="7"; $category2="test3"; // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); mysql_query( "INSERT INTO $tbl_name (category_Name, ID, test) VALUES ('werwerwer', $internalId, 'werrr')" ); echo "Done now 6!"; ?> Folks, Tell me, do you see anything wrong in my INSERT ? If not, then why is it not INSERTING ? I get no php error, nor mysql error. Button I click. Then form data vanishes as if submitted. I check db and no submission came through! <?php //include('error_reporting.php'); ini_set('error_reporting','E_ALL');//Same as: error_reporting(E_ALL); ini_set('display_errors','1'); ini_set('display_startup_errors','1'); ?> <form name = "submit_link" method = "POST" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <label for="domain">Domain:</label> <input type="text" name="domain" id="domain" placeholder="Input Domain"> <br> <label for="domain_email">Domain Email:</label> <input type="email" name="domain_email" id="domain_email" placeholder="Input Domain Email"> <br> <label for="url">Url:</label> <input type="url" name="url" id="url" placeholder="Input Url"> <br> <label for="link_anchor_text">Link Anchor Text:</label> <input type="text" name="link_anchor_text" id="link_anchor_text" placeholder="Input Link Anchor Text"> <br> <textarea rows="10" cols="20">Page Description</textarea> <br> <label for="keywords">Keywords:</label> <input type="text" name="keywords" id="keywords" placeholder="Input Keywords related to Page"> <br> <button type="submit">Click me</button> <br> <input type="reset"> <br> </form> <?php if($_SERVER['REQUEST_METHOD'] === 'POST') { /* if(ISSET($_POST['submit_link'])) {*/ mysqli_report(MYSQLI_REPORT_ALL|MYSQLI_REPORT_STRICT); mysqli_connect("localhost","root","","test"); $conn->set_charset("utf8mb4"); if(mysqli_connect_error()) { echo "Could not connect!" . mysqli_connect_error(); } $query = "INSERT into links (domain,domain_email,url,link_anchor_text,page_description,keywords) VALUES (?,?,?,?,?,?)"; $stmt = mysqli_stmt_init($conn); if(mysqli_stmt_prepare($stmt,$query)) { mysqli_stmt_bind_param($stmt,'ssssss',$_POST['domain'],$_POST['domain_email'],$_POST['url'],$_POST['link_anchor_text'],$_POST['page_description'],$_POST['keywords']); mysqli_stmt_execute($stmt); mysqli_stmt_close($stmt); mysqli_close($conn); } else { die("INSERT failed!"); } //} } ?>
@MacGuyver,
I will do the VALIDATIONS later. Remember, I was testing myself how much I can code without notes. What you see above was from my memory. Am still a beginner php student for 3yrs now, however! As for validation stuff will have to check notes and learn or relearn. Meaning, have to memorise the code before I add it here on current project. And so for now, ignore VALIDATIONS and let me know why it's not submitting data into db.
I am trying to create a query to insert data into a table in my Access database. I have the following query:
INSERT INTO Issues (DateRequested, CustomerID, ComputerID, Issue, ItemsIncl, ImageName) VALUES (#1/14/2015#, 1, 1, "Computer freezes while I'm on the internet.", "AC Adapter", "none.gif")which should be performed from within my PHP page. However, when I check the database afterward, the new record isn't there. I then tried performing the query directly in Access and it worked fine. Why would it work in Access, but not when I run the same query in PHP? Chris Hi I am new to PHP and this is my first post one here so appologies is this questions seems a bit dumb! I have an if clause such that if a button is pressed on my web page then i want to reload the page and include a new form on it. I am having a problem getting the $_SERVER['PHP_SELF'] command to work from iside a echo command. I must not be escaping the code correctly with back slashes: I currently have the line : echo"<form method=\"POST\" action=\"\<?$_SERVER['PHP_SELF']?\>\">"; However this doesnt seem to work as my page just doesnt display in the browser. Any advice is much appreciated. Thanks for taking the time to read. Is it possible to have a loop inside a mysql select statement? If yes, can someone please give me an idea. This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=315503.0 I am trying to insert a record into a mysql database which has a $ as part of the value of a field. But it seems that when the INSERT query is processed its actually looking for a variable with that name and not just inserting the raw text. Here is the insert query $query = "INSERT mytable SET myfield='I would like to have this field contain this information with a $matches[1] showing in the field value as well'"; $matches[1] has no value. Its not a variable which is in this script. I am not trying to insert the value of it. I just want to insert the actual text characters $matches[1] How can I do that? Hi - I have spent 2 days trying to figure this out. I must be doing something stupid ... I am trying to update the DB with a collection of variables off of a various POST array's. I have indexed the variables so that I can loop through them with a FOR. However I am having all kinds of trouble: 1 - WEIGHT is giving 5 values even though the counter should only go 4 times. 2 - The WEIGHT variable is going into the wrong field in the DB even though I specify in my Query a specific place. 3 - I get undefined offset errors even though I have initialised the variables with their respective offsets. 4 - Adding the conditional statement adds even more offset errors even though they are initialised I am starting to wonder if my entire approach to updating my DB is flawed. As a student of PHP I think I need someone with more experience to look at what I am doing and tell me if something jumps out at them. There is a lot of statements echoing out values - and they all seem to check out. Man Many thanks for your advice Code: [Select] function finishedorder(){ $prodname = $_POST['prodname']; $prodid =$_POST['prodid']; $quantity = $_POST['quantity']; $pricelb = $_POST['pricelb']; $customerid = $_POST['customerid']; $price = $_POST['price']; $orderid = $_POST['orderid']; $weight = $_POST['weight']; echo "Varuable WEight"; print_r($weight); echo"<br/>"; echo "line 196 Weight"; print_r ($_POST['weight']); echo"<br/>"; echo "line 192 PriceLB"; print_r ($_POST['pricelb']); echo "<br/>"; echo "line 193 Price"; print_r ($_POST['price']); echo "<br/>"; echo "line 194 ProdID"; print_r ($_POST['prodid']); echo "<br/>"; echo "line 195 OrderID"; print_r ($_POST['orderid']); echo "<br/><br/>"; $numloops = count($_POST['prodid']); for ($i = 0; $i < $numloops ; $i++) { // !!! Start of the for loop !!! if (!isset($orderid[$i])) $orderid[$i] =''; if (!isset($prodid[$i])) $prodid[$i] =''; if (!isset($weight[$i])) $weight[$i] =''; if (!isset($pricelb[$i])) $pricelb[$i] =''; // This only initialises the Price & Weight variable to avoid an offset error message. if (!isset($weight[$i])) $weight[$i] =''; $ordervalue = $pricelb[$i] * $weight[$i]; echo " L. 216 The number is " . $i . "<br />"; echo "line 221 ProdID".$prodid[$i];echo "<br/>"; echo "line 217 Pricelb".$pricelb[$i];echo "<br/>"; echo 'Weight L. 219 weight[i]'. $weight[$i];echo "<br/>"; echo "line 220 weight".$weight; echo "<br/>"; echo "line 221 Numloops".$numloops; echo "<br/><br/>"; echo ' L. 225 $ordervalue ' .$ordervalue;echo "<br/>"; } //if ($pricelb[$i] == 0 ){ // conditonal statement // $ordervalue = $price[$i]; // } $sql =" UPDATE confirmedorder SET weight='$weight[$i]', ordervalue='$ordervalue', confirmedorder.picking = 'finished', confirmedorder.sale = 'open' WHERE prodID = '$prodid[$i]' AND OrderID = '$orderid[$i]' ; "; $this->db->query($sql); } // !! End For Loop. !! |