I am new to web development. I am trying to implement a database-driven web server using Apache+PHP+SQLite. Using the post method, I try to pass the input values on the html page to the web server as an SQL query to retrieve data inside the database.
Problem description:
Let's say there is a table (named my_table) in my database, having 3 columns, a1, a2 and a3. In the php file, there are 3 input values specified by the end-user, say $v1, $v2 and $v3. The values of $v1, $v2 and $v3 will be matched with patterns in a1, a2 and a3 so that the matched data rows will be retrieved. $v1, $v2 or $v3 can be an empty string, depending on the queries by the user. Formally speaking, if $v1='', $v2='' and $v3='', all of the data in my_table will be retrieved; if $v1='v1_value', $v2='' and $v3='', the data where column a1 has pattern v1_value will be retrieved.
My HTML form tag
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<table>
<tr><td>Item1: </td><td><input type="text" name="v1"></td></tr>
<tr><td>Item2: </td><td><input type="text" name="v2"></td></tr>
<tr><td>Item3: </td><td><input type="text" name="v3"></td>
</table>
<input type="submit", name="submit" value="Submit">
</form>
My PHP code
$v1 = $_POST['v1'];
$v2 = $_POST['v2'];
$v3 = $_POST['v3'];
And I am stuck at here...
$query = "SELECT * FROM my_table WHERE <A_PROPER_CONDITION_STATEMENT>"
That is, how to have a query to retrieve data as I want.
Hope I describe clearly. Thanks for help.
Try this code :-
$query = "SELECT * FROM my_table WHERE 1=1 ";
if(isset($_POST['v1']))
$query .=" and a1=".$_POST['v1'];
if(isset($_POST['v2']))
$query .=" and a2=".$_POST['v2'];
if(isset($_POST['v3']))
$query .=" and a3=".$_POST['v3'];
Related
I'm doing a school project - a website with students performances in various sports. I have three tables:
TABLE1 - "students"
id (primary key)
class
firstname
lastname
TABLE2 - "sports"
sport_id (primary key)
sportname
TABLE3 - "performances"
performance_id (primary key)
sport_id (foreign key - sports.sport_id)
student_id (foreign key - students.id)
value
I want to make a form that adds data into the third table.
That form should include:
class
firstname
lastname
sportname
value
...but I have no idea how to achieve this.
I could just create a form where user user adds value and then copy-pastes sport_id and student_id from tables below it, but that's unpractical.
I've been searching the internet for a while, but I haven't found any solution to this and if I did, it was only for one foreign key.
Does anyone know how to do this? If so, I would highly appreciate it! :)
EDIT: I should've mentioned that tables "students" and "sports" already have all the data in them, I just need to insert new performances using that data.
Since the data is already in the tables for students and sports, this information can be queried with some select statements in order to populate some HTML dropdowns. The advantage of using the select queries and the dropdowns is that value of the options can be set to the database ID while showing the user the human-readable text. Then, the page just needs to monitor for the form's submission and insert the IDs from the dropdowns along with the performance metric. I have not tested the code below, but here is a quicky example of how that might work.
Note: I like the PDO interface for preparing SQL queries in order to prevent injection attacks.
<?php
$user = 'user';
$password = 'password';
$con = new PDO('mysql:dbname=dbname;host=127.0.0.1;chartset=urf8', $user, $password);
$student_stmt = $con->prepare('select * from students');
$student_stmt->execute();
$sport_stmt = $con->prepare('select * from sports');
$sport_stmt->execute();
if (isset($_GET['student']) && isset($_GET['sport']) && isset($_GET['value'])) {
$student = $_GET['student'];
$sport = $_GET['sport'];
$value = $_GET['value'];
$insert_stmt = $con->prepare('insert into preformances (sport_id, student_id, value) values (:sport_id, :student_id, :value)');
$insert_stmt->bindParam(':sport_id', $sport);
$insert_stmt->bindParam(':student_id', $student);
$insert_stmt->bindParam(':value', $value);
$insert_stmt->execute();
}
?>
<html>
<head>
<title>Form</title>
</head>
<body>
<form action="self.php" method="get">
Student:
<select name="student">
<?php while ($row = $student_stmt->fetch(PDO::FETCH_ASSOC)) { ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['firstname'] . " " . $row['lastname']; ?></option>
<?php } ?>
</select>
Sport:
<select name="sport">
<?php while ($row = $sport_stmt->fetch(PDO::FETCH_ASSOC)) { ?>
<option value="<?php echo $row['sport_id']; ?>"><?php echo "$row['sportname']"; ?></option>
<?php } ?>
</select>
Performance: <input name="value" type="text" />
<button type="submit">Submit</button>
</form>
</body>
</html>
Edit:
Made the changes in the code in the suggested comment.
I think all you need to do is to get input values from your form ($variable = $_GET["classinput"];) and then connect to database and write mysqli query with input query for every table.
like this:
$query = mysqli_query($connection, "INSERT INTO STUDENTS(id,class,firstname,lastname) VALUES (null,\"$class\",\"$firstname\",\"$lastname\")");
And do this for all your tables.
I researched a lot and found some solution ,probably not a convincing solution for me.Hence i am posting this question,Please help me
I Have A checkbox with same name and different values like
1.cate.php
<form action="mobile-phones-category.php" method="post">
<input type="checkbox" value="samsung" name="mobile[]"> sams
<input type="checkbox" value="nokia" name="mobile[]"> nolkia
<input type="submit" name="submit" value="SUBMIT" class="btn btn-primary pull-right">
</form>
2.) mobile-phones-category.php
I retrieve the values of check box on submit[array format] and want to search from db..I am using normal mysql_query(not pdos)
$search=$_POST["mobile"];
$search_string = implode(', ', $search);
echo $search_string;
Here i Get something like Nokia,Sams
Next I write a single sql query
include('connection.php');
$query = mysql_query("SELECT * FROM tablename where titles like '%$search_string%' ") or die(mysql_error());
What is happening is that only one value in the array is searched and not all the values in array..What changes should i Make so that all the array element should get searched
Thanks and regards
Use IN keyword in your query instead of LIKE
$query = mysql_query("SELECT * FROM tablename where titles IN ($search_string)" ) or die(mysql_error());
Usage Example:
$query = mysql_query("SELECT * FROM tablename where titles IN ('Nokia','Sams')" ) or die(mysql_error());
This will give you records with title Nokia & Sams from the table.
Like User016 said, I would also recommend using the IN Statement. It searchs for several searchterms, splitted by a ,.
You can find the Doc there:
http://dev.mysql.com/doc/refman/5.1/en/comparison-operators.html#function_in
I am trying to use a dynamic select form to send information to a MySQL database. The user will be able to choose their school, and then select their major from within that school's list (all retrieved from a MySQL table). I then want to send that information to a different table in the database to be stored.
This is what I have for the code thus far:
<select name="school">
<php
$sql = "SELECT school_name, school_id FROM school_table ORDER BY school_name";
$query = mysql_query($sql,$conn);
while($row = mysql_fetch_array($states))
{
echo ("<option value=$row[school_id]>$row[school_name]</option>");
}
?>
</select>
I don't know how to make the second select, which would ideally recognize the school_id from the first table and match it with the corresponding school_id on the second table, which also lists the majors at that school. Also, I don't know how to send the form when it is finally done to a MySQL table.
You could either use a simple form to submit the value from the combobox to the server (as HTTP POST or HTTP GET) and use the value as a variable in you SQL statement or you could use a simple AJAX request to send the necessary information to your php script. Anyway, your serverside code should look like this:
//process.php
$myRetrievedValue = $_POST["school"];
$mySqlStm = "SELECT * FROM foo WHERE bar = '".mysql_escape_string($myRetrivedValue)."'";
On the client side you code could look like this (using a simple form and no AJAX stuff):
<form action="process.php" method="post">
<select name="school">
<php $sql = "SELECT school_name, school_id FROM school_table ORDER BY school_name";
$query = mysql_query($sql,$conn); while($row = mysql_fetch_array($states)) {
echo ("<option value=$row[school_id]>$row[school_name]</option>"); } ?>
</select>
<input name="" type="submit" />
</form>
Please remember: Whenever you use a user input in you query use prepared statements (or at least escape methods as above) to avoid SQL injections.
answer is to select from both tables in one SELECT using joins:
http://dev.mysql.com/doc/refman/5.0/en/join.html
INNER JOIN
SELECT `school_table`.`school_name`,
`school_table`.`school_id`,
`2ndTable`.`school_id`,
`2ndTable`.`major`,
FROM school_table,2ndTable
WHERE `school_table`.`school_id`=`2ndtable`.`school_id`
ORDER BY school_name
or a
LEFT JOIN (returning all columns in the left)
SELECT `school_table`.`school_name`,
`school_table`.`school_id`,
`2ndTable`.`major`,
`2ndTable`.`school_id`
FROM school_table
LEFT JOIN on `school_table`.`school_id`=`2ndtable`.`school_id`
ORDER BY school_name
Please help me with this:
I am creating a survey facility for the administrator. The administrator is asked for the number of questions in the questionnaire. And based on this the rows are created in the survey details table. In the question table the corresponding number of rows are created for the same in the question table.
Now the admin can enter the questions and answers. For this I need to insert the row in question table and update it from the informations collected from FORM using a loop. But the inserted rows are not getting updated simultaneously. Help me with this or is there any other way to do this?
This is my code: Please ignore the programming style as this is the script by a novice:
$sid = intval ($_GET['ids']);
$noq = intval ($_GET['qn']);
for($noq !=0;$noq >=1;$noq--){
$q = "insert into sur_ques (sur_id) values ('$sid')";
$ex = mysql_query($q);
$rs = mysql_affected_rows();
if($rs ==1){ echo" Questions Rows Created Corresponding to Survey Subject";}
?>
<form name="form1" method="post" action="<?php echo($PHP_SELF); ?>">
<table width="500" border="0" cellspacing="1" cellpadding="0">
<tr><br><b>Ques No-<?php echo"$noq";?></b></tr><br>
<tr><textarea name = "q" rows ="10" cols = "70" wrap = "hard" ></textarea></tr><br>
<tr><td><b>Ans 1:</b></td><td><input type="text" name="a1" size="37" /></td></tr>
<tr><td><b>Ans 2:</b></td><td><input type="text" name="a2" size="37" /></td></tr>
<tr><td><b>Ans 3:</b></td><td><input type="text" name="a3" size="37" /></td></tr>
<tr><td><b>Ans 4:</b></td><td><input type="text" name="a4" size="37" /></td></tr>
</table>
<input type = "submit" name="qa" Value = "Add Q&A" />
<input type ="reset" Value="Reset" />
</form>
<?
if ($_POST['qa']){
$id = mysql_insert_id();
$result = mysql_query("update ques set q_txt = '$q', ans1 = '$a1' ans2 = '$a2' ans4 = '$a4' ans4 = '$a4' where q_id = '$id'");
if($r = mysql_num_rows($result)){
echo" Question and answers updated";
}
} else {
break;
}
}
?>
I dont get you .. may be you can put more info like table structure so that i can understand it well.
but one thing for sure you can not update and insert row simultaneously... you will have to insert row into database in order to update row.
I think what you are looking for is mysql_insert_id.
session_start();
$q = "INSERT INTO table (id,key1,key2) VALUES (null,'value1','value2')";
$r = mysql_query($q);
$_SESSION['rowid'] = mysql_insert_id();
then subsequent queries would do:
$sq = "UPDATE table SET key='value',secondkey='secondvalue', WHERE id=$_SESSION['rowid'] ";
$sr = mysql_query($sq);
I don't see the need for a loop when you can insert/update as many columnsas you need in one go as you can see above. Doing it like this you will never need to insert and update at the same time (which is impossible), because you simply start the record with whatever info is available, or even if no info is available, you create an empty row, store the id and then update the row as new infomration becomes available.
"In the question table the corresponding number of rows are created for the same in the question table." - did you mean questions and answers?
Well you have a form, you have two type of inputs (questions[] and answers[]), then in cycle you just insert a question and a corresponding answer text (based on input's key) and connect them (answer should have quesitonID or vise versa, depending on what you insert first and what type of multiplicity connection is between them.. i guess question can have multiple answers)
I have a table in MySQL with 5 data fields: id, name, total marks, percentage, and rank. I already fetch and displayed all data, but I want search and display by 3 fields name: total marks, and rank. These 3 will be entered in text boxes.
Please mention the particular query for this 3 fields search.
As you've had to ask this question, I'd like to first of all point you towards the MySQL manual and the PHP manual. However, I'll also give you some pointers.
First of all, you'll need to post these search values to your PHP code. This can be done using a form.
<form method="POST" action="script.php">
<input name="name" type="text" />
<input name="total_marks" type="text" />
<input name="rank" type="text" />
<input type="submit" value="Search" />
</form>
Then, you'll need to access these values in your PHP script as such.
// script.php
$name = mysql_real_escape_string($_POST['name']);
$total_marks = mysql_real_escape_string($_POST['total_marks']);
$rank = mysql_real_escape_string($_POST['rank']);
// I'll leave SQL injection protection up to you
Finally, you'll need to pass these queries to an SQL query to retrieve the items from your database. As you haven't posted your exact scheme, you'll have to modify this to suit your needs. Also, I've left the actual database loading/access to you.
// script.php
$sql = "SELECT * FROM `table` WHERE (
`name` = '{$name}' AND
`total_marks` = '{$total_marks}' AND
`rank` = '{$rank}'
)";
Rather than passing the variables directly to the SQL query and using mysql_real_escape_string or similar functions, I'd look in to using PDO for security and for some database abstraction.
If I understand you correctly
Select *
FROM Keys
WHERE name = 'stringName' AND total_marks = numberTotalMarks AND rank = procent