I am creating a user registration form with simple requirements.and insert data with simple query
<?php
if (isset($_POST) && isset($_POST["form_register"]))
{
$insert_query = "INSERT INTO users SET
users.first_name='" . mysql_real_escape_string($_POST['fname']) . "',
users.last_name='" . mysql_real_escape_string($_POST['lname']) . "',
users.email='" . mysql_real_escape_string($_POST['email']) . "',
users.password='" . mysql_real_escape_string($_POST['password']) . "';";
if (mysql_query($insert_query))
{
$_SESSION['messageType'] = "success_msg";
}
else
{
$_SESSION['message'] = "-Registration not Successful.";
$_SESSION['messageType'] = "error_msg";
}
}
?>
but now I have 3 extra fields in this form. If I select a checkbox then the other 2 field data go in another table with having this data also. how can i do that?
It is my old code...now I add 3 new columns, 1 checkbox and 2 text boxes.
The query is, if checkbox is selected then other 2 colums values go in another table and if checkbox is not select then working 1 query.
If I understand right you want to insert data in another table IF user check the checkbox.
So you have to use another IF like this:
if (mysql_query($insert_query))
{
if (/* here your condition for checkbox*/)
{
/* here your query for the secund table and the new two values*/
}
$_SESSION['messageType'] = "success_msg";
}
Note that is extremely important you run the secund query after the success of the first, cause if the first fails for some reason, secund will not be executed.
We really need to see your form as what you're providing us is way too vague, also, check the ending syntax for your $insert_query.
If I comprehended the question right, the final code should look something like this.
Tell me if I'm wrong
<?php
if(isset($_POST) && isset ($_POST["form_register"])){
$insert_query1 = "INSERT INTO users SET
first_name='".mysql_real_escape_string($_POST['fname'])."',
last_name='".mysql_real_escape_string($_POST['lname'])."',
email='".mysql_real_escape_string($_POST['email'])."',
password='".mysql_real_escape_string($_POST['password'])."'";
if(mysql_query($insert_query)){
$_SESSION['messageType'] = "success_msg";
} else {
$_SESSION['message'] = "-Registration not Successful.";
$_SESSION['messageType'] = "error_msg";
}
if($_POST['checkbox']) {
$insert_query2 = ""; //Put your second MYSQL Query here
}
if(mysql_query($insert_query2)){
$_SESSION['messageType2'] = "success_msg";
} else {
$_SESSION['message2'] = "-Registration not Successful.";
$_SESSION['messageType2'] = "error_msg";
}
}
?>
Related
I want to be able to query a table in my database using multiple form inputs which relate to several columns in the table. The problem I am running into is that not all of the form inputs are required.
A little detail...
I have a table called users. This table has many columns, but the ones I am querying are first_name, last_name, location, status (0 or 1).
I have three inputs on the search form. Name (text), Location (select) and Status (select). The user does not have to enter an input for all of the inputs, only one is required.
The main problem I have is writing the query based on the inputs. I can get it to work with multiple else/if statements, for example...
if($_POST['name'] && !$_POST['location'] && !$_POST['status']){
$query = '[QUERY THAT MATCHES NAME]';
} else if($_POST['name'] && $_POST['location'] && !$_POST['status']){
$query = '[QUERY THAT MATCHES NAME AND LOCATION]';
} else if($_POST['name'] && $_POST['location'] && $_POST['status']){
$query = '[QUERY THAT MATCHES NAME AND LOCATION AND STATUS]';
} else if {
etc...
}
But, this gets really messy, really quickly as I would need to have 9 or so "else if" statements to cover all of the possible scenarios.
My question is, is there a cleaner way to handle this in a single query, or at least with out all of these "else if" statements?
You could do something along the lines of:
$query = 'SELECT * FROM TABLE WHERE';
$flag = 0;
if ($_POST['name']) {
$query .= ' NAME = "' . $_POST['name'] . '"';
$flag = 1;
}
if ($_POST['location']) {
if ($flag) { $query .= " AND "; }
$query .= ' LOCATION = "' . $_POST['location'] . '"';
$flag = 1;
}
if ($_POST['status']) {
if ($flag) { $query .= " AND "; }
$query .= ' STATUS = "' . $_POST['status'] . '"';
}
Although, I'm not sure how much better it will make your code look.
Also this is assuming that you will have at least one value passed through your post request.
I have a script that allows for multiple rows to be created on the page and then I need to have the rows counted on the post and then each row inserted into the table.
I have the GUI working to where users can add or remove rows as needed yet when I submit no data is being written to the table. I have tried altering the script for the post to be straight '$variables' and it works to write but only writes the first row.
I have attached the action script that I am using from WebLesson that works great for one field but for more than one I am at a loss for what to try.
//includes
include '----';
include '---';
session_start();
$number = count($_POST['name']);
echo $_POST['name'] . "<br>";
echo $number . "<br>";
if($number >= 1)
{
echo $_POST['pasid'];
$conn = mysqli_connect($servername, $username, $password, $dbname);
$id = $_POST['pasid'];
$name = $_POST['name'];
$dose = $_POST['dose'];
$dir = $_POST['directions'];
$time = $_POST['time'];
echo $i;
for($i=0; $i<$number; $i++)
{
if(trim($_POST["name"][$i] != ''))
{
$sql = "INSERT INTO meds (id, name, dose, directions)
VALUES('".mysqli_real_escape_string($_POST["pasid"][$i])."',
'".mysqli_real_escape_string($_POST["name"][$i])."',
'".mysqli_real_escape_string($_POST["dose"][$i])."',
'".mysqli_real_escape_string($_POST["directions"][$i])."',
'".mysqli_real_escape_string($_POST["time"][$i])."') " ;
mysqli_query($conn, $sql);
}
}
echo "Data Inserted";
}
else
{
die("Connection failed: " . mysqli_connect_error());
}
I would like this to count how many rows were posted and then submit each row to the table.
Picture of the UI:
You can generate unique name attributes for each form element and then loop through them in PHP. The easiest way to do that would probably be increment a number at the end of the name attribute each time the user creates a new row. You will have to do that with Javascript.
var suffix = 0;
function addNewRow(){
...
<input type="text" name="pasid_${i}"/> //Add incriminating suffix
...
suffix++; //Increment suffix for next time
}
Then your PHP would look like
$suffix = 0;
while(isset($_POST['pasid' . $suffix])){ //Keep looping until no more POST value
//Process row $suffix, referencing all the data like $_POST['field_name'. $suffix]
$suffix++; //Increment suffix for the next field
}
Make sure the field you are checking for in the while loop is required or else the user might omit an input and the loop would terminate prematurely. You could also check multiple $_POST indexes in the while loop if non of the fields are required.
I am missing something from my code and I don't know how to make it work. I may have programed it wrong and that could be giving me my troubles. I am new at php and things have been going slowly. please understand that the code my not be organized as it should be. After creating about 12 pages of code I found out that I should be using mysqli or pod. Once I get everything working that will be the next project. Enough said here is my issue. I was able to populate my drop down box and there shows no errors on the page. Also all the data does get inserted into the database except for the section made on the drop down box. Here is my code. I will leave out all of the input fields except the drop down.
<?php
{$userid = $getuser[0]['username'];}
// this is processed when the form is submitted
// back on to this page (POST METHOD)
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
# escape data and set variables
$tank = addslashes($_POST["tank"]);
$date = addslashes($_POST["date"]);
$temperature = addslashes($_POST["temperature"]);
$ph = addslashes($_POST["ph"]);
$ammonia = addslashes($_POST["ammonia"]);
$nitrite = addslashes($_POST["nitrite"]);
$nitrate = addslashes($_POST["nitrate"]);
$phosphate = addslashes($_POST["phosphate"]);
$gh = addslashes($_POST["gh"]);
$kh = addslashes($_POST["kh"]);
$iron = addslashes($_POST["iron"]);
$potassium = addslashes($_POST["potassium"]);
$notes = addslashes($_POST["notes"]);
// build query
// # setup SQL statement
$sql = " INSERT INTO water_parameters ";
$sql .= " (id, userid, tank, date, temperature, ph, ammonia, nitrite, nitrate, phosphate, gh, kh, iron, potassium, notes) VALUES ";
$sql .= " ('', '$userid', '$tank', '$date', '$temperature', '$ph', '$ammonia', '$nitrite', '$nitrate', '$phosphate', '$gh', '$kh', '$iron', '$potassium', '$notes') ";
// #execute SQL statement
$result = mysql_query($sql);
// # check for error
if (mysql_error()) { print "Database ERROR: " . mysql_error(); }
print "<h3><font color=red>New Water Parameters Were Added</font></h3>";
}
?>'
Here is the drop down
<tr><td><div align="left"><b>Tank Name: </b> </div></td><td><div align="left">
<?php
echo "<select>";
$result = mysql_query("SELECT tank FROM tank WHERE userid = '$userid'");
while($row = mysql_fetch_array($result))
{
echo "". $row["tank"] . "";
}
echo "";
?>
</div></td></tr>
You missed some code in while loop.
while($row = mysql_fetch_array($result))
{
echo "<option>".$row['tank']."</option>";
}
echo "</select>";
are you able to build drop down menu or box. if not try this query
$sql="SELECT `tank` FROM `tank` WHERE user_name='$user'";
$result=mysqli_query($dbc,$sql)
//here $dbc is a variable which you use to connect with the database.
Otherwise leave that only read from here why you need to change your code. in the while loop
one one more thing you have to give your select attribute a name, because it will return the value through name so give a name to your select attributes as you are using tank while building your drop down menu so i will give a same name tank. Than you dont have to change anything.
and you have to give value to your option as well, thanks
echo "<select name='age'>";
while($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['tank'] . "' >" . $row['tank'] . "</option>";
}
echo "</select>";
In a mysql table, i have 3 fields. user_to, user_from and id. The variables are all correct and should be inserting the correct data.
When a button is clicked, named 'poke', it should insert the cookie that stores the session of who did it and the person who was poked. It doesn't seem to be inserting and I am stuck :(
$cookie = $_SESSION['user_login'];
//Poke code
if (#$_POST['poke']) {
$check_if_poked = mysql_query("SELECT * FROM pokes WHERE user_to='$username' && user_from='$added_by'");
$num_poke_found = mysql_num_rows($check_if_poked);
if ($num_poke_found == 1) {
echo "Come on! Give the guy a chance!";
}
else
if ($username == $cookie) {
echo "You cannot Jab yourself.";
}
else
{ $poke_user = mysql_query("INSERT INTO `pokes` ('user_from', 'user_to') VALUES ('$cookie', '$username')") or trigger_error(mysql_error());
echo "$username has been jabbed.";
}
}
You used wrong quotes with fields in MySQL query.
//your wrong variant
"INSERT INTO `pokes` ('user_from', 'user_to') VALUES ('$cookie', '$username')"
//right variant
"INSERT INTO `pokes` (`user_from`, `user_to`) VALUES ('$cookie', '$username')"
Quotes like ' mean values and quotes like ` mean fields in SQL syntax
<?php
if ($_POST['poke']) {
#ref to the current user
$from = $_SESSION['user_login'];
#ref to the (poked user)
$to = $_POST['poked_user_id'];
if($from == $to){
echo "you cant poke yourself!";
}
else{
#ADVICE: USE PDO OR MYSQLI INSTEAD OF MYSQL
$check_if_poked = mysql_query("SELECT * FROM pokes WHERE user_to='$to' AND user_from='$from'");
if(mysql_num_rows($check_if_poked)){
echo "Come on! Give the guy a chance!";
}
else{
if(mysql_query("INSERT INTO `pokes` (`user_from`, `user_to`) VALUES ('$from', '$to')")){
echo "$to has been jabbed.";
}
else{
trigger_error(mysql_error());
}
}
}
}
?>
This started off as a comment - but it's getting too long to fit.
A session is not the same thing as a username - your post is very confused.
Leaving aside the wrong quotes (which is why your code is not doing what you expect)....
In a mysql table, i have 3 fields. user_to, user_from and id
... in that case you don't need to check if the row already exists - and not create duplicates. Set up a unique index then...
if (#$_POST['poke'] && ($_SESSION['user_login']!===$username)) {
$qry = "INSERT INTO `pokes` (`user_from`, `user_to`)
VALUES (".mysql_real_escape_string($_SESSION['user_login'])
.", '" . mysql_real_escape_string($username) . "')"
if (mysql_query($qry)){
echo "$username has been jabbed.";
} else if (stristr(mysql_error(), 'duplicate')) {
echo "Come on! Give the guy a chance!";
} else {
echo "It's all gone Pete Tong!";
}
} else if ($_SESSION['user_login']!===$username) {
echo "You cannot Jab yourself.";
}
While it's about the same effort for PHP processing, the DB workload is significantly less. This code also prevents some SQL injection attacks, and has error handling. I presume that $username has been created elsewhere and you don't have register_globals enabled.
There might be an easy answer to this, but I can't for the life of me get this to work.
I'm using PHP and MySQL and have something like this set up:
$studentname = mysql_real_escape_string($_POST['sname']);
$studentnumber = mysql_real_escape_string($_POST['snumber']);
$course = mysql_real_escape_string($_POST['courseselect']);
$bike3 = mysql_query("SELECT stoodnumber FROM bikes505 WHERE stoodname='" . $studentname . "'");
$bikestoods = mysql_fetch_array($bike3);
while($row = mysql_fetch_array($stoodlistq))
{
$stoodentname = $row['stoodname'];
$stoodentnumber = $row['stoodnumber'];
//$coursename = $row2['coursename'];
//$coursecode = $row2['coursecode'];
if($studentname == $stoodentname && $studentnumber == $stoodentnumber){
//$success = 1;
//$success = "yupp";
//echo "SUCCESS, WE CAN REGISTER YOOOU!";
echo "<br>";
//echo "INSERT INTO " . $course . "";
switch($course){
case "Biking Safely":
if($studentnumber = $bikestoods[0] or $bikestoods[1]){
echo "Sorry, this student has already registered";
} else if($bikecurrent < $bikemax){
mysql_query("INSERT INTO bikes505 VALUES ('" . $stoodentname . "','" . $stoodentnumber . "')");
echo "Yay, successfully registered " . $stoodentname . " - " . $stoodentnumber . " for " . $course;
echo "<br>";
} else{
echo "Sorry, class is full!";
}
break;
...and so on. The only problem that I'm having is that if I have two students with the same name, the second in the list will echo that the information is not correct.
For example, the MySQL table has 'stoodname' and 'stoodnumber', and if 'Jimmy St.James','1010' and 'Jimmy St.James','1090' are both records in the table it will only let me enroll Jimmy 1010 in the course and not Jimmy 1090.
Am I just way off with how I'm validating? Or am I missing something really obvious? At first I assumed it was just because I was only using the first item in the array $bikestoods[0] so I changed it to $bikestoods[0] or $bikestoods[1] and it still doesn't work.
Per a comment, you have $stoodlistq defined as:
$stoodlistq = mysql_query("SELECT * FROM stoodinfo");
Later, you use the following block of code:
$studentname = mysql_real_escape_string($_POST['sname']);
$studentnumber = mysql_real_escape_string($_POST['snumber']);
...
while($row = mysql_fetch_array($stoodlistq)) {
...
if($studentname == $stoodentname && $studentnumber == $stoodentnumber){
The while() loop in this code iterates over every record, however, the if-statement checks against the POST variables. The POST variables make up a single combination for "one student" - therefore, you'll only ever get a single student that can be enrolled.
To fix the issue, you'll either need to update your form that submits the "student name"/"student number" to accept multiple inputs - or update the if-statement to only check against the student's name (which could lead to a more undesired situation).
You are doing your query looking for stoodname . When you are doing things like this is not good to do this statements by a value that can be repeated. Maybe you want them to login with a username and password, or maybe with an id that you give to them, but unless somebody here has a better idea, i don't think you will be able to do it by the name.
$bikestoods = mysql_fetch_array($bike3);
only refers to the first result of bike3 query and only has 2 cols : [0] and [stoodnumber] no [1]. If you want to collect all ids that are in bike3, you have to curse the result one time.
while($stoodnumbers[] = mysql_fetch_array($bike3));