PHP - First Attempt At Salting A Log In
Hey guys!
In my tutorials they were putting together a login system. After I watched the tutorial I decided to put one together that was my own. also, the tutorial only used MD5. After I read the post on the top of this forum about MD5 I decided to give salt a go on my own to see if I could pull it off. I'd like to hear what more experienced coders have to say about my code, but I'd appreciate it if you went easy on me lol. I'm quite happy with myself that I put this together all on my own and it works, I have tested it with my database lol. Code: (php) [Select] <?php //Check for form values in POST array// if (isset($_POST['username'])&& isset($_POST['password'])){ //strip tags and whitespace from user// if(!empty($_POST['username'])){ $T_user = strip_tags($_POST['username']); $user = str_replace(' ','',$T_user); }else{ $user = false; } //strip tags and spaces// if(!empty($_POST['password'])){ $T_pass = strip_tags($_POST['password']); $T2_pass = str_replace(' ', '', $T_pass); //Generate SALT and encrypt// $salt = 'angelinajolie'; $pass = md5($T2_pass.$salt); }else{ $pass = false; } //Check User and Pass for NULL then query database// if($pass || $user != false){ $query = "SELECT id FROM users WHERE username = '$user' AND password ='$pass'"; $query_run = mysql_query($query); $query_rows = mysql_num_rows($query_run); if($query_rows == 0){ echo 'Password and/or Username are invalid!'; echo $query_rows; }else if ($query_rows != 0){ echo 'Welcome back!'; } }else{ echo 'Must specify Username and Password!'; } } ?> <form action="<?php echo $current_file; ?>" method="POST"> Username: <input type="text" name="username" /> Password: <input type="password" name="password" /> <input type="submit" value="Login" /> </form> Similar TutorialsLately I've been telling myself to start touching up my security when it comes to passwords, so here I am with another question on PHPFreaks. I've read several salting guides, but I still have a few lingering questions. One of which is: once a salt has been created (see my function below), do I store it in a column named "salt" for each user in the "users" table? It seems like if a hacker got a hold of the database information, they could just ignore the salt and go straight to deciphering a user's hashed password. Just curious about that... Now, onto my simple function I decided to write to give this a try: function generateSalt($username) { //length of salt $char_max = 21; $char_list = array('A', 'B', 'C', 'D', 'G', 'Z', rand(0,200), 9, 8, 6, rand(3,55), rand(7, 1444)); //random numbers and letters will be appended to this variable $gen_chars = ''; for($x = 0; $x < 10; $x++) { $gen_chars .= $char_list[rand(0, count($char_list))]; } //random addition to salt $gen_chars = hash(sha256, $gen_chars); //shorten then hash -- max 5 chars $shorten_user = substr(sha1(strpos($username, 0, 3)), 0, 5); //salt var $salt = $gen_chars.$shorten_user.date('M-d-Y h:m:s'); $salt = substr(hash(sha256, $salt), 0, $char_max); return $salt; } Any feedback regarding this function? I've read that MD5 isn't really reliable, and people should be using SHA256, so I decided to go with that. I also tried to make each user's salt really random and unique. But how does this affect the user's password or make it any securer if I can't combine the salt and password? I know for a fact that I'm missing a piece of information or doing something wrong, so if anyone could help me out: that'd be very appreciated. I'm incorporating a dynamic salt into my user system, but I'm not sure how to store the salt itself. The password is hashed and added to the database, but wouldn't you need to store the salt as plain text in the database in order to verify the login later? Also, I've read that using both a dynamic and static salt is good practice. If this is the case, is the static salt simply defined within the PHP? Or is there another method to storing it? Thanks for the help Hi all. I`m starting with the php programming and i try to create a simple questionnaire i want to ask few questions with few possible answers could anyone give me any sample how the code should look like, i`ve created few quetsions but they are all seperate code, how can i put them together into one code? any suggestions? Thanks I stumbled across this site after being slammed hard elsewhere for being a novice and really not knowing what I am doing. What I have read so far is more encouraging. I just wrote my first program in php and it is not working at all right now. All it keeps doing is opening window after window until I force the browser to close. I am using a Mac running Yosemite and using MAMP. Hopefully that is enough background.
I know this is an introduction area, so I will also post this in another forum in case this is closed for being off topic.
This is a login file to connect to the server:
<?php // login.php // Get connection information echo <<<_END <form method = "post" action = "login.php"> <pre> <input type = "text" name = "localhost" />host server<br /> <input type = "text" name = "username" />Username<br /> <input type = "text" name = "password" /><br /> <br /> <input type = "submit" value = "submit" /> </form> _END $db_server = sanitize_string($localhost); $db_username = sanitize_string($username); $db_password = sanitize_string($password); /* $user = 'root'; $password = 'root'; $db = 'rpsls'; $host = 'localhost'; $port = 3306; $link = mysql_connect( "$host:$port", $user, $password ); $db_selected = mysql_select_db( $db, $link ); */ mysql_connect($db_server, $db_username, $db_password) or die(mysql_error()); // Create rpsls table if it does not exist $tbl = "rpsls"; $query = "CREATE TABLE rpsls(human VARCHAR(10), computer VARCHAR(10), outcome VARCHAR(5), action VARCHAR(15)); INSERT INTO rpsls (human, computer, outcome, action) VALUES ("Rock", "Paper", "Lose", "Covers"); INSERT INTO rpsls (human, computer, outcome, action) VALUES ("Rock", "Scissors", "Win", "Crushes"); INSERT INTO rpsls (human, computer, outcome, action) VALUES ("Rock", "Lizard", "Win", "Crushes"); INSERT INTO rpsls (human, computer, outcome, action) VALUES ("Rock", "Spock", "Lose", "Vaporizes"); INSERT INTO rpsls (human, computer, outcome, action) VALUES ("Paper", "Rock", "Win", "Covers"); INSERT INTO rpsls (human, computer, outcome, action) VALUES ("Paper", "Scissors", "Lose", "Cuts"); INSERT INTO rpsls (human, computer, outcome, action) VALUES ("Paper", "Lizard", "Lose", "Eats"); INSERT INTO rpsls (human, computer, outcome, action) VALUES ("Paper", "Spock", "Win", "Disproves"); INSERT INTO rpsls (human, computer, outcome, action) VALUES ("Scissors", "Lizard", "Win", "Decapitates"); INSERT INTO rpsls (human, computer, outcome, action) VALUES ("Scissors", "Spock", "Lose", "Smashes"); INSERT INTO rpsls (human, computer, outcome, action) VALUES ("Scissors", "Rock", "Lose", "Crushes"); INSERT INTO rpsls (human, computer, outcome, action) VALUES ("Scissors", "Paper", "Win", "Cuts"); INSERT INTO rpsls (human, computer, outcome, action) VALUES ("Lizard", "Spock", "Win", "Poisons"); INSERT INTO rpsls (human, computer, outcome, action) VALUES ("Lizard", "Rock", "Lose", "Crushes"); INSERT INTO rpsls (human, computer, outcome, action) VALUES ("Lizard", "Paper", "Win", "Eats"); INSERT INTO rpsls (human, computer, outcome, action) VALUES ("Lizard", "Scissors", "Lose", "Decapitates"); INSERT INTO rpsls (human, computer, outcome, action) VALUES ("Spock", "Rock", "Win", "Vaporizes"); INSERT INTO rpsls (human, computer, outcome, action) VALUES ("Spock", "Paper", "Lose", "Disproves"); INSERT INTO rpsls (human, computer, outcome, action) VALUES ("Spock", "Scissors", "Win", "Smashes"); INSERT INTO rpsls (human, computer, outcome, action) VALUES ("Spock", "Lizard", "Lose", "Poisons");"; check_table($tbl, $query); // Create choices table if it does not exist $tbl = "choices"; $query = "CREATE TABLE choices(id SMALLINT, choice VARCHAR(10)); INSERT INTO choices (id, choice) VALUES (1, "Rock"); INSERT INTO choices (id, choice) VALUES (2, "Paper"); INSERT INTO choices (id, choice) VALUES (3, "Scissors"); INSERT INTO choices (id, choice) VALUES (4, "Lizard"); INSERT INTO choices (id, choice) VALUES (5, "Spock");"; check_table($tbl, $query); // Sanitize user input function sanitize_string($var) { $var = stripslashes($var); $var = htmlentities($var); $var = strip_tags($var); return $var; } function check_table($tbl, $query){ $db = new mysqli(...); $result = $db->query("SHOW TABLES LIKE "$tbl); if ($result->num_rows == 0){ mysql_query($query); } } ?>and this is the program: <?php // log into server and database require_once 'login.php'; $db_server = mysql_connect($db_hostname, $db_username, $db_password); if (!$db_server) die("Unable to connect to MySQL: " . mysql_error()); $conn = mysql_connect($db_server, $db_username, $db_password) or die(mysql_error()); $db_database = 'rpsls'; mysql_select_db($db_database) or die("Unable to select database: " . mysql_error()); // Start Game ready_to_play(); // Rock Paper Scissors Lizard Spock game function rock_paper_scissors_lizard_spock() { $human = human_play(); $computer = computer_play(); game_outcome($human, $computer); play_again(); // Start Game Function function ready_to_play(){ echo <<<_END <form method = "post" action = "rpsls.php"> <h2>Ready to play Rock, Paper, Lizard, Spock?</h2> <hr> <table> <tr> <td><input type = "radio" name = "ready" value = "Yes" />Yes</td> <td><input type = "radio" name = "ready" value = "No" />No</td> </tr> <tr> <td colspan = "2"><input type = "submit" value = "Play!" /></td> </tr> </table> </form> _END if ($ready == "Yes"){ $query = "CREATE TABLE gameResults ( games SMALLINT NOT NULL, win SMALLINT NULL, loss SMALLINT NULL, draw SMALLINT NULL, PRIMARY KEY (games))"; mysql_query($query); rock_paper_scissors_lizard_spock(); }else{ close_rpsls(); } } // Play Again // Start Game Function function play_again() { echo <<<_END <form method = "post" action = "rpsls.php"> <h2>Play Again?</h2> <hr> <table> <tr> <td><input type = "radio" name = "ready" value = "Yes" />Yes</td> <td><input type = "radio" name = "ready" value = "No" />No</td> </tr> <tr> <td colspan = "2"><input type = "submit" value = "Play!" /></td> </tr> </table> </form> _END if ($ready == "Yes"){ rock_paper_scissors_lizard_spock(); }else{ close_rpsls(); } } // Human Play Selection function human_play() { echo <<<_END <form method = "post" action = "rpsls.php"> <h2>Let's Play Rock, Paper, Lizard, Spock</h2> <hr> <table> <tr> <td><input type = "radio" name = "human" value = "Rock" />Rock</td> <td><input type = "radio" name = "human" value = "Paper" />Paper</td> </tr> <tr> <td><input type = "radio" name = "human" value = "Scissors" />Scissors</td> <td><input type = "radio" name = "human" value = "Lizard" />Lizard</td> </tr> <tr> <td colspan = "2"><input type = "radio" name = "human" value = "Spock" />Spock</td> </tr> <tr> <td colspan = "2"><hr></td> </tr> <tr> <td colspan = "2"><input type = "submit" value = "Play!" /></td> </tr> </table> </form> _END return $human; } // Computer Play Selection function computer_play() { $play = rand(1,5); $query = "SELECT choice FROM choices WHERE number = $play"; $computer = mysql_query($query); return $computer; } // Game Outcome Function function game_outcome($human, $computer) { $win = $loss = $draw = 0 if ($human == $computer){ echo "Draw<br />"; echo "We both played ".$human; $draw = 1; }else{ $query = "SELECT outcome, action FROM rpsls WHERE human = $human AND computer = $computer"; $results = mysql_query($query); $results2 = mysql_fetch_array($results); $outcome = $results2[0]; $action = $results2[1]; if ($outcome == "Win"{ echo "You Win!!!<br />" echo "Your ".$human. " ".$action." my ".$computer."<br />"; $win = 1; }else{ echo "You Lose/.<br /> echo "My ".$computer." ".$action." your ".$human."<br />"; $loss = 1; } } $query = "INSERT INTO gameResults VALUES".(NULL, '$win', '$loss', '$draw')"; mysql_query($query); } // Game Statistics Function function game_statistics () { $query = "SELECT * FROM gameResults"; $result = mysql_query($query); $rows = mysql_num_rows($result); $games = $rows; $win = $loss = $draw = 0; for ($index = 0; $index < $rows; ++$index){ $row = mysql_fetch_row($result); $win = $win + $row[1]; $loss = $loss + $row[2]; $draw = $draw + $row[3]; } echo <<<_END <table> <tr> <td>Games</td> <td>Win</td> <td>Loss</td> <td>Draw</td> </tr> <tr> <td>$games</td> <td>$win</td> <td>$loss</td> <td>$draw</td> </tr> </table> _END } // Print Statistics and close the game function close_rpsls(){ echo <<<_END <form method = "post" action = "rpsls.php"> <h3>Are you sure you want to quit?</h3> <hr> <table> <tr> <td><input type = "radio" name = "ready" value = "Yes" />Yes</td> <td><input type = "radio" name = "ready" value = "No" />No</td> </tr> <tr> <td colspan = "2"><input type = "submit" value = "Play!" /></td> </tr> </table> </form> _END if ($ready == "No"){ rock_paper_scissors_lizard_spock(); }else{ $query = "DROP TABLE gameResults"; mysql_query($query); } } // close connection mysql_close($conn); ?>Please forgive my novice errors and help me figure out what is wrong with this program. Thank you. Here is the contents of the error log: 141104 18:36:26 mysqld_safe Starting mysqld daemon with databases from /Applications/MAMP/db/mysql 141104 18:36:28 [Warning] Setting lower_case_table_names=2 because file system for /Applications/MAMP/db/mysql/ is case insensitive 141104 18:36:28 [Note] Plugin 'FEDERATED' is disabled. 141104 18:36:28 InnoDB: The InnoDB memory heap is disabled 141104 18:36:28 InnoDB: Mutexes and rw_locks use GCC atomic builtins 141104 18:36:28 InnoDB: Compressed tables use zlib 1.2.3 141104 18:36:28 InnoDB: Initializing buffer pool, size = 128.0M 141104 18:36:28 InnoDB: Completed initialization of buffer pool 141104 18:36:28 InnoDB: highest supported file format is Barracuda. 141104 18:36:32 InnoDB: Waiting for the background threads to start 141104 18:36:33 InnoDB: 5.5.38 started; log sequence number 1711074 141104 18:36:33 [Note] Server hostname (bind-address): '0.0.0.0'; port: 8889 141104 18:36:33 [Note] - '0.0.0.0' resolves to '0.0.0.0'; 141104 18:36:33 [Note] Server socket created on IP: '0.0.0.0'. 141104 18:36:35 [Note] Event Scheduler: Loaded 0 events 141104 18:36:35 [Note] /Applications/MAMP/Library/bin/mysqld: ready for connections. Version: '5.5.38' socket: '/Applications/MAMP/tmp/mysql/mysql.sock' port: 8889 Source distribution I have possible HTTP_REFERER values such as the following:
[HTTP_REFERER] => http://www.example.com/lib/index.php?cid=components&controller=data&id=17&roles_id=15 [HTTP_REFERER] => http://www.example.com/lib/index.php?cid=createhelpI am just trying to get the value of "cid" Note that this applies to a TinyMCE plugin, and my $_GET variable does not include "cid". Looking at my $_SERVER array, HTTP_REFERER is the only element that includes "cid". I am also not concerned about spoofing HTTP_REFERER. I am getting the value of "cid" as follows. Is this the right way to do so? $RegExp = '/index\.php\?cid=([^&]+)/'; preg_match($RegExp, $_SERVER['HTTP_REFERER'], $matches); exit($matches[1]); Hi guys, I am creating a piece of code that blocks a user a for 48 hours after attempting to login 5 times with the wrong password, within a 24hour period. If the user logs in successful within the 24hr and, it should reset the attempt count.
The issue I'm having ATM is that with the attempt count, It is only updating the first row of that user, if i attempt more times. Here is an example of whats going on:
User - Time - Attempt- count()
User 1 10:00pm Attempt 1 (5)
User 1 10:02pm Attempt 2 (4)
User 1 10:04pm Attempt 3 (3)
User 1 10:06pm Attempt 4 (2)
User 1 10:07pm Attempt 5 (1)
User 2 10:15pm Attempt 1 (2)
User 2 10:20pm Attempt 2 (1)
As you can see, all the attempts will increment (the numbers in the bracket) but the latest attempt will be set to one. How do I get it so that all the attempts are incremented so it looks like this.
User - Time - Attempt- count()
User 1 10:00pm Attempt 1 (5)
User 1 10:02pm Attempt 2 (5)
User 1 10:04pm Attempt 3 (5)
User 1 10:06pm Attempt 4 (5)
User 1 10:07pm Attempt 5 (5)
User 2 10:15pm Attempt 1 (2)
User 2 10:20pm Attempt 2 (2)
Here is a snippet of my code:
if (!$pw_ok) { if (isset($_SERVER["REMOTE_ADDR"])) { $str_RemoteHost = $_SERVER["REMOTE_ADDR"]; } else { $str_RemoteHost = ''; } $qry_WriteToDatabase = " INSERT INTO cms_user_login_attempts ( cula_user_id, cula_date_time, cula_remote_host, cula_attempt_count ) VALUES ( " . $db->SQLString($row->user_id) . ", Now(), " . $db->SQLString($str_RemoteHost, true) . ", 'cula_attempt_count' )"; $db->query($qry_WriteToDatabase); $qry_UpdateCount = " UPDATE cms_user_login_attempts SET cula_attempt_count = cula_attempt_count + 1 WHERE cula_user_id = " . $db->SQLString($row->user_id) . " "; $db->query($qry_UpdateCount); $qry_CheckDatabase = " SELECT CASE WHEN count(*) >= 5 THEN 0 ELSE 1 END as allowed_login FROM cms_user_login_attempts WHERE cula_date_time >= DATE_SUB(CURRENT_TIMESTAMP, interval 48 hour) AND cula_user_id = " . $db->SQLString($row->user_id) . ""; $rs_CheckDatabase = $db->query($qry_CheckDatabase); if (! (isset($qry_CheckDatabase) && $qry_CheckDatabase)) { $errors->defineError("invalid_user_pass", "Too many attempts, account locked for 48hours.", array("username","password")); } } Edited by Navees_, 08 January 2015 - 06:15 PM. hope you all had a good Christmas/New Year. What I am trying to do is to submit as POST values to database_write.php, from within the while statement. What is happening is I am getting the second row of data every time I change the primary button.
Currently database_write.php is just doing print_r($_POST), And my array is always the same, no matter which select box I choose from. How can I get the values to be associated with the row I am currently changing? Any help would be great, thanks.
What I have so far:
<table class="table table-bordered table-hover"> <thead> <th>Room Number</th> <th>Primary Caregiver</th> <th>Seconday Caregiver</th> </thead> <tbody class="list"> <?php $sql = 'SELECT alarm_device_id, alarm_description, alarm_device_type, notes FROM alarm_device where notes in (\'MSU\') ORDER BY alarm_description'; $retval = mysql_query( $sql, $con ); if(! $retval ) { die('Could not get data: ' . mysql_error()); } $x=0; while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) { $id = $row['alarm_device_id']; $alarm_description = $row['alarm_description']; echo '<form id="msu_form">'; echo "<tr><td>{$row['alarm_description']}</td>"; echo "<td>"; $query2 = "SELECT alert_device_id,alert_description FROM alert_device WHERE notes = 'MSU'"; $result2 = mysql_query($query2) or die("Error in alarm_device select:" . mysql_error()); $count2 = mysql_num_rows($result2); if($count2 > 0) { //echo '<select name='.$x.'>'; echo '<select id="Primary" name="primary" onchange="doAjaxPost(this)">'; while($row2 = mysql_fetch_array($result2)) { echo "<option value=".$row2['alert_device_id'].">".$row2['alert_description']."</option>"; } echo "</select>"; }else { echo "Please update alert device to this area"; } echo "</td>"; echo "<td>"; $query3 = "SELECT alert_device_id,alert_description FROM alert_device WHERE notes = 'MSU2'"; $result3 = mysql_query($query3) or die("Error in alarm_device select:" . mysql_error()); $count3 = mysql_num_rows($result3); if($count3 > 0) { echo '<select id="Secondary" name="secondary">'; while($row3 = mysql_fetch_array($result3)) { echo "<option value=".$row3['alert_device_id'].">".$row3['alert_description']."</option>"; } echo "</select>"; }else { echo "Please update alert device to this area"; } echo "</td>"; $aid = $id + $x; //echo $aid; //$ad = $alarm_description + $x; echo '<input type="hidden" id="ID" name="ID" value="'.$id.'"/>'; //echo '<input type="hidden" id="desc" name="desc" value="'.$ad.'"/>'; //echo '<td>'."<input type='submit' name='btnupdate' value='UPDATE' /></td>"; //echo '<td><input type="button" value="Ajax Request" onClick="doAjaxPost()"></td>'; echo '</form>'; $x = $x+1; } ?> <script> function doAjaxPost() { // get the form values var primary = $('#Primary').val(); var secondary = $('#Secondary').val(); var hidden = $('#ID').val(); //var desc = $(sel).parent().nextAll('#desc').val(); $.ajax({ type: "POST", url: "functions/database_write.php", data: $('#msu_form').serialize(), //data: "Primary="+primary+"&Hidden="+hidden+"&Secondary="+secondary, success: function(resp){ //we have the response alert("'" + resp + "'"); }, error: function(e){ alert('Error: ' + e); } }); } </script> </tr> </tbody> </table> At the fear of bothering all you, I will post here hoping that I am in the write section. I am new to php and mysql. I am using such to develope a webpage for my new business. I do believe that my php scripting is turned on because I have one script that "works". However when I take the wheel and write a script of my own and try to view it all I get is a blank white page and no errors nor anything that I wanted to display. I have tried numerous attempts at tiring to get anything to show up all I can ever seem to do is "echo" something anything else is null in displaying. Please feel free to take a look. http://72.28.26.162/rc/ phpinfo.php is accessible if you insert it after the last / (http://72.28.26.162/rc/phpinfo.php) I am at a loss. I have spent hours looking for something I miss during set up or with my procedure. I thank whomever my help me in advance. I am running ubuntu server 10 Apache/2.2.16 port 80 (Please advise if you need anything else) thanks Incorrect login attempt 1 \/ Incorrect login attempt 2 \/ Incorrect login attempt 3 -->> ?forgot your login details? What's the most effecient way of achieving this? Is it to: 1. create a session for the user who hasn't logged in 2. the user login fails once, session['fail']=1 3. the user login fails twice, session['fail']=2 4. the user login fails for a third time pushing the session['fail'] count to three: this triggers an 'if' on the index.php prompting the user to retrieve their details through the "forgot login details system" However if the session['fail'] count never reaches 3 then this temp session is destroyed and the proper one created allowing the user into the site?? As usual any pointers into the correct direction here would be very much appreciated (and i try to repay by answering other peoples questions [where i can ]) Bonjour, I have a form in php (name, adresse ... and Email). Somebody is playing me a joke in sending me about 100 mails a day through my form. It's a joke but at last not really funny. What I am lookink for is lines of PHP codes which control the Email field into the form and would not allow the form to be sent. If you have another solution it's with a great pleasure I will accept it; Thanks a lot My english is definitively french. sorry about it Ener SET UP: Windows vista # XAMPP 1.7.3, # Apache 2.2.14 (IPv6 enabled) + OpenSSL 0.9.8l # MySQL 5.1.41 + PBXT engine # PHP 5.3.1 # phpMyAdmin Error message: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') VALUES ('qwerty','uiop','asd')' at line 2 I'm trying to get this multi page order form to insert information into two tables via a session. But it comes up with the above error message. This script worked perfectly with one table but as soon as I coded he information to go into two tables it screwed up. Is it the sprint <?php //let's start our session, so we have access to stored data session_start(); session_register('membership_type'); session_register('terms_and_conditions'); include 'db.inc.php'; $db = mysql_connect('localhost', 'root', '') or die ('Unable to connect. Check your connection parameters.'); mysql_select_db('ourgallery', $db) or die(mysql_error($db)); //let's create the query $query = sprintf("INSERT INTO subscriptions ( name, email_address, membership_type,) VALUES ('%s','%s','%s')", mysql_real_escape_string($_SESSION['name']), mysql_real_escape_string($_SESSION['email_address']), mysql_real_escape_string($_SESSION['membership_type'])); //let's run the query $result = mysql_query($query, $db) or die(mysql_error($db)); $query = sprintf("INSERT INTO site_user_info ( terms_and_conditions, name_on_card, credit_card_number, credit_card_expiration_data) VALUES ('%s','%s','%s','%s')", mysql_real_escape_string($_SESSION['terms_and_conditions']), mysql_real_escape_string($_POST['name_on_card']), mysql_real_escape_string($_POST['credit_card_number']), mysql_real_escape_string($_POST['credit_card_expiration_data'])); //let's run the query $result = mysql_query($query, $db) or die(mysql_error($db)); echo '$result'; ?> I'm trying to insert into this database: <?php require 'db.inc.php'; $db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or die ('Unable to connect. Check your connection parameters.'); mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db)); $query = 'CREATE TABLE IF NOT EXISTS subscriptions ( name VARCHAR(50) NOT NULL, email_address VARCHAR(50), membership_type VARCHAR(50), PRIMARY KEY (name) ) ENGINE=MyISAM'; mysql_query($query, $db) or die (mysql_error($db)); // create the user information table $query = 'CREATE TABLE IF NOT EXISTS site_user_info ( name VARCHAR(50) NOT NULL, terms_and_conditions VARCHAR(50) NOT NULL, name_on_card VARCHAR(50), credit_card_number VARCHAR(50), credit_card_expiration_data VARCHAR(50), FOREIGN KEY (name) REFERENCES subscriptions(name) ) ENGINE=MyISAM'; mysql_query($query, $db) or die (mysql_error($db)); echo 'Success!'; ?> What am I doing wrong? is there a code spell checker ? Also should I use the mysql_real_escape_string() on the user input as they become sessions variables or is it okay to wait and clean the input as it gets inserted in the table? Thanks for your help. I want to query a database (search) and pass the desired columns from the search results to another page like so: Code: [Select] <?php //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); //authenticate user require('auth.php'); if (isset($_POST['submit'])) { // Connect to the database. require_once ('config.php'); //Query the database. $sql = "SELECT* FROM members INNER JOIN images ON members.member_id = images_member_id WHERE members.ethnicity = '{$_POST['ethnicity']}'"; $query = mysql_query($sql); if(mysql_num_rows($query) > 0){ while(($row = mysql_fetch_assoc($query)) !== false) { //Redirect to search results page. header("Location: search_results.php?friend='.$row['member_id'].'&me='.$_SESSION['id'].' &pic='.$row['image'].'&name='.$row['username'].'"); } } else { //If no results found. echo 'No results match this search query.' ; } } ?> I get the following error when i try to run the page (by submitting a form from another page which executes this page): Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in /home/a4993450/public_html/profile_search.php on line 31 The culprit line is this one: header("Location: search_results.php?friend='.$row['member_id'].'&me='.$_SESSION['id'].' &pic='.$row['image'].'&name='.$row['username'].'"); As you can see, I eliminated all white space between the variables and concatenations, thinking that that was the problem but I keep getting the error message. I'm at a loss about what to do next. Any help? I get the following error when I try to pass a value to a methiod in a loop: Warning: Attempt to assign property of non-object in /Users/staceyschaller/Sites/dev_zone/ckwv2/classes/class.php on line 670 This one has me very baffled. It will work the first time, and seems to work every other time, so I have no clue what is wrong. Here is the code: This code is part of my "display" class: function display_partner ($type,$loc,$rand=0,$narrow=0) { $this->partners = new partner($this->cxn); $display = ' <div id="cont_info" class="partner-list"> <div> <h3 class="settings">'.ucfirst($loc).' '.ucfirst($type).last_letter($type).'s</h3> </div> <div class="settings-value" style="height:12px;padding:0;margin:0;text-align:right;padding-right:10px;"> <a href="" class="trunc">Add your organization to this list</a></p> </div> <div style="height:2px;padding:0;margin:0;"> <hr class="account" /> </div> '; $ids = $this->partners->get_partners_list($type,$loc,$rand); for ($b=0;$b<sizeof($ids->id);$b++) { $this->partnerID = $ids->id[$b]; $display .= ($narrow)? $this->card_partner_narr():$this->card_partner(); if ($b!=(sizeof($ids->id)-1)) { $display .= '<hr class="account" />'; } } if (sizeof($ids->id)==0) { $display .= '<div style="color:#999999;display:line;text-align:center;height:20px;">No Partners found for '.ucfirst($loc).' '.ucfirst($type).'</div>'; } $display .= ' </div>'; return $display; } function card_partner () { $this->partners->set_partner_id($this->partnerID); $part_info = $this->partners->get_partner_info(); if ($part_info) { $display .= ' <table class="settings"> <tr> '.$this->show_if($part_info['partLogo']['val'],'<td class="settings-value" rowspan="2"><img src="'.LOGO_FOLDER.$part_info['partLogo']['val'].'" '.resize_img(LOGO_FOLDER.$part_info['partLogo']['val'],175).'alt="'.$part_info['partName']['val'].'" /></td>').' <td class="settings-value" colspan="2"><h5>'.$part_info['partName']['val'].'</h5></td> </tr> <tr> <td class="settings-value"> <span style="color:999999;">'.$part_info['partAddress']['val'].'<br /> '.$part_info['partCity']['val'].', '.$part_info['partST']['val'].' '.$part_info['partZIP']['val'].'<br /> '.$part_info['partPhone']['val'].'</span><br /> <a href="'.$this->form->show_href($part_info['partWeb']['val']).'" target="_blank">'.$part_info['partWeb']['val'].'</a> </td> <td class="settings-value">'.$part_info['partInfo']['val'].'</td> </tr> </table> '; } return $display; } This code is part of my "partners" class: function set_partner_id($partID) { echo '<p>partID: '.$partID.' '.gettype($partID).'<br> $this->partner->id: '.$this->partner->id.'</p>'; $this->partner->id = $partID; ///*** ERROR HAPPENS HERE ***/ echo '<p>id set: '.$this->partner->id.'<br> $this->partner->id: '.$this->partner->id.'</p><hr>'; } function get_partner_id() { return $this->partner->id; } // gets user info at login function get_partner_info() { $this->partner = $this->cxn->proc_info('partner','partID',$this->partner->id);//$this->partner->id return $this->partner; } The following is the output generated: partID: 24 string $this->partner->id: id set: 24 $this->partner->id: 24 partID: 26 string $this->partner->id: Warning: Attempt to assign property of non-object in /Users/staceyschaller/Sites/dev_zone/ckwv2/classes/class.php on line 670 id set: $this->partner->id: partID: 17 string $this->partner->id: id set: 17 $this->partner->id: 17 partID: 25 string $this->partner->id: Warning: Attempt to assign property of non-object in /Users/staceyschaller/Sites/dev_zone/ckwv2/classes/class.php on line 670 id set: $this->partner->id: As you can see, the value passes to $this->set_partner_id($partID) each time. It is formatted as a string. When it assigns the value to $this->partner->id, however, sometimes it works, and sometimes it doesn't. It's probably something obvious, but I've racked my brain to see what it is. Any ideas? |