PHP - Check Existing Data Insert Into The Table?
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); ?> Similar TutorialsI have a table with lots of records. My table has the following field, with records containing either NULL or '1' that I need to modify. //database create table mydata ( id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, fname varchar(20), phoneno int(12) NOT NULL /*......*/ ); //class my data php <?php include('connect.php'); class InsertMydata { public function insertnow($fname, $phoneno) { $connect = new Connect; $insrt = $db -> prepare('INSERT INTO mydata (fname, phoneno) VALUES (?,?)'); $insrt -> execute(array($fname, $phoneno)); } } ?> //insernow validate form <?php include('../classs/mydata.php'); //Declare data and error arrays $errors = []; $mydara = []; if(!preg_match('/^[a-zA-Z]{4,15}$/', $_POST['fname'])) { $errors['fname'] = 'Enter full name!'; } //this block not working even the phone exist $connect = new Connect; $phoneno = $_POST['phoneno']; $checkiexist = $connect -> prepare('SELECT * FROM mydata WHERE phoneno = ?'); $checkiexist -> execute([$phoneno]); if($checkiexist->rowCount() > 0) { $errors['phonenoexist'] = 'Try another phone number!'; } if(!empty($errors)){ $data['success'] = false; $data['errors'] = $errors; }else{ $data['success'] = true; $data['message'] = 'success message!'; $mydata = new InsertMydata; $mydata -> insertnow($fname, $phoneno); } echo json_encode($data); ?> //my ajax $("#insertbtn").click( function(e) { var fname = $('#fname').val(), phoneno = $('#phoneno').val(), $.ajax({ url: 'insertnow.php', type: 'POST', data: {fname:fname, phoneno:phoneno}, dataType: "JSON", encode: true, }).done( function (data) { if (data.success == false) { if (data.errors.fname) { $('#fname').append('<p class="text-danger">' + data.errors.fname + '</p>'); } if (data.errors.phonenoexist) { $('.card-header').append('<div class="alert alert-info alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+data.errors.phonenoexist+'</div>'); } } else { $('.card-header').append('<div class="alert alert-success alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+data.message+'</div>'); } }); e.preventDefault(); }); //the problem is, the code insert data even if the phone exist why? the problem is, the code insert data even if the phone exist why? Edited April 8 by mahendaI have displayed check box values(ugroup field) from ugroups table.now what i want to do is,when user select multiple check boxes and submit it should be insert into relavent feild in table.now it's insert check boxes values.but not in relevant field.this is my code.Please help me.
//select ugroup's from group table. <?php $result = "SELECT id,ugroup FROM group"; $res_result = db::getInstance()->query($result); ?> <form action="db_sql/db_add_page.php" method="get"> Tittle :<input type="text" size="100" name="tittle" /> Description :<textarea cols="80" id="editor1" name="description" rows="10"></textarea> //Display ugroups in textboxes and checkboxes <?php while( $line=$res_result->fetch(PDO::FETCH_ASSOC)) { echo '<input type="checkbox" name="group[]" value=" '. $line['ugroup'] .'" />'; echo'<input type="text" name="ugroup" disabled="disabled" value=" '. $line['ugroup'] .'" size="7" "/>'; echo ' '; } ?><input type="submit" value="Submit"> </form>db_add_page.php if(isset($_POST)) { $tittle = $_POST['tittle']; $description = $_POST['description']; $ugroup = $_POST['group']; $acc_status = "INSERT INTO add_services (id,tittle,description,g1,g2,g3,g4,g5,g6,g7,g8) VALUES(NULL,'".$tittle."','".$description."','".$ugroup[0]."','".$ugroup[1]."','".$ugroup[2]."',' ".$ugroup[3]."','".$ugroup[4]."','".$ugroup[5]."','".$ugroup[6]."','".$ugroup[7]."')"; $rate = db::getInstance()->exec($acc_status); if(!$rate){ echo '<script type="text/javascript">alert("Update Error !");</script>'; }else{ header('Location:../add_page.php'); echo '<script type="text/javascript">alert("Successfuly Updated User Group !");</script>'; } }Attached Files group.jpg 22.14KB 0 downloads add_services.jpg 21.36KB 0 downloads 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 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. 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? 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"); } } ?> 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 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') 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 = ""; } ?> <?php if(!isset($_SESSION)) { session_start(); } // UNCOMMENT NEXT LINE TO PRINT THE $_SESSION ARRAY TO THE SCREEN . . . // echo '<pre>'; print_r($_SESSION); echo '</PRE>'; if(empty($_SESSION['userID']) || $_SESSION['authorized'] != true ) { header("Location: login.php"); exit; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html lang="EN" dir="ltr" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/xml; charset=utf-8" /> <meta http-equiv="refresh" content="5;url=editprofile.php"> <title>Saving Profile</title> </head> <body> <?php require_once ("dbconn.php"); ?> <?php $userID = $_SESSION['userID']; $insert_query = 'insert into users WHERE userID='$userID'( aim, msn, yim, psnID, xblGamertag, otherContact ) values ( "' . $_POST['aim'] . '", "' . $_POST['msn'] . '", "' . $_POST['yim'] . '", "' . $_POST['psnID'] . '", "' . $_POST['xblGamertag'] . '", "' . $_POST['otherContact'] . '" )'; mysql_query($insert_query); ?> Your profile has been saved! You will now be redirected from where you came from. <br /><a href="editprofile.php" title="Click here if you don't want to wait">Click here if you don't want to wait.</a> </body> </html> It creates a new record but I want it to update an existing one. It's an editprofile script. Hi I'm currently experiencing a problem with my query. I've used the `INSERT IGNORE` option in my query and it works pretty well not to add duplicates, but the problem is that if my unique field match it doesn't update any other info in the row, is there maybe another option to update a row if an existing field exists but insert new row if it doesn't exists?
my current query is as follow
$query = mysqli_query($con,"INSERT IGNORE INTO mxit (ip,time,user_agent,contact,userid,id,login,nick,location,profile) VALUES ('$ip','$post_time','$mxitua','$mxitcont','$mxituid','$mxitid','$mxitlogin','$mxitnick','$mxitloc','$mxitprof')") or die(mysqli_error($con)); I have made a form that asks a user for email, first name, last name, and password. I am using Spry validation tools in Dreamweaver. When I used those only, I did not have a problem. The problem began once I tried to actually check to see if the email was already registered. I have tried changing so many things like what $_POST variable to look for at the beginning, to different db connection arrangements. I am stumped. The only other thing I can think of is that I have the order wrong somehow in the logic. Thanks for the help. First, here is the form: Code: [Select] Enter Email<?php if($error_email_taken) echo ": $error_email_taken."; ?> <form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <input name="email" type="text" id="email" value="<?php if($_POST["email"]) echo $_POST["email"]; ?>"> <input name="first" type="text" id="first" value="<?php if($_POST["first"]) echo $_POST["first"]; ?>"> <input name="last" type="text" id="last" value="<?php if($_POST["last"]) echo $_POST["last"]; ?>"> <input name="pass" type="password" class="formText1" id="pass" value="<?php if($_POST["pass"]) echo $_POST["pass"]; ?>"> <input type="submit" name="Submit" value="Submit"></td> </form> And the email verification and insert, which is placed before the opening html tag. Code: [Select] <?php if($_POST['Submit']) { //Check to see if email is registered. $email = $_POST['email']; $dbc=mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); $q_1 = "SELECT users_email FROM table WHERE users_email = $email"; $r_1 = mysqli_query($dbc, $q_1); $rows_1 = mysqli_num_rows($r_1); if ($rows_1 == 0) { //If 0, email is not already registered. $new_email = $_POST['email']; } else { $error_email_taken = "This email is already registered."; } //If everything is good, insert the information. if(isset($new_email)) { $first_name = $_POST['first']; $last_name = $_POST['last']; $password = $_POST['pass']; //Insert User information. $q_2 = "INSERT INTO table (users_email, users_first, users_last, users_pass) VALUES ('$new_email', '$first_name', '$last_name', '$password')"; $r_2 = mysqli_query($dbc, $q_2); //Go to new page if form was submitted and information properly inserted. header('Location: new_page.php'); }//End: if($new_email) } //End: if $_POST['submit'] ?> I've simplified it as much as I could. I totally eliminated stuff like a password hash, etc. because I wanted to get it down to the most simple form, so once this gets working, I'll add that other stuff later. Thanks so much again. splobjectstorage.attach shows how to add an object inside the storage and associate it to some data. How should one replace the data associated to an object already in storage? All of the following solutions seem to work, however, I would like confirmation as I couldn't find and specific direction in the documentation. Assuming that detaching shown in my options 3 and 4 is not required, right? Probably option 2? Or, would it be best not to replace the data in storage, but add a shell object to the storage and update the data property? Use case is the object is a stream and the data is a specific type of client which can change over time. <?php class dataA{} class dataB{} class dataC{} class dataD{} class dataE{} class obj{} $storage = new SplObjectStorage(); $obj=new obj; $storage->attach($obj, new dataA); $data = $storage[$obj]; var_dump($data); //Option 1 $storage->attach($obj, new dataB); $data = $storage[$obj]; var_dump($data); //Option 2 $storage->offsetSet($obj, new dataC); $data = $storage[$obj]; var_dump($data); //Option 3 $storage->detach($obj); $storage->attach($obj, new dataD); $data = $storage[$obj]; var_dump($data); //Option 4 $storage->detach($obj); $storage->offsetSet($obj, new dataE); $data = $storage[$obj]; var_dump($data); object(dataA)#3 (0) { } object(dataB)#4 (0) { } object(dataC)#3 (0) { } object(dataD)#4 (0) { } object(dataE)#3 (0) { } Edited May 21, 2019 by NotionCommotion Added thought about not changing Hello everybody,
I have been racking my brain trying to decipher something that should be really simple for a seasoned programmer. Newbieprogrammer
<html>
function display($randomNr) I'm racking my brain trying to figure out the most effective way (any way) to insert some information into a table if it hasn't been previously inserted. Here's a simplified sample that I'm working with: -- Column 1 Column 2 Coloumn3 Sue Cat Adopted Jack Dog Adopted Cujo Dog Not Adopted -- The column I'm trying to scrub my loop against is column 3. Here's what I have so far... <?PHP $question = "ADOPTED"; $res = mysql_query("SELECT file FROM temp_data"); while($rw = mysql_fetch_array($res)){ $arr[] = $rw['file']; if (in_array($question, $arr)){ echo "ADOPTED"; //Leave it alone... } else { echo "NOT ADOPTED<br />"; //Insert My New Data } ?> I think I'm on the right path by using the 'in_array' function to check if '$question' variable is within the the '$arr' array, however, logically (to me) it makes sense but it is not working. Suggestions? I should also mention that I'm not receiving any error messages but rather, a completely inaccurate result instead. 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) ?> |