PHP - How Do I Take Data From A Select Query And Insert Into Another Table?
I have tried several attempts and can get data to select and using echo display it, however, I need to take this data and insert it into the database in a separate table. I have the following which does hafl the job, can I get some pointers on the rest. I have looked everywhere and not found a solution, at all.
// Selects the data I need <?php mysql_connect("PRIVATE INFO","PRIVATE INFO","PRIVATE INFO") or die("Could not connect: " . mysql_error()); mysql_select_db("wpdb"); $result = mysql_query("SELECT ID FROM wp_posts WHERE post_title LIKE '%future%' AND post_status = 'publish' OR post_title LIKE '%option%' AND post_content LIKE '%fundamental%' AND post_status = 'publish' ORDER BY post_date DESC"); while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { echo $row['ID']; echo "<br />";}; ?> Thought maybe something like the following would work, but am at a loss: INSERT INTO wp_term_relationships (object_id, term_taxonomy_id, term_order) SELECT ID FROM wp_posts WHERE post_title LIKE '%future%' AND post_status = 'publish' OR post_title LIKE '%option%' AND post_content LIKE '%fundamental%' AND post_status = 'publish' ORDER BY post_date DESC while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) VALUES ($row['ID'], '25', '0') Similar Tutorialsi want the name of a picture stored in my db after i upload it the data is not stored in the db after i run this script, but i dont get errors either i print the two vars before sending them, and they get printed fine any help on this would be greatly appreciated thanks ! <?php error_reporting(E_ALL); ini_set("display_errors", 1); // INCLUDE THE CLASS FILE include('ImageLib.Class.php'); include("./includes/egl_inc.php"); $displayMessage = ''; if($_POST){ if(isset($_FILES['image_file'])){ // SEE THE MAGIC HAPPEN $destination_path = 'uploads/'; $post_file_name = 'image_file'; $width = 600; $height = 400; $scale = false; $trim = true; $uniqueName = true; $img = ImageLib::getInstance()->upload($post_file_name, $destination_path, $uniqueName)->resize($width, $height, $scale, $trim)->save(); $imgstr = mysql_real_escape_string ($img); $fileName = $_FILES['image_file']['name']; $displayMessage = '<div class="image"><img src="'.$destination_path.$fileName.'" /><br />Uploaded And Resized...With new file name : "'.$img.'"</div><br /><br />'; $playerid=$_SESSION['tid']; $matchdetails = mysql_fetch_array(mysql_query("SELECT id FROM ffa_matches WHERE status=2 and admin=$playerid")); $id = $matchdetails[id]; print $img;print $imgstr; print $id; mysql_query(" INSERT INTO ffa_screens (imgname,match) VALUES( '" . mysql_real_escape_string($imgstr) . "', '" . mysql_real_escape_string($id) . "' )"); }} ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>ImageLib Samples By Rahul Kate</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <style> body{font-family: arial; font-size:12px; color:#444444; padding:20px;} li{margin-top:10px;} .image{color:green;} .image img{margin-bottom:5px;} </style> </head> <body> <h1>ImageLib | Upload Image, move it to Uploads folder and Resize it and Trim</h1> <?php echo $displayMessage; ?> <form method="post" enctype="multipart/form-data"> Select Image<br /> <input type="file" name="image_file" id="image_file" /> <br /> <br /> <input type="submit" name="submit" value="Submit" /> <br /> <br /> <a href="index.html">Back TO Home</a> </form> </body> </html> Hi, I would like to do the following in PHP using a MySQL database, but not sure how. select a, b,c etc.. from mailbox where id = X then insert id,a,b,c etc.. into problem When I select, I will be calling the id So I would like it to get data from mailbox and then insert it into problem. How would I go about doing this? Thanks for any help you can give me could anyone please help me with the code which is i have already displayed data as a multi select list but now i need to select one or more from them and insert into another database table. would be appreciate your help. thanx I've been poking around the Internet for the answer to this without any success. This query APPEARS to run, but NOTHING GETS INSERTED. The QuestionID in the Questions table is set to auto-increment, so I only need the QuestionText data for this table. the QuestionID in the Answers table is not because there might be four or five options per question. The snippets of code under consideration is pasted below snipped from index.php: Code: [Select] <form action="./newquestion.php" method="post"> Question Text:<br><input type="text" size=100 name="QuestionText" /><br><br> <input type="submit" value="Enter next question"/> </form> Then snipped from newquestion.php mysql_select_db(quiz); $query = mysql_query("INSERT INTO Questions VALUES ('$_POST[QuestionText]'"); $result = mysql_query($query); Thank you all. I'm sure I'll learn this pretty fast, but I still need a little help. hi ..
hit little snag Ive got html <form name="formx" method="POST" action="connect.php" class='ajaxform'> and about 4 varibles in that form .. now how to properly
query table users so i can find out which prefix correspond with that user
Insert into table "upis" in this case that prefix with 3 variables..
everything in single,.. in this case connect.php file
I know how to do QUERY and INSERT INTO but i don't know how to connect with 2 different tbl or db and do the query and input of data.. every time I put 2 of them together .. never works out..
this is example.. i dont know is this right way to do it .. How can i use single quote for values? $qry='insert into tablename values('a','b');'; i want a situation where, when i upload something into my database, it creates a new table, everytime, i saw this
$forum = "CREATE TABLE IF NOT EXISTS for_".$id." ( Code: [Select] $myusername = $_POST['myusername']; mysql_query("INSERT INTO logedin ( username ) VALUES ('$myusername')") OR die("Could not send the message: <br>".mysql_error()); wont insert anything no error's given even just trying to insert username into the the loged in table yes i know i spelt loged in wrong but i did that on the db lol hi im trying to use query to select from a table where the price is between to values that the user has to input such as min of 3 and max of 8 and return all the fields from the database where it is true im unsure how to do this but this is what i have so far
$res = pg_query ($conn, "SELECT ref,artist,composer,genre,title,album,label,price,description FROM music WHERE price = < && > "); This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=319161.0 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> Hi guys, Im making an event booking/reservation site, I have 5 tables (Malls, Events, Booking, Reservation and Users) which are all connected and doing fine. I created a function which is this... function select_all_events_by_mall_id($mall_id) { echo "<table id='event_table'>"; echo "<th>Event Name</th>"; echo "<th>Event Location</th>"; echo "<th>Number of Cars</th>"; echo "<th>Description</th>"; echo "<th>Booked</th>"; echo "<th>Reserved</th>"; echo "<th>Reserved Until</th>"; echo "<th>Vacant</th>"; $events_set = select_all_events($mall_id); while($events = mysql_fetch_array($events_set)) { echo "<tr>"; echo "<td>" . $events['event_name'] . "</td>"; echo "<td>" . $events['event_location'] . "</td>"; echo "<td>" . $events['number_of_cars'] . "</td>"; echo "<td>" . $events['description'] . "</td>"; // Booked echo "<td>"; $booked_set = select_all_booking($events['id']); while($booked = mysql_fetch_array($booked_set)) { $user_set = select_all_user_booked($booked['users_id']); while($user = mysql_fetch_array($user_set)) { echo $user['company'] . ", " . $user['branch'] . "<br />"; } } echo "</td>"; // Reserved echo "<td>"; echo "<ol>"; $reserved_set = select_all_reservation($events['id']); while($reserved = mysql_fetch_array($reserved_set)) { if(empty($reserved['events_id'])) { echo "No Reservation's "; } else { $reserved_user = select_all_user_reserved($reserved['users_id']); while($user_set = mysql_fetch_array($reserved_user)) { echo "<li>" . $user_set['brand'] . ", " . $user_set['branch'] . "</li>"; } } } echo "</ol>"; echo "</td>"; // Expiration Date echo "<td>"; echo "<ol>"; $reserved_set = select_all_reservation($events['id']); while($reserved = mysql_fetch_array($reserved_set)) { $reserved_user = select_all_user_reserved($reserved['users_id']); while($user_set = mysql_fetch_array($reserved_user)) { $exp_date = select_all_expiration_date($user_set['id']); while($date = mysql_fetch_array($exp_date)) { echo "<li>" . $date['expiration_date'] . "</li>"; } } } echo "</ol>"; echo "</td>"; //Vacant echo "<td>"; $vacant_set = select_all_booking($events['id']); $booking_count = mysql_num_rows($vacant_set); $reserved_count = mysql_num_rows($reserved_set); $total_count = $booking_count + $reserved_count; $vacant = $events['number_of_cars'] - $total_count; if($vacant < 0) { echo "This Event is fully booked"; } else { echo $vacant; } echo"</td>"; echo "</tr>"; } echo "</table>"; } The function starts by receiving an id from picking a mall name from a select tag. It works fine, it outputs the data on the page like i want it to, but my problem is that i need a way to add a submit or any button to each generated row that will, when clicked will insert the event id and user id (who clicked it) to my booking/reservation table as a new row. I tried adding a form inside my function and saving the event id every loop but when i click the submit button i think it doesn't work (or i made a mistake).. Sorry if my coding sucks, I'm kinda new in php. Sorry if its kinda confusing my head is spinning right now from thinking this stuff the whole day.. Thanks in advance for any comments and ideas. Hi all, probably a fairly straightforward question, but I can't find the answer I'm looking for: I have an array 'idents' that contains ID numbers. I now want to write a MySQL query that selects all values of the table-field 'email' where the field 'ID' = any of the IDs stored in 'idents'. Then I want to put those emails in an array 'emails'. So e.g. my table is as follows: ID | email ---------------------- 111111 | email1 222222 | email2 333333 | email3 444444 | email4 555555 | email5 666666 | email6 and the array 'idents' is as follows: '111111','444444','555555' then I want the query to return 'emails' = array('email1','email4','email5'); Thanks for your help! Hi? im just a beginner in php i just want to ask how to insert a data into a table from a dropdown list. I have concatenate the itemid and description to form the dropdown list. But when i viewed my item_table the itemid and description columns are null. can you help me with this.. this is my php code for the dropdown list... <?php $query = "SELECT CONCAT(itemid,' ', '-',' ', description) AS Item FROM item_table"; $result = mysql_query($query) or die(mysql_error()); $dropdown = "<SELECT CONCAT(itemid,' ' '-',' ', description) AS Item FROM item_table>"; while($row = mysql_fetch_assoc($result)) { $dropdown .= "\r\n<option value='{$row['Item']}'>{$row['Item']}</option>"; } $dropdown .= "\r\n</select>"; echo $dropdown; ?> this my code for inserting data into the item_table... <?php if(isset($_POST ['submit'])) { $itemid = $_POST['itemid']; $description = $_POST['description']; $datein = $_POST['datein']; $qtyin = $_POST['qtyin']; $unitprice = $_POST['unitprice']; $unit = $_POST['unit']; $category = $_POST['category']; $empid = $_POST['empid']; $message =''; if(($itemid && $description == "")||($itemid && $description == null)) { header("location:IncomingEntry.php?msg=Incorrect"); exit(); } else { $link = mysql_connect('localhost', 'root', '') or die(mysql_error()); $db_selected = mysql_select_db('inventory', $link); $message=''; $query = "INSERT INTO incoming_table (itemid , description, datein, qtyin, unitprice, unit, category, empid) VALUES ('".$itemid."', '".$description."', '".$datein."', '".$qtyin."', '".$unitprice."', '".$unit."', '".$category."', '".$empid."')"; if (!mysql_query($query,$link)) { die('Error: ' . mysql_error()); } header("location: IncomingEntry.php?msg=1 record added"); } } ?> Hi guys, im inserting data into the table using drop-down list & multi select list,well it works very well. but i need to make sure i should not insert same StudentID & CourseID twice. here my code for you could anyone tell me pls where should i write code to check existing data? <?php $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("uni", $con)or trigger_error('MySQL error: ' . mysql_error()); $result = mysql_query("SELECT * FROM student") or trigger_error('MySQL error: ' . mysql_error()); echo '<select name="sid">'; while($row = mysql_fetch_array($result)) { echo '<option value="' . $row['StudentID'] . '">' . $row['StudentName'] . '</option>'; } echo '</select>'; // ---------------- ?> </div> <div class="style41" id="Layer7"> <?php $result = mysql_query("SELECT * FROM course") or trigger_error('MySQL error: ' . mysql_error()); echo '<select name ="cid[]" multiple="multiple" size="10">'; while($row = mysql_fetch_array($result)) { echo '<option value="' . $row['CourseID'] . '">' . $row['CourseName'] . '</option>'; } echo '</select>'; mysql_close($con); ?> ------------------------------------ <?php $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("uni", $con)or trigger_error('MySQL error: ' . mysql_error()); if (!empty($_POST['sid']) && !empty($_POST['cid'])) { $ct = 0; $student = $_POST['sid']; foreach ($_POST['cid'] as $key => $course) { $sql = "INSERT INTO take (StudentID, CourseID) VALUES('".mysql_real_escape_string($student)."', '".mysql_real_escape_string($course)."')"; $query = mysql_query($sql) or trigger_error('MySQL error: ' . mysql_error()); if (mysql_affected_rows() > 0){$ct++;} } echo $ct . ' rows added.'; } mysql_close($con); ?> 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) ?> I have a photo album style gallery to build and i'm finding it dificult to list all the table names (these are names of photo albums) and then enter the data into a seperate query for each album name (these will change often so i cant keep updating the file as normal. this will then post all the data to the xml file and show the set of photos in the individual albums in a flash file. can anyone help me where im going wrong at all? <?php $dbname = 'cablard'; if (!mysql_connect('localhost', 'cablard', '')) { echo 'Could not connect to mysql'; exit; } $sql = "SHOW TABLES FROM $dbname"; $result = mysql_query($sql); if (!$result) { echo "DB Error, could not list tables\n"; echo 'MySQL Error: ' . mysql_error(); exit; } while ($row = mysql_fetch_row($result)) { echo "Table: {$row[0]}\n"; } mysql_free_result($result); $query = "SELECT * FROM photo ORDER BY id DESC"; $result2 = mysql_query ($query) or die ("Error in query: $query. ".mysql_error()); while ($row = mysql_fetch_array($result2)) { echo " <image> <date>".$row['date']."</date> <title>".$row['title']."</title> <desc>".$row['description']."</desc> <thumb>".$row['thumb']."</thumb> <img>".$row['image']."</img> </image> "; } ?> Thanks James I'm creating a report page and can't figure out how to retrieve multiple rows from a table and display them in html. There are 5 data elements in each row and I'm thinking that using a form in the html might be the best way as I'm totally ignorant about tables in html. I'm a newbie to php and can't figure out how to accomplish this. Here's the code that I have so far: <?php $filename = NULL; session_start(); // start of script every time. // setup a path for all of your canned php scripts $php_scripts = '../php/'; // a folder above the web accessible tree // load the pdo connection module require $php_scripts . 'PDO_Connection_Select.php'; //******************************* // Begin the script here // Connect to the database if (!$con = PDOConnect("foxclone")): { echo "Failed to connect to database" ; exit; } else: { $sql = 'SELECT COUNT(IP_ADDRESS) FROM download WHERE FILENAME IS NOT NULL'; $sql1 = 'Update download t2, ip_lookup t1 set t2.country = t1.country, t2.area = t1.area, t2.city = t1.city where ((t2.IP_ADDRESS) = (t1.start_ip) OR (t2.IP_ADDRESS) > (t1.start_ip)) AND ((t2.IP_ADDRESS) = (t1.end_ip) OR (t2.IP_ADDRESS) < (t1.end_ip)) AND (t2.FILENAME is not null and t2.country is null)'; $sql2 = 'SELECT (IP_ADDRESS, FILENAME, country, area, city) from download where FILENAME is not null'; // Update the table $stmt = $con->prepare($sql1); $stmt->execute(); // Get count of rows to be displayed in table $stmt = $con->prepare($sql); $stmt->execute() ; $cnt = $stmt->fetch(PDO::FETCH_NUM); // retrieve one row at a time $i = 1; while($i <= $cnt){ $stmt = $con->prepare($sql2); $row->execute(array('')); // Do I need an array here? // from here on, I'm lost $i++; I'd appreciate any guidance you can provide or understandable tutorials you can point me to. Larry Hi, Hope somebody can help me because I am relatively new to PHP and I am currently unsure how to implement the following: Let's assume I have a table like this id_number, name, data1, data2. When displayed on HTML page: Column id_number should be hidden. Column name is a link. When you click on this column then value stored in id_number should be used in a query to database. Result should be displayed below the link on the same page. When clicked again data should hide. I have some idea how to toggle visibility with a simple javascript function. How do i populate the table with hidden data and then extract it later on? Any help or suggestions are appreciated. Thanks. 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 = ""; } ?> |