PHP - Get The Name Of The First Field In A Table
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); 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!. 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 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. 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...
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. 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*********************** 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?? Im not much of a coder, and I obviously did this wrong since it is not working. Im trying to bring a new field value in to an existing php file. I created a new table, and an admin page to control that field. I cant, however, figure out how to use that value in a different php file. Actually, there are 2 files. Each using a different field from that new table. I will post what my current code is below with the additions I tried to add. I bolded the lines that contain the tags Im trying to use. Any and help you can give in fixing this to make it work is greatly appreciated. Code: [Select] <?php # INCLUDE ALL NECESSARY FILES. include_once("Constants.php"); include_once("Database.php"); include_once("SiteSetting.php"); [b]$query = "SELECT arcade_multiplier FROM tbl_point_rewards"; mysql_query($query) or die("Invalid query". mysql_error() ); $result = mysql_fetch_array($result); $arcade_multiplier = $result["arcade_multiplier"];[/b] $dbObj = new database(); # SAVE ARCADE GAME POINTS INTO THE DATABASE function saveGamePoints( $game_id, $user_id, $game_score, $calculate_score_flag, $play_date ){ global $dbObj; $user_max_plays = getUserMaxPlaysLimit( $user_id, $game_id ); //$_SESSION["arcade_game"]["save_score"] = ($user_max_plays < $_SESSION["arcade_game"]["max_plays"]) ? "yes" : "no" ; if($user_max_plays < $_SESSION["arcade_game"][$_SESSION["url_gameid"]]["max_plays"]){ $total_points = calculatePointRatio($game_id, $game_score); //$total_points = $game_score; $x_gameid = md5($game_id); if($_SESSION["arcade_game"][$x_gameid]["play_time"] > 0){ $playTime['start'] = $_SESSION["arcade_game"][$x_gameid]["play_time"]; $playTime['end'] = time(); $playTime = ($playTime['end'] - $playTime['start']); } else { $playTime = 0; } # update total points into main score [b] $update_sql = "update tbl_users set points_gained = (points_gained+(".ceil($total_points)." * $arcade_multiplier)) where usrid={$user_id}";[/b] $rs = mysql_query($update_sql) or die("Invalid query: {$update_sql} - ". mysql_error()); $table = "tbl_arcade_game_score"; $fields = array("game_id", "user_id", "game_score", "calculate_score_flag", "play_date", "game_time"); $values = array($game_id, $user_id, $game_score, $calculate_score_flag, $play_date, $playTime); // return $dbObj->cgi( $table, $fields, $values, 1 ); $insertid = $dbObj->cgi( $table, $fields, $values, "" ); $ceiling_point = getCeiling($game_id); if($game_score >= $ceiling_point) { $chk_authourity = isAlreadyTrophyOwner($user_id, $game_id); //if($chk_authority < 1) if($chk_authourity < 1) { # store award details into the database (tbl_trophy_award) //$trophy_id = getTrophy( $game_id ); $trophy = getTrophyDetails($game_id); $trophy_id = $trophy['ctoon_id']; $tbl_fields = array('userid', 'game_id', 'award_date', 'trophy' ); $tbl_values = array($user_id, $game_id, $play_date, $trophy_id ); $insert_tbl_trophy_award_id = $dbObj->cgi('tbl_trophy_award', $tbl_fields, $tbl_values , "" ); # award trophy to user (tbl_users_ctoons) $table = "tbl_users_ctoons"; $fl = array("usrid", "ctoon_id", "del_status", "ctoons_auction", "auction_id", "location", "batpts"); $vl = array($user_id, $trophy_id, '0', '', 0, 1, 0); $dbObj->cgi($table, $fl, $vl , "" ); # send a pm to the user about the trophy include_once("send_pm_message.php"); $game = getGameDetails($game_id); $msgSub = "Grats! You just got a trophy!"; $message = "Grats! You got the ".$trophy["toon_name"]." trophy for the ".$game["game_name"]." game!<br> <img src=\"{$game['path']}\">"; //echo $message; //echo "<br><hr><br>"; sendMessage($user_id, 0, 0, $msgSub, $message, 1); sendMessage(2034, $user_id, 0, $msgSub, $message, 1); } } return $insertid; } }//end function function getCeiling($game_id) { $sql = "SELECT ceiling FROM tbl_game WHERE game_id = '".$game_id."'"; $rs = mysql_query($sql); $result = mysql_fetch_assoc($rs); return $result['ceiling']; } function isAlreadyTrophyOwner($user_id, $game_id) { $sql = "SELECT * FROM tbl_trophy_award WHERE game_id = {$game_id} and userid = {$user_id}"; $rs = mysql_query($sql); $num_rows = 0; $num_rows = mysql_num_rows($rs); if($num_rows > 0) { return $num_rows; } else { return $num_rows; } } # calculate game ratio function calculatePointRatio($game_id, $game_score){ //return $game_score; $sql = "select gs.* from arcade_game_setting as gs where gs.game_id={$game_id}"; $rs = mysql_query($sql) or die( "Invalid query". mysql_error() ); if($rs){ $row = mysql_fetch_array($rs); switch($row["calculation_type"]){ case "divide": $x_score = round($game_score / $row["r_no"]); break; case "multiply": $x_score = round($game_score * $row["r_no"]); break; default : $x_score = ceil($game_score); break; }//switch $row["r_no"]; if($row["game_cap"] > 0){ if($x_score > $row["game_cap"]){ $x_score = $row["game_cap"]; } } return $x_score; }//if }// end function # get user total plays function getUserMaxPlaysLimit($user_id, $game_id){ global $d_start_time, $d_end_time; $sql = "select * from tbl_arcade_game_score where user_id={$user_id} and game_id={$game_id} and play_date between {$d_start_time} and {$d_end_time}"; $rs = mysql_query($sql) or die("Invalid query :". mysql_error() ); if($rs){ return mysql_num_rows($rs); }//if } # get game details function getGameDetails($game_id){ $sql = "select g.game_id, g.game_name, g.award_ctoonid, c.toon_name, c.toon_cat, c.toon_subcat, c.toon_small_img from tbl_game as g, tbl_ctoon as c where g.game_id = {$game_id} and g.award_ctoonid=c.ctoon_id"; $rs = mysql_query($sql); if($rs){ $row = mysql_fetch_array($rs); if($row['toon_cat']!="" && $row['toon_subcat']!=0) $tpth="imgtoon/".$row['toon_cat']."/".$row['toon_subcat']."/thumb"; elseif($row['toon_cat']!="" && $row['toon_subcat']==0) $tpth="imgtoon/".$row['toon_cat']."/thumb"; $game["game_name"] = $row["game_name"]; $game["award_ctoon_id"] = $row["award_ctoonid"]; $game["toon_name"] = $row["toon_name"]; $game["path"] = SITEROOT ."/" . $tpth ."/" . $row["toon_small_img"]; return $game; } else { return false; } } # send pm message to winner function sendPMToWinner($user_id, $game_id, $game_score){ include_once("send_pm_message.php"); $g = $game_id; //$point_prize = calculatePointRatio($game_id, $game_score); $point_prize = $game_score; $game = getGameDetails($game_id); //# select ctoon //$sql = "select award_ctoonid from tbl_game where game_id=".$g; //$rsctoon = mysql_query($sql) or die("Invalid query: {$sql} - ". mysql_error()); //$row_ctoon = mysql_fetch_array($rsctoon); //$ctoon_id = $row_ctoon["award_ctoonid"]; //# award ctoon //$insert_user_ctoon = "insert into tbl_users_ctoons (usrid, ctoon_id, del_status, ctoons_auction, auction_id, location, batpts) //values('{$user_id}', '{$ctoon_id}', '0', '', '', '1', '0')"; //mysql_query($insert_user_ctoon) or die("Invalid insert query:".mysql_error() ); //# update points $update_points_sql = "update tbl_users set points_gained = (points_gained+1500) where usrid={$user_id}"; mysql_query($update_points_sql) or die("Invalid updates points query". mysql_error() ); $dbObj = new database(); $msgSub = "Grats! You got a Top Score for ".$game["game_name"]." !"; $message = "Grats! You had one of the Top 10 scores in the ".$game["game_name"]." game last month, and got a 1500 point bonus!<br>"; //<img src=\"{$game['path']}\">"; // echo $message; // echo "<br><hr><br>"; sendMessage($user_id, 0, 0, $msgSub, $message, 1); } /** * function getTrophy( $game_id ) * @param $game_id */ function getTrophy( $game_id ){ $sql = "select award_ctoonid from tbl_game where game_id=".$game_id; $rs = mysql_query( $sql ) or die( mysql_error() ); if( $rs ){ $row = mysql_fetch_assoc( $rs ); } return $row["award_ctoonid"]; } // Updated function from above // Will get more information about the trophy function getTrophyDetails($game_id) { $sql = "select b.ctoon_id,b.toon_name,b.toon_small_img from tbl_game as a,tbl_ctoon as b where a.game_id = '$game_id' and b.ctoon_id = a.award_ctoonid LIMIT 1"; $rs = mysql_query( $sql ) or die( mysql_error() ); if( $rs ){ $row = mysql_fetch_assoc( $rs ); } return $row; } ?> Code: [Select] <?php include_once("Constants.php"); include_once("Database.php"); include_once("SiteSetting.php"); /**************************************************/ # SAVE DONETION IN DATABASE # @param $uid # @param $donation_amt /**************************************************/ function saveDonetion($uid, $donation_amt, $transaction_id, $subscr_id='', $type){ if($transaction_id != "") { $flag = checkExist($uid); if($flag > 0){ updateDonetion($uid, $donation_amt, $transaction_id, $subscr_id='', $type); }else{ addDonetion($uid, $donation_amt, $transaction_id, $subscr_id='', $type); } } } /**************************************************/ /**************************************************/ # CHECK IS RECORD EXITS IN DONETION TABLE # @param $uid /**************************************************/ function checkExist($uid){ $dbObj = new database(); $sql = "select user_id from tbl_donation where user_id={$uid}"; $dbObj->myquery($sql); if($dbObj->row_count > 0){ return $dbObj->f_user_id; }else{ return 0; } } /**************************************************/ /**************************************************/ # INSERT DONETION RECORD IN tbl_donation # @param $uid # @param $donation_amt /**************************************************/ [b]$query = "SELECT arcade_multiplier FROM tbl_point_rewards"; mysql_query($query) or die("Invalid query". mysql_error() ); $result = mysql_fetch_array($result); $arcade_multiplier = $result["arcade_multiplier"];[/b] function addDonetion($uid, $donation_amt, $transaction_id, $subscr_id='', $type){ $dbObj = new database(); $months = floor($donation_amt / 5); $exp_time = mktime(date("H"),date("i"),date("s"),date("m") + $months,date("d"),date("Y")); $fields = array("transaction_id", "subscr_id", "user_id", "donation_amt", "donation_date", "exp_date", "donation_type", "transaction_details"); $values = array($transaction_id, $subscr_id, $uid, $donation_amt, time(), $exp_time, $type, serialize($_SESSION["recurring_td"])); # update points [b]$update_points_sql = "update tbl_users set points_gained = (points_gained+(($donation_amt / 5) * $donation_pts)) where usrid={$uid}";/[b] mysql_query($update_points_sql) or die("Invalid updates points query". mysql_error() ); if($donation_amt < 5){ // The user donated less than $5 }else{ upgradeAccount($uid); } return $dbObj->cgi("tbl_donation", $fields, $values, false); } /**************************************************/ /**************************************************/ # UPDATE EXISTING DONETION RECORD # @param $uid # @param $donation_amt /**************************************************/ function updateDonetion($uid, $donation_amt, $transaction_id, $subscr_id='', $type){ if(strlen($subscr_id) > 0){ $cd = " AND subscr_id='".$subscr_id."'"; } $sql_select = "select exp_date, donation_amt from tbl_donation where user_id=".$uid; //$sql_select = "select exp_date, donation_amt from tbl_donation where user_id=".$uid." and donation_type like '%recurring%'"; $rs_select = mysql_query($sql_select) or die("Invalid query".mysql_error()); if($rs_select){ $row = mysql_fetch_array($rs_select); $expdt = $row["exp_date"]; $damt = ($row["donation_amt"] + $donation_amt); $months = floor($donation_amt / 5); $exp_time = mktime(23, 59, 59, date("m",$row["exp_date"]) + $months, date("d", $row["exp_date"]), date("Y", $row["exp_date"])); } $dbObj = new database(); $sql = "update tbl_donation set transaction_id='".$transaction_id."', donation_amt=(donation_amt + {$donation_amt}), donation_date = ".time().", exp_date=".$exp_time.", donation_type='".$type."', transaction_details='".serialize($_SESSION["recurring_td"])."' where user_id={$uid}"; # update points [b]$update_points_sql = "update tbl_users set points_gained = (points_gained+(($donation_amt / 5) * $donation_pts)) where usrid={$uid}";[/b] mysql_query($update_points_sql) or die("Invalid updates points query". mysql_error() ); $dbObj->myquery($sql, 1); if($donation_amt < 5){ // The user donated less than $5 }else{ upgradeAccount($uid); } } /**************************************************/ /**************************************************/ # UPDATE EXISTING RECURRING DONETION RECORD # @param $uid # @param $donation_amt /**************************************************/ function updateRecurringDonetion($subscr_id, $transaction_amt){ $sql_subscr = "select donation_id, transaction_id, user_id from tbl_donation where subscr_id = '".$subscr_id."'"; $rs_subscr = mysql_query($sql_subscr) or die("Invalid query".mysql_error()); if(strlen($rs_subscr) > 0){ $row_subscr = mysql_fetch_assoc($rs_subscr); $uid = $row_subscr["user_id"]; $donation_amt = $transaction_amt; $transaction_id = $row_subscr["transaction_id"]; $subscr_id = $subscr_id; $type = "Recurring"; updateDonetion($uid, $donation_amt, $transaction_id, $subscr_id='', $type); } } /**************************************************/ /**************************************************/ # UPDATE USER STATUS FROM STANDERED TO PREMIUM # @param $uid /**************************************************/ function upgradeAccount($uid){ $dbObj = new database(); $sql = "UPDATE tbl_users SET acc_type = 'P' WHERE usrid={$uid} LIMIT 1 "; # update points $update_points_sql = "update tbl_users set points_gained = (points_gained+0) where usrid={$uid}"; mysql_query($update_points_sql) or die("Invalid updates points query". mysql_error() ); $dbObj->myquery($sql, 1); }//function upgradeDonation($uid) ?> I'm trying to add ui autocomplete functionality to some fields in a form and am running into a few issues. The first is I want to be able to both add and pull multiple values from the one field. I had originally thought I could comma delimit the values and handle it that way, but it seems it's a bit more complicated than that. I've tried to explode the value but it doesn't go far enough, I think I need to find a way to refine the array down by trying to replace the comma in the code somehow. Here's my current php code: <?php //connection information $host = "localhost"; $user = "myuser"; $password = "mypass"; $database = "mydb"; $param = $_GET["term"]; //make connection $server = mysql_connect($host, $user, $password); $connection = mysql_select_db($database, $server); //query the database $query = mysql_query("SELECT cb_activities FROM jos_comprofiler WHERE cb_activities REGEXP '^$param'"); //build array of results for ($x = 0, $numrows = mysql_num_rows($query); $x < $numrows; $x++) { $row = mysql_fetch_assoc($query); $activities[$x] = array(cb_activitiesterm => $row[cb_activities]); } //echo JSON to page $response = $_GET["callback"] . "(" . json_encode($activities) . ")"; echo $response; mysql_close($server); ?> Someone else had mentioned maybe using something like this: $string="([{\"cb_activitiesterm\":\"Kicking Cats, Working\"},{\"cb_activitiesterm\":\"Web Development\"}])"; $one=str_replace("([{\"cb_activitiesterm\":\"","",$string); $two=str_replace("\"},{\"cb_activitiesterm\":\"",",",$one); $three=str_replace("\"}])","",$two); echo $three; // now you can explode it ... by commas $items=explode(",",$three); But of course the problem here is he's creating the string in the php file and adding the /'s when in reality this needs to be pulled from the database and then refined. The values are currently formatted like this: ([{"cb_activitiesterm":"Kicking Cats, Working"},{"cb_activitiesterm":"Web Development"}]) Exploding simply adds a "" around the comma so it won't work. I need it to format like this: ([{"cb_activitiesterm":"Kicking Cats"},{"cb_activitiesterm":"Working"},{"cb_activitiesterm":"Web Development"}]) My second issue is I need to be able to pass multiple values into the hidden input in the script and adding a comma/space between each value. Currently if you click another value it simply replaces the prior value with the next one. Here's my script: Code: [Select] <div id="editcbprofile"> <div id="formWrap"> <div id="activities" class="ui-helper-clearfix"> <input id="cb_activitiesterm" type="text"> <input id="cb_activities" name="cb_activities" type="hidden"> </div> </div></div> <script type="text/javascript" src="autocomplete/js/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="autocomplete/js/jquery-ui-1.8.custom.min.js"></script> <script type="text/javascript"> $(function(){ //attach autocomplete $("#cb_activitiesterm").autocomplete({ //define callback to format results source: function(req, add){ //pass request to server $.getJSON("autocomplete/autocom.php?callback=?", req, function(data) { //create array for response objects var suggestions = []; //process response $.each(data, function(i, val){ suggestions.push(val.cb_activitiesterm); }); //pass array to callback add(suggestions); }); }, //define select handler select: function(event, ui) { //create formatted activity var activity = ui.item.value, span = $("<span>").text(activity), a = $("<a>").addClass("remove").attr({ href: "javascript:", title: "Remove " + activity }).text("x").appendTo(span); //add interest to activities div span.insertBefore("#cb_activitiesterm"); //add activity to hidden form field $('input[name=cb_activities]').val(activity); }, //define select handler change: function() { //prevent 'to' field being updated and correct position $("#cb_activitiesterm").val("").css("top", 2); } }); //add click handler to activities div $("#activities").click(function(){ //focus 'to' field $("#cb_activitiesterm").focus(); }); //add live handler for clicks on remove links $(".remove", document.getElementById("activity")).live("click", function(){ //remove current activity $(this).parent().remove(); //add activity to hidden form field $('[name=cb_activities]').val().remove(); //correct 'to' field position if($("#activities span").length === 0) { $("#cb_activitiesterm").css("top", 0); } }); }); </script> And then my 3rd issue is if you remove a value it needs to also remove it from the hidden input. I've tried several attempts of the remove() in the onclick function but I can't get it to remove it. Lol other than that it's cherry. Any advice on any of these would be great. 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 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 have members DOB stored in a mysql table field called birthday in the following format YYYY-MM-DD I can't seem to convert the time stamp into the members age I need to be able to feed $birthday which is the field in mysql table that is in the above format and then use php code to convert to members age Everything I try doesn't seem to work 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!! 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, 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> Alright, I looked though the read me's, went over the FAQ's... Think it is time to post...
So, this lump is what I got from going though google and piecing together the bits that looked good.
<?php $db_host = "****"; $db_user = "****"; $db_pwd = "****"; $database = "****"; $table = "****"; $query = "SELECT * FROM {$table}"; $conn = mysqli_connect($db_host, $db_user, $db_pwd, $database); $result = mysqli_query($conn,$query) or trigger_error($query . ' - has encountered an error at:<br />' . mysqli_error($conn)); $fields = mysqli_fetch_fields($conn); $field_count = mysqli_num_fields($conn); echo '<table border="1" style="width:100%">' . "\n" . '<tr>'; $i = 0; foreach($fields as $field) { if(++$i == 1) { echo '<th colspan="' . $field_count . '">' . $field->table . '</th></tr><tr>'; } echo "\n" . '<th>' . $field->name . '</th>'; } echo '</tr>'; while($row = mysqli_fetch_row($result)) { echo '<tr><td>' . implode('</td><td>' , $row) . '</td></tr>'; } echo '</table>'; ?>The goal is to display the table and conditionally format the contents. Let's forget about the conditional part (thinking if/than but don't know how I'm going to do that yet) and focus on the key problem: displaying the table. I have tested this code. It works...to a point. it displays the table and its contents but no headers. I know my issue is in line 20 and 22 but I can not for the life of me figure it out. If it is stupidly easy (for you) please remember that I am not a coder. At best I am a scripter when it comes to linux. I am over my head on this stuff. Thank you all for any help you can give me Edited by TheAlmightyOS, 18 November 2014 - 03:30 PM. Hi Good day Can someone pls help me regarding with this matter. I have a page for inserting records. And I have a combobox that is fetched through the specific field in database. I also have a table of records, for each row i have an href edit which throws the values to its respective texbox and combobox. THE PROBLEM is that when i click the href edit, the value from a selected row was not displayed from the combobox I want to loop through a MySQL table, and perform a calculation based on the current row the loop is on and the previous loop. Say my table has 2 columns - Film_id and FilmRelease, how would I loop through and echo out a calculation of the current FilmRelease and the previous row's column value? Thanks guys I have got to this stage, but for some reason it's not printing out anything Code: [Select] <?php mysql_connect("localhost", "****", "*****") or die(mysql_error()); mysql_select_db("*****") or die(mysql_error()); $sql = mysql_query("SELECT FilmRelease FROM Films_Info") or die(mysql_error()); $last_value = null; while ($row = mysql_fetch_assoc($sql)) { if (!is_null($last_value)) { print date_diff($row['FilmRelease'], $last_value) . "<BR>"; } $last_value = $row['FilmRelease']; } |