PHP - Saving To A Sql Database Using Php And Wamp
Hi guys
Im looking to save the contents of 4 textboxes to a mySql db. Using wamp, phpmyadmin etc. Code: [Select] ?php $Name = $_Post('Name'); $Age = $_Post('Age'); $Sex = $_Post('Sex'); $Address_1 = $_Post('Address_1'); mysql_connect("127.0.0.1","user","") or die ('Error: ' .mysql_error()); mysql_select_db("user"); $query ="INSERT INTO users(Name,Age,Sex,Address_1) VALUES('".$Name."', '".$Age."','".$Sex."','".$Address_1."'); mysql_query($query) or die ('Error updating datadase'); mysql_Close(); ?>This is the code im using, it dosent seem to do anything to the database..... can someone point out where im going wrong... thanks Similar TutorialsHi, I'm still new to php and having some problems. Sorry about the code not being formatted properly. The snippet I posted has both the code intend to work but it is commented out and a test version that has an array already set thus getting rid of the need of setting up every thing like I have. Ok this is basically my problem. I'm building a store like website. Its suppose to be very basic for now Part of the website is an RMA system where the customer enters an order number and then pulls up all items in the order on a different page in a table format with check boxes next to each item found in the database. Each item that is checked off is then saved to an array rma[] which posts to another page when submitted. What this page(copied down below) does is it pulls values from the cookie already made and creates new variables which is not a problem. After that it does a foreach loop for the array of the items into a mysql query which then is suppose to insert it into a database. When the code runs it only inserts the first item in the array into the database no matter how many items are in the array. When I echo the $insert statement I get this(using the test code) like I expect I'm suppose to. I would assume that because I'm doing a foreach loop that it is doing an INSERT for the number of items in the array. Quote INSERT INTO `project`.`rma` (rmanumber, AccountID, item, ordernumber) VALUES ('857442', '1','Saab','123') INSERT INTO `project`.`rma` (rmanumber, AccountID, item, ordernumber) VALUES ('857442', '1','Volvo','123') INSERT INTO `project`.`rma` (rmanumber, AccountID, item, ordernumber) VALUES ('857442', '1','BMW','123') INSERT INTO `project`.`rma` (rmanumber, AccountID, item, ordernumber) VALUES ('857442', '1','Toyota','123') Code: [Select] <?php //connects to the data base mysql_connect("localhost", "root", "") or die(mysql_error()); mysql_select_db("project") or die(mysql_error()); /* //retrieving rma array from previous page $rmarequest = $_POST['rma']; //retieves using name from cookie $username = $_COOKIE['ID_my_site']; //retrieves order number from cookie $ordernumber = $_COOKIE['order']; //creates rma number $rmanumber = rand(1000, 999999); //retrieves accountid from database using the username $getid = mysql_query("SELECT AccountID FROM users WHERE username = '$username'"); $id = mysql_fetch_array( $getid ); //takes the value of $id $final = $id['AccountID']; //suppose to loop through all values for the array created by $request on the previous page and insert into database foreach($rmarequest as $key){ // $insert = "INSERT INTO `project`.`rma` (rmanumber, AccountID, item, ordernumber) VALUES ('".$rmanumber."', '".$AccountID."','".$key."','".$ordernumber."')"; //mysql_query($insert) OR die(mysql_error()); //this is test to see what is being passed to mysql server $insert = "INSERT INTO `project`.`rma` (rmanumber, AccountID, item, ordernumber) VALUES ('".$rmanumber."', '1','".$key."','123')"; //mysql_query($insert) OR die(mysql_error()); //to view what $insert is passing to the data base. echo $insert;} */ //THIS SECTION IS TEST ONLY //test array $cars[0]="Saab"; $rmarequest[1]="Volvo"; $rmarequest[2]="BMW"; $rmarequest[3]="Toyota"; //creates rma number $rmanumber = rand(1000, 999999); foreach($rmarequest as $key){ //this is test to see what is being passed to mysql server $insert = "INSERT INTO `project`.`rma` (rmanumber, AccountID, item, ordernumber) VALUES ('".$rmanumber."', '1','".$key."','123')"; mysql_query($insert) OR die(mysql_error()); //to view what $insert is passing to the data base. echo $insert."<br />"; } ?> Included is a copy of the table and the php code above. (I looked at the appropriate forums to put this in, but it seems I couldn't find a forum section specifically for this problem) Yesterday PHP on WAMP was working perfectly. So I shutdown the computer, go to sleep, and wake up and turn WAMP on. But for some odd reason, when none of my PHP files are loading properly. It just shows all the code as if it were a .txt file. Any reasons for this? I keep trying to install every wordpress, or php web server software I can find, the lastest being WAMP. Nothing ever works. I feel like a complete retard here being that I can't even set up a stupid program, to be ABLE to program myself. Everything I install gives me a 404 not found error when I try to load the admin index page to a browser. I honestly have no friggn clue what is going on, I know syntax pretty decently for a lot of these languages, but as far as setting them up, I might as well just shoot myself. I know they can't make it any easier with these step by step tutorials, but it just doesn't seem to work on my comp.
Each time i try to open WAMP's phpmyadmin so i can create a database it has this ERROR #1045 - Access denied for user 'root'@'localhost' (using password: NO) how do i fix it Code: [Select] <?php exec('java -jar/MicroChatServer.jar',$output); print_r($output); ?> Hello frds......... I have chat prg. jar file and I have to integrate this chat in a PHP website uses Wampserver.... I try above code but it display "Array()" instead of execute jar file. What should I do???? Any idea?????????????// I get a "No database selected" error whenever I submit information on my register.php page, which is: <?php include_once('includes/config.php'); include_once('functions.php'); $return_content = AccountRelated(null, null, 3); ?> <html> <head> <link rel="stylesheet" type="text/css" href="style/style.css" /> <title><?php echo $title; ?></title> </head> <body> <div class="logo"><a href="index.php"><img src="style/images/logo.png" border="0"></a></div> <center> <div class="background"> <div class="container"> <?php echo $return_content; ?> </div> </div> </center> </body> </html> But after I click submit, I get the "No database selected" error, but using WAMP, I include config.php which holds the following details: <?php $title = "NovaUpload - File Uploader"; mysql_connect("localhost", "", ""); mysql_select_db("data"); ?> And if functions.php is required, he <?php function AccountRelated($username, $password, $query_type) { if($query_type == 1) { $set_query = mysql_query("SELECT COUNT(d.username), u.date, u.username FROM uploads d, users u WHERE d.username = '$username' AND u.username = '$username' LIMIT 1") or die(mysql_error()); //user must not exist if(mysql_num_rows($set_query) == 0) { $content_return = 'Sorry, no information was found'; } else { $grab = mysql_fetch_assoc($set_query); //login information if($grab['COUNT(d.username)'] > 0) { $welcome_return = "You have uploaded ". $grab['COUNT(d.username)'] ." files. You've registered on ". $grab['u.date'] ."!"; } else { $welcome_return = "You have uploaded 0 files. You've registered on ".$grab['date'] . "!"; } } } elseif($query_type == 2) { $set_query = mysql_query("SELECT title,views,downloads,description,username,date FROM uploads LIMIT 20"); if(mysql_num_rows($set_query) == 0) { $content_return = "Sorry, there are currently no files uploaded to view."; } else { //display all files while($row = mysql_fetch_assoc($set_query) == 0) { echo $row['title']."<br/>"; } } } elseif($query_type == 3) { $username = mysql_real_escape_string($_POST['username']); $password = sha1(sha1(md5($_POST['password']))); if(!$username || !$password) { $return_content = "All fields are required! <table><form action='register.php' method='POST'> <tr><td>Username</td><td><input type='text' name='username' maxlength='20'></td></tr> <tr><td>Password</td><td><input type='text' name='password' maxlength='30'</td></tr> <tr><td><input type='submit' value='Register'></td></tr> </form></table>"; } else { $set_query = mysql_query("SELECT username FROM users WHERE username = '$username' LIMIT 1"); if(mysql_num_rows($set_query) == 0) { $return_content = "You have successfully registered the account ". $username ." with the password ". $_POST['password'] ."!"; mysql_query("INSERT INTO users VALUES (null, '$username', '$password', 0, 0, '". date("M-d-Y") ."', '". $_SERVER['REMOTE_ADDR'] ."')") or die(mysql_error()); } else { $return_content = "An account with this username already exists."; } } return $return_content; } else { //nothing to process } } ?> Hi, My program works on WAMP (PHP Version 5.5.12) running on my machine. However, the same program will not run on remote server (PHP Version 5.4.32). Basically, I'm trying to insert values obtained from a form into a database. I've checked and rechecked the table I'm inserting into and I can't find anything wrong with it. The trouble is it's hard to debug a PHP program. Unlike, say, C++ which requires a compiler, you can trace the program line by line to look for errors. That's not possible with PHP and makes it so much harder to look for faults. The relevant functions used to send data to database are shown below. insert() is returning false every time and I can't understand why! I wonder if anyone can suggest where things might be going wrong. I would be very grateful. public function insert($table, $fields = array()) { if(count($fields)) //true if $fields holds data { $keys = array_keys($fields); $values = ''; //to put inside query $x = 1; foreach($fields as $field) { $values .= '?'; if($x < count($fields)) { $values .= ', '; } $x++; } $sql = "INSERT INTO {$table} (`".implode('`, `', $keys) . "`) VALUES({$values})"; if(!$this->query($sql, $fields)->error()) { return true; } } return false; } public function query($sql, $darams = array()) { $this->_error = false; //reset error if($this->_query = $this->_pdo->prepare($sql)) { $x = 1; if(count($darams)) { foreach($darams as $param) { $this->_query->bindValue($x, $param); $x++; } } if($this->_query->execute()) { $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ); $this->_count = $this->_query->rowCount(); } else //an error has occured in SQL query { $this->_error = true; } } return $this; } public function error() { return $this->_error; } public function count() { return $this->_count; } Okay, so I keep crashing my server while trying to get a simple script to run. Firstly, here's the code. <?php $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = ''; $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql'); $dbname = 'businessletters'; mysql_select_db($dbname); $files = getFiles("parseme.txt"); for($i=0;$i<200;$i++) { $file = getReadFile($files[$i][0]); insertIntoDb($files[$i][1], $file); //echo "Inserted successfully - " . $files[$i][0] . "<br />"; } function getFiles($file) { $fh = fopen($file, "rb"); $data = fread($fh, filesize($file)); fclose($fh); $dataArr = explode("\n", $data); for($i=0;$i<count($dataArr);$i++) { $dataArr[$i] = explode(",", $dataArr[$i]); } return($dataArr); } function getReadFile($file) { $fh = fopen($file, "rb"); $data = fread($fh, filesize($file)); fclose($fh); return $data; } function insertIntoDb($title, $body) { $sql = "insert into letters values('', '".mysql_real_escape_string($title)."', '".mysql_real_escape_string($body)."')\n"; //mysql_query($sql) or die("Error inserting"); echo $sql; } mysql_close(); ?> And now, here's what it's supposed to do. Open and read File A - this file has file names and titles in a CSV file. File,Title is the format. Then the loop starts. Here I would like to do everything in one run, which could be done by counting the records in the CSV file, which I can do with count(), but even 200 is too much. I have 600. Anyway, it goes through the CSV file and opens every file referenced and pulls out the content. Then it creates a simple SQL statement where the content is entered into the database. And the problem is that Apache keeps crashing on me... There must be a better way for me to do this without having my server crash on me! hey guy, <p>I'm kind of new to php , and I need you to help me. I have developed a website im lamp. I don't how to get that working in wamp/ xamp . <i>Please tell me how to do it.<i> </p>
I'm currently trying to building a websocket widget, using node package manager(NPM),WAMPserver and electronjs. now i am getting this error ( ! ) Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'talos342c'@'localhost' (using password: YES) in C:\wamp\www\myNewweb\storescripts\connect_to_mysql.php on line 19 Call Stack # Time Memory Function Location 1 0.0008 380440 {main}( ) ..\index.php:0 2 0.0012 384880 include( 'C:\wamp\www\myNewweb\storescripts\connect_to_mysql.php' ) ..\index.php:11 3 0.0012 385528 mysql_connect ( ) ..\connect_to_mysql.php:19 This topic has been moved to PHP Applications. http://www.phpfreaks.com/forums/index.php?topic=309461.0 Hi Guys, how to execute batch file in wamp server php code. Could you please help on that.
I am attempting to install PEAR however am very confused and I believe I have stuffed up something from which it will be very complicated to come back from. Firstly, for some reason I have the C:\wamp\bin\php\php5.3.0\go-pear.bat installation file, but I also have the C:\PHP\go-pear.bat installation file. Which one do I choose? And is the C:\PHP direcotry left over from an old installation. I have no idea. Further to that, I ran the go-pear.bat installation from the C:\PHP directory, I have a feeling this was the wrong decision. After installing everything it stated that it had updated my php.ini file, however this file was in the wrong directory and so I took the updated lines from the php.ini which put in a a new include_path and pasted them into the php.ini file in the C:\wamp... directory. Now when I go to the command prompt and type in pear here is the message I get: PHP_PEAR_PHP_BIN is not set correctly. Please fix it using your environment variable or modify the default value in pear.bat The current value is: .\php.exe I have followed a remedy to this which is included he http://www.pear-forum.org/topic2413.html However still to no avail. I am further confused why I have a C:\PHP folder and why it is seperate from my WAMP folder. Further to that, when I try to install PEAR from my WAMP folder and click on C:\wamp\bin\php\php5.3.0\go-pear.bat I get the following error message: phar "C:\wamp\bin\php\php5.3.0\PEAR\go-pear.phar" does not have a signaturePHP warning require_once(phar://go-pear.phar/index.php>: failed to open stream: phar error: invalid url or non-existent phar "phar://go-pear.phar/index.php" in C:\wamp\bin\php\php5.3.0\PEAR\go-pear.phar n line 1236 (and another message that looks very similar) ----- Note: the installation instructions I am following are located here > http://trac.symfony-project.org/wiki/HowToInstallPearOnWindowsWithWamp ------ So basically I am stuck. Why is it so difficult to install PEAR and how do I simply get it working? I am trying a very simple thing , just to run an exe on local WAMP environment.The code below launches does launch notepad(can see in task manager) but doesn't show up.I want test.txt to be opened in a window. <?php $WshShell = new COM("WScript.Shell"); $oExec = $WshShell->Run("notepad.exe C:\wamp\www\test.txt", 3, true); ?> I have tried exec as well .Same problem.What modifications are needed? I have been working on a blog program with a tag system. When I add tags and ask to display them to a certain webpage they all appear on my WAMP environment but not my live server. Any thoughts as to why this might be? Here is the code needed to display the tags. I am not sure if maybe live servers have restrictions that might be stopping it from displaying.
This is on the main page to display the tags.
<div class="widget"> <?php echo '<h2>Tags</h2>'; echo '<ul>'; getTagCount($DBH); echo '</ul>'; ?> </div>Next here is the function from the includes file. function getTagCount($DBH) { //Make the connection and grab all the tag's TAG TABLE HAS TWO FIELDS id and name $stmt = $DBH->query("SELECT * FROM tags"); $stmt->execute(); $result = array(); $result = $stmt->fetchAll(); //For each row pulled do the following foreach ($result as $row){ //set the tagId and tagName to the id and name fields from the tags table $tagId = $row['id']; $tagName = ucfirst($row['name']); //Next grab the list of used tags BLOG_POST_TAGS TABLE HAS TWO FILEDS blog_post_id and tag_id $stmt2 = $DBH->query("SELECT count(*) FROM blog_post_tags WHERE tag_id = " . $tagId); $stmt2->execute(); $tagCount = $stmt2->fetchColumn(); //Print the following list echo '<li><a href="blog_tags.php?tagId=' . $tagId . '"title="' . $tagName . '">' . $tagName . '(' . $tagCount . ')</a></li></form>'; //End of loop - start again } }The "tags" database is structured like so id, name The "blog_post_tags" is structured like so, blog_post_id, tag_id On the WAMP server it returns all of tags while the live server only returns the first one. Any suggestions on what is going on? If you need any other info please let me know. Hi, I have a mail script to that will take a long time to process, let me call it form2.php Now I post from form1.php to form2.php. I like to run/execute the form2.php in the background so that the user will not wait for the time executing the form2.php. I have used exec and shell_exec but not success. I am using latest WAMP server in my local mechine. Thanks Hi, when I run my script I get the following error message. These are array variables I am passing into the playerAttack function. I can't figure out what is wrong it looks fine to me. Any help greatly appreciated. Thanks. Derek Code: [Select] attack posted Fatal error: Cannot use string offset as an array in C:\wamp\www\SUN_DRAGON_GAME\gamestart.php on line 202 Code: [Select] $currentMonster='octalisk'; ///////////////////////////////////////////////////////////battle//////////////////////////// //function monsterEncounter($echoMonster,$monsterImage) if(!empty($_POST['attack'])) { echo "attack posted"; playerAttack($currentMonster,$player['stats']['playerHitRollLow'],$player['stats']['playerHitRollHigh'], $player['stats']['playerDmgLow'],$player['stats']['playerDmgHigh'],$monsters['Ocean']['octalisk']['defense'],$monster['Ocean']['octalisk']['hp'],$player['faction']['Teardrop_Ocean_Protectors']); $doesItAttack=encounter($monsters['ocean']['octalisk']['seeInvis'],$monsters['ocean']['octalisk']['aggro'],$player['factions']['Teardrop_Ocean_Protectors']); //insert octalisk stats into monsterattack function. if($doesItAttack =='yes') { monsterAttack($currentMonster,$monsters['Ocean']['octalisk']['hitRollLow'],$monsters['Ocean']['octalisk']['hitRollHigh'] , $monsters['Ocean']['octalisk']['dmgLow'],$monsters['Ocean']['octalisk']['dmgHigh'], $player['stats']['playerDefense'],$player['stats']['playerHp'],$monsters['Ocean']['octalisk']['hp']); } else { echo "do nothing"; } } here is the attack function Code: [Select] function playerAttack($currentMonster,$hitRollLow,$hitRollHigh,$dmgLow,$dmgHigh,$monsterDefense, $monsterHp,$playerFaction) { echo "in player attack"; $playerRoll= rand($playerHitRollLow, $playerHitRollHigh); if($playerHitRoll>=$monsterDefense) { global $theMessage; //shit had to make it global $playerDamage= rand($playerDmgLow,$playerDmgHigh); $theMessage = "You have hit a ". $currentMonster." for "."<strong>". $playerDamage."</strong> points of damage!"; $monsterHp= $monsterHp- $playerDamage; $theMessage.=" The ".$currentMonster."'s hp is now ".$monsterHp; if($monsterHp<=0) { if($playerFaction<=0) { $theMessage="Your faction standing with ".$playerFaction. "could not possibly get any worse."; } } $theMessage.=" You have killed the ".$currentMonster. "Your faction standing with ".$playerFaction." is now ".$playerFaction-1; } else { global $theMessage; //WTF i dont know what im doing. $theMessage= " Whoa! You missed the ".$currentMonster; } } <?php shell_exe ("172.18.9.25\photoshop\photoshop.exe"); ?> When I run this from the server computer program opening. But when i tried from a diferent computer it is only downloading the exe file to the client computer. How can I open the application from a diferent computer in the same network. hello all i am building a small forum website for kids to discuss their school work etc. As this website will be assess by my prospect employer for a job as a entry level web apllication developer. The problem is am having this error : Notice: Undefined index: user_name in C:\wamp\www\pennacool_forum\loggedin.php on line 21 when i tried to display the user name in the session of the user who just loggedin. here is the loggedin.php script: Code: [Select] <?php // loggedin.php // The user is redirected here from login.php. session_start(); // Start the session. // If no session value is present, redirect the user: // Also validate the HTTP_USER_AGENT! if (!isset($_SESSION['agent']) OR ($_SESSION['agent'] != md5($_SERVER['HTTP_USER_AGENT']) )) { require_once ('includes/login_functions.inc.php'); $url = absolute_url(); header("Location: $url"); exit(); } $page_title = 'Logged In!'; include ('includes/header.html'); // Print a customized message: echo "<h1>Logged In!</h1> <p>You are now logged in, {$_SESSION['user_name']}!</p> <p><a href=\"logout.php\">Logout</a></p>"; include ('includes/footer.html'); ?> this is the login function: Code: [Select] function check_login($dbc, $user_name = '', $user_pass = '') { $errors = array(); // Initialize error array. // Validate the email address: if (empty($user_name)) { $errors[] = 'You forgot to enter your username.'; } else { $u = mysqli_real_escape_string($dbc, trim($user_name)); } // Validate the password: if (empty($user_pass)) { $errors[] = 'You forgot to enter your password.'; } else { $p = mysqli_real_escape_string($dbc, trim($user_pass)); } if (empty($errors)) { // If everything's OK. // Retrieve the user_id and first_name for that email/password combination: $q = "SELECT user_id, user_email FROM users WHERE user_name='$u' AND user_pass=SHA1('$p')"; $r = @mysqli_query ($dbc, $q); // Run the query. // Check the result: if (mysqli_num_rows($r) == 1) { // Fetch the record: $row = mysqli_fetch_array ($r, MYSQLI_ASSOC); // Return true and the record: return array(true, $row); } else { // Not a match! $errors[] = 'The username and password entered do not match those on file.'; } } // End of empty($errors) IF. // Return false and the errors: return array(false, $errors); } // End of check_login() function. ?> here is the login script: Code: [Select] <?php #login.php if (isset($_POST['submitted'])) { require_once ('includes/login_functions.inc.php'); require_once ('mysqli_connect.php'); list ($check, $data) = check_login($dbc, $_POST['user_name'], $_POST['user_pass']); if ($check) { // OK! // Set the session data:. session_start(); $_SESSION['user_id'] = $data['user_id']; $_SESSION['user_name'] = $data['user_name']; // Store the HTTP_USER_AGENT: $_SESSION['agent'] = md5($_SERVER['HTTP_USER_AGENT']); // Redirect: $url = absolute_url ('loggedin.php'); header("Location: $url"); exit(); } else { // Unsuccessful! $errors = $data; } mysqli_close($dbc); } // End of the main submit conditional. include ('includes/login_page.inc.php'); ?> thanks in advance guys ! |