PHP - Table Field Is Equal To Another Tables Id Field
Hi,
I'm developing an app using flash AS2 as the front end via PHP and a mySQL database at the backend on my server. what i'm looking to do is update/insert into a table called 'cards' and at the same time update/insert into another table called 'jingle'. There is a field called 'cardID' in jingle that should be the same as the ID number created in 'cards' thus creating a link between entries in the different tables that can be called up as i choose. hope i've been clear i just wouldn't know where to start any help would be appreciated. MySQL client version: 5.0.91 PHPmyAdmin Version information: 3.2.4 thanks in advance Similar TutorialsThis is my first real jump into PHP, I created a small script a few years ago but have not touched it since (or any other programming for that matter), so I'm not sure how to start this. I need a script that I can run once a day through cron and take the date from one table/filed and insert it into a different table/field, converting the human readable date to a Unix date. Table Name: Ads Field: endtime_value (human readable date) to Table Name: Node Field: auto_expire (Converted to Unix time) Both use a field named "nid" as the key field, so the fields should match each nid field from one table to the next. Following a tutorial I have been able to insert into a field certain data, but I don't know how to do it so the nid's match and how to convert the human readable date to Unix time. Thanks in advance!. i have:
if( $stmt = $db_connect->prepare('UPDATE '.C_T_DRAGONS.' AS d, '.C_T_USERS.' AS u SET d.'.$prop.' = d.'.$prop.'+'.$val.', u.ap=u.ap-1 WHERE d.id = ? AND (SELECT u2.ap FROM '.C_T_USERS.' as u2 WHERE u2.id = ?) > 100') )which echoes out as: UPDATE dragons AS d, users AS u SET d.claws_dam = d.claws_dam+1, u.ap=u.ap-1 WHERE d.id = ? AND (SELECT u2.ap FROM users as u2 WHERE u2.id = ?) > 100and am getting the following response: Error : (1093) Table 'd' is specified twice, both as a target for 'UPDATE' and as a separate source for datawill this have to be done in 2 queries? did a little searching and im thinking maybe the subquery is being refused? Edited by BuildMyWeb, 04 December 2014 - 04:35 PM. Hi: I'm going crazy trying to do the following: I'm making a job registration process where the user registers on one php page to the website, must acknowlege and email receipt using an activate php page, then is directed to upload their C.V. (resume) based on the email address they enter in the active page output. I then run an upload page to store the resume in teh MySQL db based on the users email address in the same record. If I isolate the process of the user registering to the db, it works perfectly. If I isolate the file upload process into the db, it works perfect. I simply cannot upload teh file to the existing record based on teh email form field matching the user_email field in the db. With the processes together, teh user is activated, but teh file is not uploaded. Maybe I've simply been at this too long today, but am compeled to get through it by end day. If anyone can help sugest a better way or help me fix this, I will soo greatly appreciate it. My code is as follows for the 2 pages. ---------activate.php------- <?php session_start(); include ('reg_dbc.php'); if (!isset($_GET['usr']) && !isset($_GET['code']) ) { $msg = "ERROR: The code does not match.."; exit(); } $rsCode = mysql_query("SELECT activation_code from subscribers where user_email='$_GET[usr]'") or die(mysql_error()); list($acode) = mysql_fetch_array($rsCode); if ($_GET['code'] == $acode) { mysql_query("update subscribers set user_activated=1 where user_email='$_GET[usr]'") or die(mysql_error()); echo "<h3><center>Thank You! This is step 2 of 3. </h3>Your email is confirmed. Please upload your C.V. now to complete step 3.</center>"; } else { echo "ERROR: Incorrect activation code... not valid"; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <title>Job application activation</title> </head> <body> <center> <br/><br/><br/> <p align="center"> <form name="form1" method="post" action="upload.php" style="padding:5px;"> <p>Re-enter you Email : <input name="email" type="text" id="email"/></p></form> <form enctype="multipart/form-data" action="upload.php" method="POST"> <input type="hidden" name="MAX_FILE_SIZE" value="4000000"> Upload your C.V.: <input name="userfile" type="file" id="userfile"> <input name="upload" type="submit" id="upload" value="Upload your C.V."/></form> </p> </center> </body> </html> --------upload.php---------- <?php session_start(); if (!isset($_GET['usr']) && !isset($_GET['code']) ) { $msg = "ERROR: The code does not match.."; exit(); } if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0) { $fileName = $_FILES['userfile']['name']; $tmpName = $_FILES['userfile']['tmp_name']; $fileSize = $_FILES['userfile']['size']; $fileType = $_FILES['userfile']['type']; $email = $_POST['email']['user_email']; $fp = fopen($tmpName, 'r'); $content = fread($fp, filesize($tmpName)); $content = addslashes($content); fclose($fp); if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); } include 'reg_dbc.php'; $query = "UPDATE subscribers WHERE $email = user_email (name, size, type, content ) ". "VALUES ('$fileName', '$fileSize', '$fileType', '$content')"; mysql_query($query) or die('Error, query failed'); mysql_close($dbname); } ?> <center> <br/> <br/> <br/> <br/> Thank you for uploading your <?php echo "$fileName"; ?> file, completing your registration, and providing us your C.V. for this position. <br/> <br/> <br/> We will contact you if your canditature qualifies. </center> I want to select the user from super_administrators, administrators, teachers and students, and give the user permission based from what table he "came". But is giving the "Query failed" error... Code: [Select] <?php //Start session session_start(); //Include database connection details require_once('../config/config.php'); //Array to store validation errors $errmsg_arr = array(); //Validation error flag $errflag = false; //Connect to mysql server $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } //Select database $db = mysql_select_db(DB_DATABASE); if(!$db) { die("Unable to select database"); } //Function to sanitize values received from the form. Prevents SQL injection function clean($str) { $str = @trim($str); if(get_magic_quotes_gpc()) { $str = stripslashes($str); } return mysql_real_escape_string($str); } //Sanitize the POST values $email = clean($_POST['email']); $password = clean($_POST['password']); //Input Validations if($email == '') { $errmsg_arr[] = 'O campo Email nao foi preenchido.'; $errflag = true; } if($password == '') { $errmsg_arr[] = 'O campo Senha nao foi preenchido.'; $errflag = true; } //If there are input validations, redirect back to the login form if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; session_write_close(); header("location: ../index.php"); exit(); } //Create query $qry = "SELECT * FROM super_administrators,administrators,teachers,students WHERE email = '$email' AND passwd = '".md5($_POST['password'])."'"; $result = mysql_query($qry); $member = mysql_fetch_assoc($result); $table = mysql_field_table('$result', '0'); //Check whether the query was successful or not if($result) { if(mysql_num_rows($result) == 1) { if($table == 'super_administrators') { session_regenerate_id(); $_SESSION['SESS_ID'] = $member['id']; $_SESSION['SESS_NAME'] = $member['name']; $_SESSION['SESS_EMAIL'] = $member['email']; session_write_close(); header("location: ../users/sadmin/index.php"); exit(); } if($table == 'administrators') { session_regenerate_id(); $_SESSION['SESS_ID'] = $member['id']; $_SESSION['SESS_SCHOOL_ID'] = $member['school_id']; $_SESSION['SESS_NAME'] = $member['name']; $_SESSION['SESS_EMAIL'] = $member['email']; session_write_close(); header("location: ../users/admin/index.php"); exit(); } if($table == 'teachers') { session_regenerate_id(); $_SESSION['SESS_ID'] = $member['id']; $_SESSION['SESS_SCHOOL_ID'] = $member['school_id']; $_SESSION['SESS_NAME'] = $member['name']; $_SESSION['SESS_EMAIL'] = $member['email']; session_write_close(); header("location: ../users/prof/index.php"); exit(); } if($table == 'students') { session_regenerate_id(); $_SESSION['SESS_ID'] = $member['id']; $_SESSION['SESS_SCHOOL_ID'] = $member['school_id']; $_SESSION['SESS_CLASS_ID'] = $member['class_id']; $_SESSION['SESS_NAME'] = $member['name']; $_SESSION['SESS_REGISTRATION'] = $member['registration']; $_SESSION['SESS_EMAIL'] = $member['email']; session_write_close(); header("location: ../users/aluno/index.php"); exit(); } } else { $errmsg_arr[] = 'Suas informacoes de login estao incorreta. Por favor, tente novamente.'; $errflag = true; $_SESSION['ERRMSG_ARR'] = $errmsg_arr; session_write_close(); header("location: ../index.php"); exit(); } } else { die("Query failed"); } ?> Code: [Select] $new_array2=array_diff($my_array,$itemIds); $updatedb = mysql_query("UPDATE content_type_ads SET field_expire_value = '666' WHERE $new_array2 = field_item_id_value"); "$new_array2" has only 12 digit numbers for each item in the array, and I want to match them to the "field_item_id_value" field in the table, updating the "field_expire_value" field for the record where they match. I know I am close because the UPDATE code works before I add the WHERE statement (it of course adds '666' to EVERY field, but for a noobie it's a start!). (Another quite newbie...) I have already an online booking form. The Form works fine now and I would like to add on one more issue, but the code ignores what I want to check. I have 4 fields: arrival, departure, no. of persons and comments to check. Scenario 1: All field mentioned above are emtpty: Workes fine and message appears: "You have not provided any booking details". Scenario 2: If arrival (date_start) and departure (date_end) is entered, there should be at least an entry either in the field "comment", or in the field "pax". If not, there should be a message: "You have not provided sufficient booking details". INSTEAD: The booking request is sent, which should not be the case. The code is currently: # all fields empty : arrival, departure, pax and comments - error if(empty($data_start) && empty($data_end) && empty($pax)&& empty($comment)){ exit("You have not specified any booking details to submit to us. <br>Please use your browser to go back to the form. <br>If you experience problems with this Form, please e-mail us"); exit; } #If arrival and departure date is entered, there should be at least an entry either in the field "comment", or in the field "pax". if(!isset($data_start) && !isset($data_end) && empty($pax) && empty($comment)){ exit("You have not provided sufficient booking details. <br>Please use your browser to go back to the form. <br>If you experience problems with this Form, please e-mail us"); exit; } The form can be tested at http://www.phuket-beachvillas.com/contact-own/contact-it.php Can someone please check and tell me what's wrong with the code ? Thanks to anyone for any hint. Hi
I am very new to PHP & Mysql.
I am trying to insert values into two tables at the same time. One table will insert a single row and the other table will insert multiple records based on user insertion.
Everything is working well, but in my second table, 1st Table ID simply insert one time and rest of the values are inserting from 2nd table itself.
Now I want to insert the first table's ID Field value (auto-incrementing) to a specific column in the second table (only all last inserted rows).
Ripon.
Below is my Code:
<?php $con = mysql_connect("localhost","root","aaa"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("ccc", $con); $PI_No = $_POST['PI_No']; $PO_No = $_POST['PO_No']; $qry = "INSERT INTO wm_order_entry ( Order_No, PI_No, PO_No) VALUES( NULL, '$PI_No', '$PO_No')"; $result = @mysql_query($qry); $val1=$_POST['Size']; $val2=$_POST['Style']; $val3=$_POST['Colour']; $val4=$_POST['Season_Code']; $val5=$_POST['Dept']; $val6=$_POST['Sub_Item']; $val7=$_POST['Item_Desc']; $val8=$_POST['UPC']; $val9=$_POST['Qty']; $N = count($val1); for($i=0; $i < $N; $i++) { $profile_query = "INSERT INTO order_entry(Size, Style, Colour, Season_Code, Dept, Sub_Item, Item_Desc, UPC, Qty, Order_No ) VALUES( '$val1[$i]','$val2[$i]','$val3[$i]','$val4[$i]','$val5[$i]','$val6[$i]','$val7[$i]','$val8[$i]','$val9[$i]',LAST_INSERT_ID())"; $t_query=mysql_query($profile_query); } header("location: WMView.php"); mysql_close($con); ?>Output is attached. Lets say I want to get the name of the first field in a table (or the second) and assign it to a variable. i.e., if the first fieldname in a table is called "record_number", I would want: $first = "record_number"; Here's what I was able to come up with so far but not sure what to do next: $sql = "SELECT * FROM $tbl "; $result = mysql_query($sql) or die("Query failed : " . mysql_error()); $line = mysql_fetch_array($result, MYSQL_ASSOC); How should it look if I want to make a query where a field value should be lower than another field? Code: [Select] ....WHERE total_points<max_points"); I'm trying to create a search form where members of a site can search other members whose user information is stored in a mysql database. One of the search parameters is gender which searches for records from a column in the database called gender where members can either have the value "man" or "woman". The user can choose between 3 options from a pull down menu named gender (man, woman, both). Then I'm thinking about using a select query to search the database upon submission of the form, which goes something like this: Code: [Select] $sql= SELECT* FROM members WHERE gender ='{$_POST['gender']}' ; Now I can easily assign the value "man" for the option man in the pull down menu and "woman for the option woman, to match their corresponding names in the database. The problem lies with the "both" option which has to be either man or woman. I'm thinking about assigning it the value "man OR woman" so that when the form is submitted, the query would read: SELECT*FROM members WHERE gender ='{$_POST[man OR woman']}; I just don't know if this would be a right usage of the OR keyword and if such a query would work. Before trying it out, I'd like to know if this makes any sense and if not, what's an alternative way to work around this? I would like to echo field names in my table on webpage one by one. I know mySQL has "describe" function which will list the complete table, I am looking for a way to display each field name one by one with other stuff in between them like input field or description. Is there a way to duplicate all rows in a table AND change one field's value for each new row?
For example...
TABLE: comments
FIELDS:
commentid
userid
comment
weeknumber
Say there are only 5 comments in there like this (I have MANY rows, but keeping sample size small for example's sake)...
1-17-hello-3
2-41-hey-3
3-18-yo-3
4-67-sup-3
5-12-hola-3
I would like to duplicate them AND make the "weeknumber" = 4, so the table ultimately has 10 rows like this...
1-17-hello-3
2-41-hey-3
3-18-yo-3
4-67-sup-3
5-12-hola-3
1-17-hello-4
2-41-hey-4
3-18-yo-4
4-67-sup-4
5-12-hola-4
Is this doable?
Thanks...
Hi, when I submit a form I want to update a field in the "daterange" table. In the form the id field (RID) from "daterange" is selected prior to submit. Basically, I want to change the STATUS field to B (from A). The structure of daterange table is as follows: RID (key field) DEND MONTH DATE SITE PRICE STATUS What is the easiest way to accomplish this? Here is the code from the form (if it will help)... Code: [Select] <?php //************************************** // Page load dropdown results // //************************************** function getTierOne() { $result = mysql_query("SELECT DISTINCT MONTH FROM daterange") or die(mysql_error()); while($tier = mysql_fetch_array( $result )) { echo '<option value="'.$tier['MONTH'].'">'.$tier['MONTH'].'</option>'; } } //************************************** // First selection results // //************************************** if($_GET['func'] == "drop_1" && isset($_GET['func'])) { drop_1($_GET['drop_var']); } function drop_1($drop_var) { include_once('db.php'); $result = mysql_query("SELECT * FROM daterange WHERE DEND > DATE(NOW()) AND STATUS='A' AND MONTH='$drop_var' ORDER BY DATE, SITE") or die(mysql_error()); echo '<select name="RID"> <option value=" " disabled="disabled" selected="selected">Choose a Reservation</option>'; while($drop_2 = mysql_fetch_array( $result )) { echo '<option value="'.$drop_2['RID'].'">'.$drop_2 ['DATE']. ', '.$drop_2 ['SITE']. ', '.$drop_2 ['PRICE'].'</option>'; } echo '</select> '; echo "<br />"; echo "</select><p align=left><label><font size=\"2\" face=\"Arial\">First Name: <input type=\"text\" name=\"FNAME\" size=\"50\" maxlength=\"50\" tabindex=\"1\"<br />"; echo "<p align=left><label>Last Name: <input type=\"text\" name=\"LNAME\" size=\"50\" maxlength=\"50\" tabindex=\"2\"<br />"; echo "<p align=left><label>Address Line 1: <input type=\"text\" name=\"ADDR1\" size=\"50\" maxlength=\"50\" tabindex=\"3\"<br />"; echo "<p align=left><label>Address Line 2: <input type=\"text\" name=\"ADDR2\" size=\"50\" maxlength=\"50\" tabindex=\"4\"<br />"; echo "<p align=left><label>City: <input type=\"text\" name=\"CITY\" size=\"50\" maxlength=\"50\" tabindex=\"5\"<br />"; echo "<p align=left><label>State (abbrev.): <input type=\"text\" name=\"STATE\" size=\"2\" maxlength=\"2\" tabindex=\"6\"<br />"; echo "<p align=left><label>Zip Code: <input type=\"text\" name=\"ZIP\" size=\"5\" maxlength=\"5\" tabindex=\"7\"<br />"; echo "<p align=left><label>Contact Phone Number: (<input type=\"text\" name=\"PHONE1\" size=\"3\" maxlength=\"3\" tabindex=\"8\""; echo "<label>)<input type=\"text\" name=\"PHONE2\" size=\"3\" maxlength=\"3\" tabindex=\"9\""; echo "<label>-<input type=\"text\" name=\"PHONE3\" size=\"4\" maxlength=\"4\" tabindex=\"10\"<br />"; echo "<p align=left><label>Email: <input type=\"text\" name=\"EMAIL\" size=\"50\" maxlength=\"50\" tabindex=\"11\"<br />"; echo '<input type="submit" name="submit" value="Book Now!" /><br />'; echo '<input type="reset" name="submit" value="Reset" /><br />'; } ?> Hi everyone, I'm trying to create a site where teachers can upload educational animations (swfs) and source files (.fla's) to a site as a shared resource for others to use in their classrooms. I've concatinated a random number to both the source file and animation file to circumvent the problem of files with same names being uploaded. However, I have one small problem. The source file is not a mandatory upload, so sometimes the $source_file is null. However, with the random number concatinated, $source_fileX is not null. I tried to write some code saying that if $source_file is null, then $source_fileX should be null, else $source_fileX should be random_number concatinated with $source_file , but it doesn't seem to be working. The animation files are uploading fine. It's just the source files that are not. Nor is $source_fileX being inserted into the source_file field in the database. Code below. Thanks in advance. Code: [Select] <?php $keywords = $_POST["keywords"]; $subject = $_POST["subject"]; $description = $_POST["description"]; $website = $_POST["website"]; $firstname = $_POST["firstname"]; $lastname = $_POST["lastname"]; $school = $_POST["school"]; $animation_file = $_POST["animation_file"]; $source_file = $_POST["source_file"]; $random_digit=rand(00000, 9999); $animation_fileX=$random_digit . $_FILES['animation_file']['name']; if($animation_fileX!="") { if (!copy($_FILES['animation_file']['tmp_name'], "uploads/$animation_fileX")) { echo "failed to copy \n"; } } if ($source_file!="") { $source_fileX=$random_digit . $_FILES['source_file']['name']; } else { $source_fileX=""; } if($source_fileX!="") { if (!copy($_FILES['source_file']['tmp_name'], "source_file_uploads/$source_fileX")) { echo "failed to copy \n"; } } //**********************SEND TO DATABASE**************************** include 'mysql_connect.php'; $query = "INSERT INTO animation_uploads (date, animation_file, source_file, keywords, subject, description, firstname, lastname, school, website)" . "VALUES (NOW(), '$animation_fileX', '$source_fileX', '$keywords', '$subject' , '$description', '$firstname', '$lastname', '$school' , '$website')"; //if($query){echo 'data has been placed'} mysql_query($query) or die(mysql_error()); //***********************END OF DATABASE CODE*********************** Okay, so I'm trying to run a query to pull the information from a specific item that they click on in order to edit it. When I run an echo $query, though, it shows the field names rather than the information from the table. How can I make it so that it pulls the information rather than the field names? Here's what I have... <?php include("lib.php"); define("PAGENAME", "Edit Equipment"); if ($player->access < 100) $msg1 = "<font color=\"red\">"; //name error? $error = 0; $query = $db->execute("SELECT * FROM items WHERE id=?", array($_POST['id'])); echo "$id"; $result = mysql_query($query); echo "$query"; $data = mysql_fetch_assoc($result); $msg1 .= "</font>"; //name error? ?> Thanks!! Here is one part of php code. Here I try to show in last 1 month which dates exactly user made orders. When I run the SQL code in command prompt it works. I think problem is in while loop. Thanks beforhand for contribution. $query = "SELECT Date FROM orders WHERE User='$username' and DATE_SUB(CURDATE(),INTERVAL 30 DAY) <= Date;"; $result = mysql_query($query,$link_id) or die (mysql_error()); echo "<table border='1'> <tr> <td> Last 1 month's orders:</td> </tr>"; while($order_date = mysql_fetch_row($result)) { echo "<tr>"; echo "<td>" . $order_date[0] . "</td>"; echo "</tr>"; } echo "</table> I want to make a table for each paddler_id (Field) which exists into pushup Database My code for paddler_id = 1 is require "../sql.php"; $result = mysql_query("EXPLAIN pushup"); $r = mysql_query("SELECT * FROM paddlerinfo t1 LEFT JOIN pushup t2 on t2.paddler_id=t1.id LEFT JOIN practicedate t3 on t3.practice=t2.practice_id ORDER BY t1.firstname ASC "); $r1 = mysql_query("SELECT * FROM pushup where paddler_id =1 ORDER BY practice_id ASC "); echo "<table width='30%' border='1' cellpadding='0' cellspacing='0' style='font-family: monospace'>"; echo "<tr>"; echo "<td>DATE</td>"; while ($row = mysql_fetch_array($result)) { if (in_array($row["Field"], array("paddler_id", "practice_id", "p_id"))) continue; echo "<td>",($row["Field"]), "</td>"; } echo "</tr>"; while (($data = mysql_fetch_array($r1, MYSQL_ASSOC)) !== FALSE) { unset($data["p_id"],$data["paddler_id"]); echo "<tr>"; foreach ($data as $k => $v) { echo "<td>"; echo"$v"; echo "</td>"; } echo "</tr>"; } echo "</table>"; mysql_free_result($result); mysql_free_result($r); mysql_free_result($r1); mysql_close(); The problem is on line $r1 = mysql_query("SELECT * FROM pushup where paddler_id =1 ORDER BY practice_id ASC "); I want to put something which makes it paddler_id = X where x = 2,3,4,5... and x exists in database and do not print twice the x (because that database may have rows where x = same id How do i do that?? Hello Everyone, I have a PHP code that reads data from db table. Then it converts it into JSON and show it. However if data table field has - or so then it gives json error. For e.g. if($num > 0){ while($res = mysqli_fetch_array($query)){ $NDate = $res['NDate']; $Summary = substr($res['Summary'],0,256); /* CREATE ARRAY FOR SHORT TERM NEWSLETTER */ $newsletters[]=array('newsletter'=>array("RecID"=>$SNo,"Summary"=>$Summary)); } /* JSON OUTPUT*/ $json = array("AuthOK" => 'True',"newsletters"=>$newsletters); header('Content-type: application/json'); echo json_encode($json); How to solve the issue ?
Regards, Hi, I'm trying to get a number of different keywords from many table fields, and i want to count them according to the occurrence of each keyword, so it should be like (keyword1 occurred 10 times for example ). the problem is when i use count in for loop: Code: [Select] $tags = explode("|", $row[0]); $i=1; $count = 0; for($i; $i<count($tags); $i++){ print "$count {$tags[$i]}<br />"; $count++; } it counts the occurrence of key words in each field separately from the rest (i.e. Code: [Select] 0 day 1 night 0sun 1 moon 0 clouds 1 rain ) 2 keywords in each field (some other fields got more). I want the count to be more like: Code: [Select] 1 day 2 night 3 sun 4 moon 5 clouds 6 rain thanks |