PHP - Ugh. Data Not Getting Inserted Into Mysql Database.
Ugh. Ive been asking so many questions, betcha already know my name. Hahah.
Anyways, I know I already asked a question like this, but this is different. One of the values I am trying to insert into a database is simply not working. Here is the columnes in my mysql database: c_id commet story user date_added star Every value but 'commet' is getting inserted into database. NO error, no mysql errror. I have racked my brain trying to figure out what is wrong with the script. Here is my code: Code: [Select] <?php $idget = $_GET['id']; mysqlConnect(); //submit story if(isset($_POST['submit'])) { $com_form = mysql_real_escape_string(bb($_POST['commet'])); $rat_form = $_POST['rat']; $story_form = $idget; $user = $_SESSION['user']; $date = date("Y-m-d"); $query1 = " INSERT INTO story_commets(star, story, user, date_added, commet) VALUES($rat_form, '$story_form', '$user', '$date', '$com_form') "; mysql_query($query1) or die(mysql_error()); //} } // desplay reviews $query3 = " SELECT * FROM story_commets WHERE story = '$idget' ORDER BY date_added "; $select3 = mysql_query($query3) or die(mysql_error()); //$x=1; $ratav = array(); //if(mysql_num_rows($select3) == 0) //{ echo '<div id="message"> No Reviews Yet.... <>'; //} //else //{ while($rows3 = mysql_fetch_assoc($select3)) { $commetdb = $rows3['commet']; $user_com_db = $rows3['user']; $datedb = $rows3['date_added']; $stardb = $rows3['star']; //get profile picture $query4 = " SELECT * FROM login_info WHERE user = '$user_com_db' "; $select4 = mysql_query($query4) or die(mysql_error()); $rows4 = mysql_fetch_assoc($select4) or die(mysql_error()); $profile_pic = $rows4['profile_picture']; $user_id = $rows4['id']; echo " <div class='rev_cont'> <div class='info'> <img src='$profile_pic' /> <a href=?p=profile&id=$user_id> $user_com_db </a> <> <br /> <div class='rev'> <strong> $stardb/10 </strong> <br /> $commetdb <> <div id='date'> <em> Date Added: $datedb </em> <> <> <hr /> "; $ratav[]=$stardb; } $sum = array_sum($ratav); $count = count($ratav); $av = $sum / $count; $avf = round($av, 1); echo"<div id='message'> Rating Avarage: $avf /10 <>"; //} if (isset($_SESSION['user'])) { echo" <p> Did you like this story? Did you hate it? Give it a rating and let the author know!</p> <form action='?p=review&id=$idget' method='post' target='_self'> <label> Your rating is on a scale of 1-10 </label> <select name='rat'> <option> 1 </option> <option> 2 </option> <option> 3 </option> <option> 4 </option> <option> 5 </option> <option> 6 </option> <option> 7 </option> <option> 8 </option> <option> 9 </option> <option> 10 </option> </select> <label> Commets: </label> <textarea name='commet' cols='70' rows='9'></textarea> <input name='story' type='hidden' value='$idget' /> <br /> <input type='submit' value = 'Post' name='submit' /> </form> "; } else { echo "<div id='message'> Sign in to post a review! <>"; } ?> Here are the specifics if you want it. Here is the response part of the code: Code: [Select] <?php if(isset($_POST['submit'])) { $com_form = mysql_real_escape_string(bb($_POST['commet'])); $rat_form = $_POST['rat']; $story_form = $idget; $user = $_SESSION['user']; $date = date("Y-m-d"); $query1 = " INSERT INTO story_commets(star, story, user, date_added, commet) VALUES($rat_form, '$story_form', '$user', '$date', '$com_form') "; mysql_query($query1) or die(mysql_error()); //} } ?> Here is the form part of my code: Code: [Select] <?php if (isset($_SESSION['user'])) { echo" <p> Did you like this story? Did you hate it? Give it a rating and let the author know!</p> <form action='?p=review&id=$idget' method='post' target='_self'> <label> Your rating is on a scale of 1-10 </label> <select name='rat'> <option> 1 </option> <option> 2 </option> <option> 3 </option> <option> 4 </option> <option> 5 </option> <option> 6 </option> <option> 7 </option> <option> 8 </option> <option> 9 </option> <option> 10 </option> </select> <label> Commets: </label> <textarea name='commet' cols='70' rows='9'></textarea> <input name='story' type='hidden' value='$idget' /> <br /> <input type='submit' value = 'Post' name='submit' /> </form> "; } else { echo "<div id='message'> Sign in to post a review! <>"; } ?> Its probably something really mundane. HelP! Similar TutorialsHello everyone.
It seems like my code is not working properly.
i have tried both mysqli and PDO to insert data into database,but it only takes me back to same page again,without doing nothing in the database (been checking this a few times to be sure).
both php and html code are on the same page.
Could anyone point me to the missing link in my code?
here's my code (HTML & PHP) :
<form action="" id="SignUpForm" autocomplete="on" style="display:none" method="post"> <!-- Form is Hidden until the user is clicking the "Sign Up" button. --> <input type="hidden" name="Language" value="English"> Fill up the following fields:<br><br> First name:<input type="text" name="fname" required><br><br> Last name: <input type="text" name="lname" required><br><br> Age: <input type="number" name="UserAge" min="1" max="120" required><br><br> Gender: <input type="radio" name="Gender" value="male">Male<br> <input type="radio" name="Gender" value="Female">Female<br> E-mail Address: <input type="email" name="email" autocomplete="off" required><br><br> Pick your new password: <input type="password" maxlength=”40” name="Password" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,40}"> Add password strength checker here.<br><br> <!-- Uses regular expression. --> Confirm Password: <input type="password" maxlength=”40” name="ConfirmPassword" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,40}"><br><br> <!-- A better way is to use onblur to check user's type match. --> <hr> <script> (function(){ $("#submit").click(function(){ $(".error").hide(); //Bind an event handler to the "error" JavaScript event. var hasError = false; var passwordVal = $("#Password").val(); var checkVal = $("#ConfirmPassword").val(); if (passwordVal == '') { $("#Password").after('<span class="error">Please enter a password.</span>'); hasError = true; } else if (checkVal == '') { $("#ConfirmPassword").after('<span class="error">Please re-enter your password.</span>'); hasError = true; } else if (passwordVal != checkVal ) { $("#ConfirmPassword").after('<span class="error">Passwords do not match.</span>'); hasError = true; } if(hasError == true) {return false;} }); }); </script> <script> //The validationMessage property of a DOM node contains the message the browser displays to the user when a node's validity is checked and fails. document.getElementById("name").validationMessage; document.getElementById("lname").validationMessage; document.getElementById("UserAge").validationMessage; document.getElementById("Gender").validationMessage; document.getElementById("email").validationMessage; document.getElementById("Password").validationMessage; document.getElementById("ConfirmPassword").validationMessage; </script> Now let's go through your prefered food. Check the appropriate boxed beyond.<br><br> This will help us to better understand your food discipline:<br> <p style="text-align:center"><b> Meat And Poultry:</b></p> <div id="MeatCheckBox"> <input type="checkbox" name="FoodTypes[]" value="Hamburger">Hamburger<br> <input type="checkbox" name="FoodTypes[]" value="Steak">Steak<br> <input type="checkbox" name="FoodTypes[]" value="GroundBeef">Ground Beef<br> <input type="checkbox" name="FoodTypes[]" value="Bacon">Bacon<br> <input type="checkbox" name="FoodTypes[]" value="Beef">Beef<br> <input type="checkbox" name="FoodTypes[]" value="Salami">Salami<br> <input type="checkbox" name="FoodTypes[]" value="Chicken">Chicken (In all its forms)<br> <input type="checkbox" name="FoodTypes[]" value="NoMeat">I don't eat meat at all (Vegeterian/Vegan)<br> </div> <p style="text-align:center"><b> Fish And Seafood:</b></p> <div id="FishAndSeaFood"> <input type="checkbox" name="FoodTypes[]" value="Fish">Fish<br> <input type="checkbox" name="FoodTypes[]" value="Sushi">Sushi<br> <input type="checkbox" name="FoodTypes[]" value="CannedFish">Canned Fish<br> <input type="checkbox" name="FoodTypes[]" value="Oysters">Seafood<br> <input type="checkbox" name="FoodTypes[]" value="SmokedSalmon">Smoked Salmon<br> </div> <div id="Vegetables"> <p style="text-align:center"><b> Do you eat vegtables?</b></p><br> <input type="radio" name="YesOrNo" value="Yes">Yes <!-- Give both options the same name,Because they are related. --> <input type="radio" name="YesOrNo" value="No">No<br> </div> <hr> <p>Do you workout as part of your lifestyle?</p><br> <input type="radio" name='workout_options' value='valuable' data-id="DoWorkout" class="workout_options" /> I do workout occasionally <input type="radio" name='workout_options' value='valuable' data-id="DoNotWorkout" class="workout_options" /> I am not working out<br><br><br> <section> <div id=DoWorkout class="workout_options"><p>We see you're not having any exercise at the moment.<br><br>Did you know that doing some kind of activity like running or cardio 3 times a week improve your life quality?<br><br>We'll help you go straight from zero to hero!</p></div> <div id=DoNotWorkout class="workout_options">What type of workout you're working on at the moment? Please choose from the options beyond:<br><br><br> <input type="checkbox" name="Cardio" value="Cardio" data-id="Cardio"/>Cardio/Aerobics<br><br> <input type="checkbox" name=" Weight_Lifting" value=" Weight_Lifting" data-id="Weight_Lifting"/>Weight Lifting/ Anaerobics</div><br> </section> <input type="submit" value="Sign Up!" id="submit"> </div> </form>PHP/PDO: <?php // connnecting to MYSQL with PDO. // Connection data (server_address, database, username, password) $hostdb = 'localhost'; $namedb = 'caf_users'; $userdb = 'root'; $passdb = 'mypassword'; if (isset($_POST['SignUpButton'])) { $yesOrNo=$_POST["YesOrNo"]; $firstName=$_POST["fname"]; $lastName=$_POST["lname"]; $userGender=$_POST["Gender"]; $emailAddress=$_POST["email"]; //check if user entered the exact password twice. if ($_POST["password"] === $_POST["confirm_password"]) { $password=$_POST["password"]; $hash = password_hash($passwod, PASSWORD_DEFAULT);} // The first parameter is the password string that needs to be hashed, //and the second parameter specifies the algorithm that should be used for generating the hash. //encrypted by bcrypt algorithm. else { echo "Passwords are mismatched. Please try again."; }; $userAge=$_POST["UserAge"]; // Display message if successfully connect, otherwise retains and outputs the potential error try { $conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb); //Initiate connection witht the PDO object instance. $conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8 echo 'Connected to database'; // Define an insert query $sql = "INSERT INTO `users` ('Workout','first_name','last_name','gender','Email_Address','Password','User_Age') VALUES ($YesOrno,$fname,$lname,$Gender,$email,$password,$UserAge)"; $count = $conn->exec($sql); $conn = null; // Disconnect if($count !== false) echo 'Number of rows added: '. $count; } catch(PDOException $e) { echo $e->getMessage(); } } ?>Thank you in advance, Osher. Am a newbie in php. Since I can't insert values to the database with respect to a user Id or with any other token using WHERE clause. I.e "INSERT INTO receipts(date) VALUES(example) where id="**....." If I need to fetch several values of column for a particular user, how do I go about it? Thank you!!! Hello to all, I have problem figuring out how to properly display data fetched from MySQL database in a HTML table. In the below example I am using two while loops, where the second one is nested inside first one, that check two different expressions fetching data from tables found in a MySQL database. The second expression compares the two tables IDs and after their match it displays the email of the account holder in each column in the HTML table. The main problem is that the 'email' row is displayed properly while its while expression is not nested and alone(meaning the other data is omitted or commented out), but either nested or neighbored to the first while loop, it is displayed horizontally and the other data ('validity', 'valid_from', 'valid_to') is not displayed.'
Can someone help me on this, I guess the problem lies in the while loop? <thead> <tr> <th data-column-id="id" data-type="numeric">ID</th> <th data-column-id="email">Subscriber's Email</th> <th data-column-id="validity">Validity</th> <th data-column-id="valid_from">Valid From</th> <th data-column-id="valid_to">Valid To</th> </tr> </thead> Here is part of the PHP code:
<?php while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { echo ' <tr> <td>'.$row["id"].'</td> '; while ($row1 = $stmt1->fetch(PDO::FETCH_ASSOC)) { echo ' <td>'.$row1["email"].'</td> '; } if($row["validity"] == 1) { echo '<td>'.$row["validity"].' month</td>'; }else{ echo '<td>'.$row["validity"].' months</td>'; } echo ' <td>'.$row["valid_from"].'</td> <td>'.$row["valid_to"].'</td> </tr>'; } ?>
Thank you. hi guys, im new to this forum I'm new also to php, I need help from you guys: I want to display personal information from a certain person (the data is on the mysql database) using his name as a link: example: (index.php) names 1. Bill Gates 2. Mr. nice Guy i want to click Bill Gates (output.php) Name: Bill Gates Country:xxxx Age: xx etc. How can i make this or how to learn this? Hello all! I'm having a problem inserting an array into my database. My database is connected when I run the script but my table isn't being populated. Please help! Here's my table structure followed by the php: CREATE TABLE `demographic` ( `uid` bigint(20) unsigned NOT NULL, `first_name` varchar(50) default NULL, `last_name` varchar(50) default NULL, `email` varchar(200) default NULL, `link` varchar(255) default NULL, `affiliations` varchar(255) default NULL, `birthday` varchar(50) default NULL, `current_location` varchar(200) default NULL, `education_history` varchar(500) default NULL, `work` mediumtext, `hometown_location` varchar(400) default NULL, `interests` varchar(200) default NULL, `locale` varchar(50) default NULL, `movies` varchar(500) default NULL, `music` varchar(500) default NULL, `political` varchar(200) default NULL, `relationship_status` varchar(100) default NULL, `sex` varchar(10) default NULL, `tv` varchar(200) default NULL, `status` tinyint(4) default NULL, `created` datetime default NULL, `updated` datetime default NULL, PRIMARY KEY (`uid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; <?php $link = mysql_connect('host', 'user', 'pass'); if (!$link) { die('Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db('database'); if (!$db_selected) { die ('Can\'t use beta : ' . mysql_error()); } echo 'Connected successfully'; mysql_close($link); include_once "fbmain.php"; $config['baseurl'] = "baseurl"; //if user is logged in and session is valid. if ($fbme){ //collect some data using legacy api $param = array( 'method' => 'users.getinfo', 'uids' => $fbme['id'], 'fields' => 'birthday_date, interests, locale, political, relationship_status, affiliations', 'callback' => '' ); try{ $info = $facebook->api($param); } catch(Exception $o){ error_log("Legacy Api Calling Error!"); } //using graph api //array data $workInfo = getWorkInfoAsString($fbme); $education = getEducationAsString($fbme); $moviesArr = $facebook->api("/me/movies"); $musicArr = $facebook->api("/me/music"); $televisionArr = $facebook->api("/me/television"); //format some api data $movies = getArrayDataAsString($moviesArr['data']); $music = getArrayDataAsString($musicArr['data']); $television = getArrayDataAsString($televisionArr['data']); //data from legacy api $networks = ''; if (!empty($info[0]['affiliations'])){ $flag = true; foreach ($info[0]['affiliations'] as $item){ if (!$flag) $networks.= ' # '; $networks .= $item['name']; $flag = false; } } $now = date("Y-m-d G:i:s"); $insData = array( 'uid' => $fbme['id'], 'first_name' => $fbme['first_name'], 'last_name' => $fbme['last_name'], 'email' => isset($fbme['email']) ? $fbme['email'] : '', 'link' => $fbme['link'], 'affiliations' => $networks, 'birthday' => $info[0]['birthday_date'], 'current_location' => isset($fbme['location']['name']) ? $fbme['location']['name'] : '', 'education_history' => $education, 'work' => $workInfo, 'hometown_location' => isset($fbme['hometown']['name']) ? $fbme['hometown']['name'] : '', 'interests' => $info[0]['interests'], 'locale' => $info[0]['locale'], 'movies' => $movies, 'music' => $music, 'political' => $info[0]['political'], 'relationship_status' => $info[0]['relationship_status'], 'sex' => isset($fbme['gender']) ? $fbme['gender'] : '', 'tv' => $television, 'status' => '0', 'created' => $now, 'updated' => $now, ); $this->db->insert('demographic', $insData); } function getWorkInfoAsString($fbme, $delim = '#', $partDelim = ' | '){ $info = ""; $flag = false; if (empty($fbme['work'])) return ''; foreach($fbme['work'] as $item){ if ($flag) $info .= $partDelim; $flag = true; $info .= (isset($item['employer']['name']) ? $item['employer']['name'] : '' ). $delim . (isset($item['location']['name']) ? $item['location']['name'] : '' ). $delim . (isset($item['position']) ? $item['position']['name'] : '' ). $delim . (isset($item['start_date']) ? $item['start_date'] : '' ). $delim . (isset($item['end_date']) ? $item['end_date'] : '' ); } return $info; } function getEducationAsString($fbme, $delim = '#', $partDelim = ' | '){ $info = ""; $flag = false; if (empty($fbme['education'])) return ''; foreach($fbme['education'] as $item){ if ($flag) $info .= $partDelim; $flag = true; $info .= (isset($item['school']['name']) ? $item['school']['name'] : '' ). $delim . (isset($item['year']['name']) ? $item['year']['name'] : ''); } return $info; } function getArrayDataAsString($data, $delim = '#', $partDelim = ' | '){ $info = ""; $flag = false; foreach($data as $item){ if ($flag) $info .= $partDelim; $flag = true; $info .= $item['name']; } return $info; } ?> Hi, I am making a website where the user can create a login and he's then redirected to the secured pages this is working ok. Then I want the user who's not yet completely registered to enter his full name and credentials and store this data in the table Owner. however when I am trying to do this with the below mentioned code I don't get any output on error level and I don't get any data inserted in my table what am I missing here Code: [Select] <?php //session starten session_start(); ini_set('display_errors', 'On'); error_reporting(E_ALL | E_STRICT); print_r($_SESSION['user_id']); //database verbinding maken mysql_connect("127.0.0.1", "root", "pass")or die("cannot connect"); mysql_select_db("tobysplace")or die("cannot select DB"); //kijken of de gebruikers_id al gekend is in de tabel Owner $result = mysql_query("Select gebruiker_id from Owner where gebruiker_id ='".mysql_real_escape_string($_SESSION['user_id'])"'"); If(!$result){ $gebruiker_id = mysql_insert_id(); } else { $gebruiker_id = mysql_real_escape_string($_SESSION['user_id']); } //de gegevens van de eigenaar wegschrijven in de database $Owner_query="insert into Owner( name, lastname, email, address1, town, postcode, phone, gebruiker_id)values( '" . mysql_real_escape_string($_SESSION['name']) . "', '" . mysql_real_escape_string($_SESSION['lastname']) . "', '" . mysql_real_escape_string($_SESSION['email']) . "', '" . mysql_real_escape_string($_SESSION['address1']) . "', '" . mysql_real_escape_string($_SESSION['town']) . "', '" . mysql_real_escape_string($_SESSION['postcode']) . "', '" . mysql_real_escape_string($_SESSION['phone']) . "', '" . mysql_real_escape_string($_SESSION['user_id']) ."')"; // // de query uitvoeren $result=mysql_query($Owner_query) //foutcontrole or die("<b>A fatal MySQL error occured</b>.\n<br />Query: " . $Owner_query . "<br />\nError: (" . mysql_errno() . ") " . mysql_error()); print '<p>'.$_SESSION['name'].' U bent met succes ingeschreven op tobys-place</p>'; //} ?> If the user signs up and does not have an avatar, a default will be given to them. I am checking for the avatar/image file, however, that is not working. Here is the messy code below: if ($_SERVER['REQUEST_METHOD'] == 'POST') { // $username = $_POST['username']; // adds user info submitted upon registration to database function addUser($pdo) { $username = $_POST['username']; $password = password_hash($_POST['password'], PASSWORD_DEFAULT); $bio = $_POST['bio']; $email = $_POST['email']; $c_status = 0; $query = $pdo->prepare("INSERT into profiles001 (username, password, email, c_status, bio) VALUES (:username, :password, :email, :cstat, :bio)"); $query->bindValue(':username', $username); $query->bindValue(':password', $password); $query->bindValue(':email', $email); $query->bindValue(':cstat', $c_status); $query->bindValue(':bio', $bio); $file = $_FILES['userfile']; $file_name = $file['name']; $file_type = $file['type']; $file_size = $file['size']; $file_tmp_name = $file['tmp_name']; $file_error = $file['error']; if (!isset($_FILES['userfile'])) { $avatar = "assets/soap.jpg"; $avatar_present_query = $pdo->prepare("INSERT into profiles001 (avatar) VALUES (:avatar) WHERE username = ':username'"); $avatar_present_query->bindValue(':avatar', $avatar); $avatar_present_query->bindValue(':username', $username); $avatar_present_query->execute(); $query->execute(); } // $query->execute(); } addUser($pdo);
hello every body...
two
I'm creating an IPN in paypal for my membership site but the problem I'm facing is that on successfull verification of the purchase, four rows are getting inserted in the database...
The code is
<?php require '../db.php'; $paypalmode = '.sandbox'; $req = 'cmd=' . urlencode('_notify-validate'); foreach ($_POST as $key => $value) { $value = urlencode(stripslashes($value)); $req .= "&$key=$value"; } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://www'.$paypalmode.'.paypal.com/cgi-bin/webscr'); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_POSTFIELDS, $req); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: www'.$paypalmode.'.paypal.com')); $res = curl_exec($ch); curl_close($ch); if (strcmp ($res, "VERIFIED") == 0) { $transaction_id = $_POST['txn_id']; $payerid = $_POST['payer_id']; $firstname = $_POST['first_name']; $lastname = $_POST['last_name']; $payeremail = $_POST['payer_email']; $paymentdate = $_POST['payment_date']; $paymentstatus = $_POST['payment_status']; $mdate= date('Y-m-d h:i:s',strtotime($paymentdate)); $otherstuff = json_encode($_POST); $date = date("y-m-d"); $q = $pdo->connect()->query("INSERT INTO payment (mid,username,amount,paypal_id,txn_id,received_date) VALUES('{$_SESSION['user_id']}','{$_SESSION['uname']}','{$_POST['mc_gross']}','{$_POST['payer_email']}','{$_POST['txn_id']}','$date')"); $q->execute(); $q1 = $pdo->connect()->query("UPDATE members SET amount_loaded = amount_loaded + {$_SESSION['amount']} WHERE mid = '{$_SESSION['user_id']}'"); $q1->execute(); //header("Location: funds.php"); echo "verified"; } ?>two for the payment and in the members table, the amount is getting doubled. (i.e if anybody purchases For $2, it shows $4 in the database....) Any help will be really appreciated... After I've successfully inputted something in my script and then click refresh in Chrome with "Right Click -> Reload", the same thing that I've inputted before gets re-inserted AGAIN into the database, thus resulting in multiple versions of the same thing in the MySQL database. How can I prevent that? p.s. Chrome is warning with a pop up of repeated action, and when I then click continue the repeated insertion of the data occurs, and I'd like to prevent the repeated insertion. Hi Guys, actually I'm doing hard with this code. the fact is that Im inserting data (name, phone number, nss) and im doing a select to get the id number where nss is like $nss (. I don`t know why I can`t receive data, i think the fact is that all the code is inside an if statement) But that is why im here guys. In adittion I tryed to get the max id in order to print into mail function. But I couldn't . This is my code...
************************************************************************************************************ //Database connection done perfectly $mysqli = mysqli_connect( "****", "***", "***", "***");
************************************************************************************************************ // Im working with bots and the intent received is this, in addition i get variables correctly.
************************************************************************************************************ //here im inserting the variables in the correct order. The database is getting the values correctly too.
************************************************************************************************************
************************************************************************************************************
//here is the section when im going to select the id from the table, where the nss number is equal to the nss variable number that i've putted (but idk if the insert is done at this point....
************************************************************************************************************ For example i'm getting the mail, the name and lastname correctly from my function (which gets the parameters and turn the information in readable characters to php)
$to = $email; } ************************************CODE DONE ***********************************************************
So guys, Idk what is happening here, I tryed lot of things but when im get the email I dont get the id value..... I think is because the insert hasn't been completed while the if is open..... In adition I wanto to ask you guys if somebody knows how to get correctly the data from this code... Firstly I was trying to get the max id from my table and then plus 1 to increase the number. and in that order put the id by myself or atleast get the value in that way. I tryed closely, but i finish getting the array value.. I going to show my code...
function obtener_Id(){ I have tried to run my code and it works. I am not getting any error message but when I checked my database nothing was added. Code: [Select] <?php session_start(); include '../Database/connection.php'; if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br />"; } $filename = $_FILES["file"]["tmp_name"]; $fd = fopen ($filename, "r"); $data = fread ($fd,filesize ($filename)); fclose ($fd); $delimiter = "\n"; $output = explode($delimiter, $data); foreach($output as $var) { $tmp = explode(".", $var); $question = $tmp[0]; $choice1 = $tmp[1]; $choice2 = $tmp[2]; $choice3 = $tmp[3]; $choice4 = $tmp[4]; $answer1 = $tmp[5]; $answer2 = $tmp[6]; $answer3 = $tmp[7]; $answer4 = $tmp[8]; $sql = "INSERT INTO question SET Que_Question='$question', Que_Choice1='$choice1', Que_Choice2='$choice2', Que_Choice3='$choice3', Que_Choice4='$choice4', Que_Answer1='$answer1', Que_Answer2='$answer2', Que_Answer3='$answer3', Que_Answer4='$answer4', Tes_ID='$_SESSION[Tes_ID]'"; mysql_query($sql); } ?> My text file holds Quote What is the sky.where.how.wen.one.0.0.1.0 What colour.where.what.how.more.0.0.1.0 hello friends, actually i am trying to insert data in mysql database. here is my code <?php include_once("../includes/database.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Insert Product</title> </head> <body> <form action="insert_product.php" method="post" enctype="multipart/form-data"> <table align="center" width="600"> <tr align="center"> <td colspan="8"><h2> Insert New Post</h2></td> </tr> <tr> <td align="right"><b>Product Title :</b></td> <td><input type="text" name="product_title" size="50" style="background-color:#06C; color:#FFF" /></td> </tr> <tr> <td align="right"><b>Product Category :</b></td> <td> <select name="product_cat" style="background-color:#06C; color:#FFF" > <option>Select A Category </option> <?php $get_cats = "SELECT * FROM categories"; $run_cats = mysqli_query($con, $get_cats); while($row_cats = mysqli_fetch_array($run_cats)){ $cat_id = $row_cats['cat_id']; $cat_title = $row_cats['cat_title']; echo "<option value='$cat_id'>$cat_title</option>"; } ?> </select> </td> </tr> <tr> <td align="right"><b>Product Platform :</b></td> <td> <select name="product_brand" style="background-color:#06C; color:#FFF" > <option>Select A Platform </option> <?php $get_brands = "SELECT * FROM brands"; $run_brands = mysqli_query($con, $get_brands); while($row_brands = mysqli_fetch_array($run_brands)){ $brand_id = $row_brands['brand_id']; $brand_title = $row_brands['brand_title']; echo "<option value='$brand_id'>$brand_title</option>"; } ?> </select> </td> </tr> <tr> <td align="right"><b>Product Image :</b></td> <td><input type="file" name="product_image" /></td> </tr> <tr> <td align="right"><b>Product Price :</b></td> <td><input type="text" name="product_price" style="background-color:#06C; color:#FFF" /></td> </tr> <tr> <td align="right" valign="top"><b>Product Description :</b></td> <td><textarea name="product_desc" cols="50" rows="10" style="background-color:#06C; color:#FFF" ></textarea></td> </tr> <tr> <td align="right"><b>Product Keywords :</b></td> <td><input type="text" name="product_keywords" size="50" style="background-color:#06C; color:#FFF" /></td> </tr> <tr align="center"> <td colspan="8"><input type="submit" name="insert_post" value="Submit Now" /></td> </tr> </table> </form> </body> </html> <?php if(isset($_POST['insert_post'])){ $product_title = $_POST['product_title']; $product_cat = $_POST['product_cat']; $product_brand = $_POST['product_brand']; $product_price = $_POST['product_price']; $product_desc = $_POST['product_desc']; $product_keywords = $_POST['product_keywords']; $product_image = $_FILES['product_image']['name']; $product_image_tmp = $_FILES['product_image']['tmp_name']; move_uploaded_file($product_image_tmp,"product_image/$product_image"); $sql = "INSERT INTO products (product_cat,product_brand,product_title,product_price,product_desc,product_image,product_keywords) VALUES ('$product_cat','$product_brand','$product_title','$product_price','$product_desc','$product_image','$product_keywords')"; $query = mysqli_query($con, $sql); if($query){ echo "<script>alert('Product Has Been Inserted')</script>"; echo "<script>windoow.open('insert_product.php','_self')</script>"; exit(); }else{ echo "<script>alert('errror')</script>"; } } ?>but somehow its not inserting data into my table can somebody tell wherre m i doing mistake. the categories and brands are displaying from database. But its not inserting data here is my database script. <?php $con = mysqli_connect("localhost","root","","sg"); ?> Hi, I'm having trouble adding data to the database (test) that i created. I just can't see where I'm going wrong. need some other peoples opinions. I have tried taking the id out of the SQL statement completely as it is an auto increment, but that doesn't seem to work either. Thanks in advance... <?php $fname = $_POST['fname']; $sname = $_POST['sname']; $email = $_POST['email']; $pword = $_POST['password']; $gender = $_POST['gender']; $user_name = "root"; $password = ""; $database = "test"; $server = "127.0.0.1"; $db_handle = mysql_connect($server, $user_name, $password); $db_found = mysql_select_db($database, $db_handle); if ($db_found) { $SQL = "INSERT INTO members (id, fname, sname, email, password, gender) VALUES (NULL, $fname, $sname, $email, $pword, $gender);"; $result = mysql_query($SQL); mysql_close($db_handle); print "Thanks for joining us ".$fname."."; print "<br /><br />"; print $fname . "<br />"; print $sname . "<br />"; print $email . "<br />"; print $pword . "<br />"; print $gender . "<br />"; } else { print "Database NOT Found"; mysql_close($db_handle); } ?> Hello, I'm new to this forum and I need some help. I'm creating a simple database that it submits data from a user input. Unfortunatly, it's not sending any data to mysql also the form is not validating each field. Code: [Select] <?php if (isset($_POST['submitted'])){ $fields = array( 'email', 'state', 'district', 'gender', 'age', 'profession', 'survey', ); foreach($fields as $fieldName) { if(isset($_POST[$fieldName]) and trim($_POST[$fieldName]) !==''){ $fieldName = trim($_POST[$fieldName]); }else { $errors[] = "Please enter your". $fieldName .""; //code to validate fields } } if(isset($errors)){ require_once('Connections/encourage.php'); $query = "INSERT INTO participants (email, state, district, gender, age, profession, survey) VALUES ('$email', '$state', '$district', '$gender', '$age', '$profession','$survey')"; //databasse connection $result = mysql_query ($query); if ($result){ echo '<h1 id="mainhead">Thanks for submitting</hl> <p>You are now registered</p>'; exit(); }else{ echo '<h1 id="mainhead">System Error</hl> <p>Your registration could not be completed due to a system error We apologize for any incovience</p>';//gives system error echo 'p' . mysql_error(). '<br /><br />Query: ' . $query . '</p>'; exit(); } mysql_close(); } else { echo '<h1 id="mainhead">Error!</h1> <p class="error">The following error(s) occurred:<br />'; foreach($errors as $msg) { echo " - $msg<br/>\n"; } echo '</p><p>Please try again.</p><p><br/></p>'; } } ?> <form id="form1" name="form1" method="post" action"registration.php"> <fieldset class="first"> <label class="lableone" for="email">Email:* </label> <input name="email" value="<?php if(isset($_POST['email'])) echo $_POST['name'];?>"/> <label for="state"/>State:* </label> <input name="state" value="<?php if(isset($_POST['state'])) echo $_POST['state'];?>"/> <label for="schooldistrict"/>School District:* </label> <input name="schooldistrict" value="<?php if(isset($_POST['district'])) echo $_POST['district'];?>" /> <label for="gender">Gender:* </label> <select name="gender"> <option>Choose Your Gender</option> <option value="male" <?php echo ($form['gender'] == 'male' ? ' selected' : ''); ?>>Male</option> <option value="female"<?php echo ($form['gender'] == 'female' ? ' selected' : ''); ?>>Female</option> </select> <label for="age"/>Your Age:* </label> <input name="age" type="text" class="age" maxlength="2" value="<?php if(isset($_POST['age'])) echo $_POST['age'];?>" /> <label for="profession"/>Profession:* </label> <input name="profession" value="<?php if(isset($_POST['age'])) echo $_POST['age'];?>" /> <label for="surveys"/>Willingness to participate in future surveys: </label> <input name="surveys" type="checkbox" id="surveys" value="yes" <?php echo ($form['survey'] == 'yes' ? 'checked' : '');?>/> </fieldset> <fieldset> <input class="btn" name="submit" type="submit" value="Submit" /> <input class="btn" name="reset" type="reset" value="Clear Form" /> <input type="hidden" name="submitted" value="TRUE" /> </fieldset> </form> Can someone help me out? Thanks in advanced! I am trying to display data from mysql. Each row from the mysql database shows up under rows. I want the rows of data from mysql to appear in colums of 4. can some one help please. <?php $sql = 'SELECT * FROM dbtable ORDER BY id'; $result = $db->query($sql); $output[] = '<ul>'; while ($row = $result->fetch()) { $output[] = '<table>'; $output[] = '<tr>'; $output[] = '<td class="style10"><strong>'.$row['item'].'</strong></td>'; $output[] = '</tr>'; $output[] = '<tr>'; $output[] = '<td><img src="images/'.$row['pic'].'" width="100" height="150" /></td>'; $output[] = '</tr>'; $output[] = '<tr>'; $output[] = '<td>'.$row['description'].'</td>'; $output[] = '</tr>'; $output[] = '</table>'; } echo join('',$output); ?> I need to display the last 30 days entries from database in PHP and here is the code that i am currently using, but its not working. While entering the data in database, the date format that i am using is this... Code: [Select] $subon = date("F j, Y, g:i a"); And to display the code i am using this query... Code: [Select] $start_date = date("F j, Y, g:i a", strtotime('-30 days')); $curr_date = date("F j, Y, g:i a"); $sql = "SELECT * FROM table WHERE status = 'approved' AND subon BETWEEN '$start_date' AND '$curr_date' ORDER BY ID DESC LIMIT 0, 5"; And then i am using the usual stuff to display the data but its not working. Somebody please help me... Thanks in advance. Hi I have been trying to grab some data from an XML feed parse it and then insert it into a database. I will only need to do this on one occasion so no update or deletes. Sample of xml structu Code: [Select] <property> <id>34935</id> <date>2009-11-03 06:52:45</date> <ref>SVS0108</ref> <price>450000</price> <currency>EUR</currency> <price_freq>sale</price_freq> </property> Using xml2array class to parse the feed: <?php /** * xml2array Class * Uses PHP 5 DOM Functions * * This class converts XML data to array representation. * */ class Xml2Array { /** * XML Dom instance * * @var XML DOM Instance */ private $xml_dom; /** * Array representing xml * * @var array */ private $xml_array; /** * XML data * * @var String */ private $xml; public function __construct($xml = '') { $this->xml = $xml; } public function setXml($xml) { if(!empty($xml)) { $this->xml = $xml; } } /** * Change xml data-to-array * * @return Array */ public function get_array() { if($this->get_dom() === false) { return false; } $this->xml_array = array(); $root_element = $this->xml_dom->firstChild; $this->xml_array[$root_element->tagName] = $this->node_2_array($root_element); return $this->xml_array; } private function node_2_array($dom_element) { if($dom_element->nodeType != XML_ELEMENT_NODE) { return false; } $children = $dom_element->childNodes; foreach($children as $child) { if($child->nodeType != XML_ELEMENT_NODE) { continue; } $prefix = ($child->prefix) ? $child->prefix.':' : ''; if(!is_array($result[$prefix.$child->nodeName])) { $subnode = false; foreach($children as $test_node) { if($child->nodeName == $test_node->nodeName && !$child->isSameNode($test_node)) { $subnode = true; break; } } } else { $subnode = true; } if ($subnode) { $result[$prefix.$child->nodeName][] = $this->node_2_array($child); } else { $result[$prefix.$child->nodeName] = $this->node_2_array($child); } } if (!is_array($result)) { $result['#text'] = html_entity_decode(htmlentities($dom_element->nodeValue, ENT_COMPAT, 'UTF-8'), ENT_COMPAT,'ISO-8859-15'); } if ($dom_element->hasAttributes()) { foreach ($dom_element->attributes as $attrib) { $prefix = ($attrib->prefix) ? $attrib->prefix.':' : ''; $result["@".$prefix.$attrib->nodeName] = $attrib->nodeValue; } } return $result; } /** * Generated XML Dom * */ private function get_dom() { if(empty($this->xml)) { echo 'No XML found. Please set XML data using setXML($xml)'; return false; } $this->xml_dom = @DOMDocument::loadXML($this->xml); if($this->xml_dom) { return $this->xml_dom; } echo 'Invalid XML data'; exit; } } ?> My results page: <?php require_once('classes/xml2array.php'); require_once('conn.php'); function curlURL($url) { $ch= curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2) Gecko/20070219 Firefox/2.0.0.2'); $output = curl_exec($ch); return $output; } $curlResults = curlURL("http://localhost/alphashare_dump/property.xml"); $xml = $curlResults; $converter = new Xml2Array(); $converter->setXml($xml); $xml_array = $converter->get_array(); $array = ($xml_array['root']['property']); echo "<pre>"; print_r($array); echo "</pre>"; ////////////// INSERT DATA INTO DB //////////////////////////////////////////////////// ?> My array structure looks like this: Code: [Select] Array ( [0] => Array ( [id] => Array ( [#text] => 34935 ) [date] => Array ( [#text] => 2009-11-03 06:52:45 ) [ref] => Array ( [#text] => SVS0108 ) [price] => Array ( [#text] => 450000 ) [currency] => Array ( [#text] => EUR ) [price_freq] => Array ( [#text] => sale ) [part_ownership] => Array ( [#text] => 0 ) Can somebody help with actually getting this into some format that will enable me to insert this into my database please GT I have got connection to the the mysql database, how do I get the data from the database to display on the webpage I am having difficulty inserting the following codes values into my database. I know that the variables contain a value as I am displaying them on the output screen. Code: [Select] $link = mysql_connect($db_host,$db_user,$db_pass) or die('Unable to establish a DB connection'); mysql_select_db($db_database,$link); mysql_query("SET names UTF8"); $usr = $userid; $golfer = $_REQUEST['golfer']; $tourney = $_REQUEST['tournament']; $backup = $_REQUEST['backup']; date_default_timezone_set('US/Eastern'); $time = date("Y-m-d H:i:s"); $t_id=1; mysql_query("INSERT INTO weekly_picks (t_id, tournament, user, player, backup, timestamp) VALUES ('$t_id', '$tournament', '$usr', '$golfer', '$backup', '$time') or die('Error, insert query failed')"); echo $t_id; echo "<br />"; echo $tourney; echo "<br />"; echo $usr; echo "<br />"; echo $golfer; echo "<br />"; echo $backup; echo "<br />"; echo $time; echo "<br />"; echo $userdetail['email']; echo "<br />"; $to = $userdetail['email']; $subject = "Weekly Tournament Pick for: $tourney"; $message = "This email is to confirm your pick for $tourney has been received. Your pick is: $golfer. Your backup pick is: $backup The time it was submitted was $time Do not reply to this email, the mailbox does not exist. Contact me with any issues at xxxxxxx@xxxxxxx.com"; $from = "noreply@chubstersgcc.com"; $headers = "From:" . $from; mail($to,$subject,$message,$headers); ?> <div> <p>This is to confirm that your pick has been submitted for the following tournament: <?php echo $tourney; ?>. A confirmation of your pick as also been emailed to you.</p> <p>Your golfer: <?php echo $golfer; ?></p> <p>Your backup: <?php echo $backup; ?></p> <p>Your pick was submitted at: <?php echo $time; ?></p> </div> I have deleted mysql info for safety reasons. Here are the two webpage's codes i'm using right now menu.php <? session_start(); if(!session_is_registered(myusername)){ header("location:login.php"); } ?> <html><title>ChronoServe - Saving Time</title> <link href="style.css" rel="stylesheet" type="text/css"> <body> <table width="100%" border="0" cellpadding="0" cellspacing="0" class="container"> <tr> <td> <table width="335px" height="50%" border="1" align="center" cellpadding="0" cellspacing="0" class="centered"> <tr> <td> <form method="post" action="insertvalues.php"> <table width="100%" border="0" align="center" cellpadding="3" cellspacing="10"> <tr> <td colspan="2"><div align="center" class="font2">Activation Information</div></td> </tr> <tr> <td colspan="2"></td> </tr> <tr> <td width="40%" class="font3">First Name :</td> <td width="60%"> <div align="center"> <input name="firstname" type="text" class="font3" id="firstname" maxlength="25" /> </div></td> </tr> <tr> <td class="font3">Last Name :</td> <td> <div align="center"> <input name="lastname" type="text" class="font3" id="lastname" maxlength="25" /> </div></td> </tr> <tr> <td height="28" class="font3">Phone Number :</td> <td> <div align="center"> <input name="pnumber" type="text" class="font3" id="pnumber" maxlength="10" /> </div></td> </tr> <tr> <td class="font3">Personnel Activated :</td> <td> <div align="center"> <input name="numberactivated" type="text" class="font3" id="numberactivated" maxlength="3" /> </div></td> </tr> <tr> <td height="37" colspan="2"></td> </tr> <tr> <td colspan="2"><div align="center"> <input name="submit" type="Submit" class="font3" value="Submit" /> </div> </td> </tr> </table> </form></td> </tr> </table> </td> </tr> </table> </body> </html> insertvalues.php <?php if(isset($_POST['Submit'])) { $firstname = $_POST['firstname']; $lastname = $_POST['lastname']; $pnumber = $_POST['pnumber']; $numberactivated = $_POST['numberactivated']; mysql_connect ("deleted", "deleted", "deleted") or die ('Error: ' . mysql_error()); mysql_select_db ("deleted"); $query = "INSERT INTO disney_database (id, firstname, lastname, pnumber, numberactivated, date) VALUES ('NULL', '".$firstname."', '".$lastname."', '".$pnumber."', '".$numberactivated."', 'NULL')"; mysql_query($query) or die('Error updating database'); header("location:menu.php"); echo "Database Updated With: ".$firstname."" - "".$lastname."" - "".$pnumber."" - "".$numberactivated.""; } else { echo "Database Error" { ?> Here is my problem. I set a one <form> on every form field I have including the submit button. Now whenever I press the submit button it redirects to insertvalues.php which it should be doing. In insertvalues i told it to query the form data and post it into my database's table. Its not doing that and tells me that it has a database error which i set it to tell me if something goes wrong. Anyone can help me? BTW I can manually query in the information using sql with phpmyadmin. so can someone please review my code for me? thanks big help! You can see what is happening. Visit www.chronoserve.com The username and password are "admin" |