I created 3 tables in my database "Colleges" in PhpMyAdmin. The names of the tables are "cool", "data" and "tab". The first table "cool" consists of the the names of the states of India. It has two columns : ID and Statename. From the data in this table, I created a drop down list in HTML form. Further the HTML form consists of the name, email id, contact and the address. The user has to fill in the details and select his/her state from the drop down list. Now, the user input consisting of name, email id, contact and the address goes into the second table "data" and the selected state from the drop down list goes into the 3rd table "tab", "tab" consists of 2 columns ID and stat where the state name gets stored here. I joined the above two tables "data" and "tab" using inner join of SQL. When I fetched the data in another web page, the name, email id, contact and address are getting printed but not the the statename. Instead of the state name, ID of the statename (as given in table cool) is getting printed.
I want state name to get printed.
Here is the drop down list created using the data from my database :
<td>State :</td>
<td>
<?php
$mysqli = new mysqli('localhost', 'root', '', 'colleges');
$resultset = $mysqli->query("SELECT ID, Statename from cool");
?>
<select name="state">
<?php
while($rows = $resultset->fetch_assoc())
{
$ID = $rows['ID'];
$Statename = $rows['Statename'];
echo "<option value='$ID'>$Statename</option>";
}
?>
</select>
</td>
</tr>
And what are the changes to be done here to insert the selected dropdown state name into the table in my database ?
<?php
$connection = mysqli_connect("localhost", "root", "", "colleges");
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$name = $_POST['name'];
$email = $_POST['email'];
$contact = $_POST['contact'];
$address = $_POST['address'];
$state = $_POST['state'];
if($name !=''||$email !=''){
//Insert Query of SQL
$insert = "INSERT Into data(student_name, student_email, student_contact, student_address) values ('$name', '$email', '$contact', '$address')";
$query = mysqli_query($connection, $insert);
$insert2 = "INSERT Into tab(stat) values ('$state')";
$query2 = mysqli_query($connection, $insert2);
echo "<br/><br/><span>Data has been inserted successfully</span>";
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank</p>";
}
}
mysqli_close($connection); // Closing Connection with Server
?>
3). The printing part:
<?php
$hostname = "localhost";
$dbname = "colleges";
$username = "root";
$password = "";
$conn = mysqli_connect("$hostname","$username","","$dbname");
if(mysqli_connect_errno())
{
echo "Failed to Connect MySQL (phpmyadmin) Database: ".mysqli_connect_error();
}
$query = ("select student_name, student_email, student_contact, student_address, stat from data t2 inner join tab t3 on t2.ID=t3.ID");
$result = mysqli_query($conn, $query);
echo "<center>";
echo "<h1>Student list</h1>";
echo "<hr/>";
echo"<table border = '1'>
<tr>
<th>Name</th>
<th>Email</th>
<th>Contact</th>
<th>Address</th>
<th>State</th>
</tr>";
while ($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>".$row['student_name']."</td>";
echo "<td>".$row['student_email']."</td>";
echo "<td>".$row['student_contact']."</td>";
echo "<td>".$row['student_address']."</td>";
echo "<td>".$row['stat']."</td>";
echo "</tr>";
}
echo "</table>";
echo "</center>";
mysqli_close($conn);
?>
echo "<option value='$ID'>$Statename</option>";
and
$state = $_POST['state'];
and
$insert2 = "INSERT Into tab(stat) values ('$state')";
You are actually not inserting the name of the state, but it's id, as the select return the selected option's value, not it's content. You can either change the first line to
echo "<option value='$Statename'>$Statename</option>";
which is a weird solution, or just use a join in your mysql query to get the statename
JOIN ON cool.ID = tab.stat
Extention:
When you use select, the innerHTML of option is displayed, but the value is sent in POST. So if you write
<select name="state">
<option value="1">name</option>
</select>
You will see name name, but the 1 will be sent.
On the next page, $State = $_POST['state']; will have $State the value of '1'. In the SQL you put this value to your stat field in your database, with a generated ID. It means, your ID won't hold any data, but the state field will!
So when printing on the third page, you have to join the list of states by it's ID with the stored stateid in the 'state' field. Then you will be able to print the statenames.
"SELECT * FROM t2 LEFT JOIN t3 ON t2.?? = t3.?? LEFT JOIN t1 ON t1.ID = t3.state"
Or something similar. Do you have a field you can use to join the t2 and t3 tables? It seems you are losing data when inserting to your database.
Related
Im currently constructing a database using PHP, HTML and MySQL.
I have an events table. Event_id is the primary key. When someone registers for an event they input their student_id and they also select an event from a dropbox that pulls the events from my events table. I have an event_registration table which records all entries into this form. I have event_id in my event_registration table and I'm trying to make it so that when someone selects a certain event, that event's id automatically goes into the event_registration table. My PHP code at present is this:
$student_id = $_POST['student_id'];
$title = $_POST['title'];
$sql = "select event_id from events where title LIKE $title";
$db->select_db($database);
$event_id = $db->query($sql);
$q = "INSERT INTO event_registration (";
$q .= "student_id, event_id, title";
$q .= ") VALUES (";
$q .= "'$student_id', '$event_id', '$title')";
$result = $db->query($q);
The student_id, title, and registraion_id (auto- increment) are inserting fine, but event_id is always showing up as 0, I'm not sure where I'm going wrong. Any help is appreciated.
<td style="width: 176px; height: 23px">Event Title</td>
<td style="height: 23px"><select name="title" style="width: 124px">
<?php
include ("detail.php");
$sql = mysqli_query($db, "SELECT title FROM events");
while ($row = $sql->fetch_assoc()){
?>
<option><?php echo ($row['title']); ?></option>";
<?php
}
?>
</select></td>
my dropdown code
The problem you seem to be having is:
$event_id = $db->query($sql);
Probably doesn't give you the number you're expecting right away, instead you need to fetch like this:
$result= $db->query($sql);
$result = $result->fetch_assoc();
$event_id = $result['event_id'];
However, based on your comment, you're constructing your dropdown with this:
<?php
include ("detail.php");
$sql = mysqli_query($db, "title FROM events");
while ($row = $sql->fetch_assoc()){
?>
<option><?php echo ($row['title']); ?></option>
<?php } ?>
You can do this instead:
<?php
include ("detail.php");
$sql = mysqli_query($db, "SELECT event_id,title FROM events");
while ($row = $sql->fetch_assoc()){
?>
<option value="<?php echo $row['event_id']; ?>"><?php echo ($row['title']); ?></option>";
<?php } ?>
Notice how I'm also adding event_id on the select caluse. WIth this the users will see the title as expected, but you'll get the id directly with POST like this:
$event_id = $_POST['event_id'];
You DO have to change the name of the select dropdown to event_id instead of title like this:
<select name="event_id">
I'm making a web site for a business and in the "car list" I would like to take information from 2 tables of my data base, one for the car info (name, price...) and the other one for the images URL table.
Example of my code:
$mysqli = new mysqli("localhost","root","","database") or die("1");
$sql = "SELECT * FROM cars WHERE type= '".$cartype."'";
$result = $mysqli->query($sql);
if($result)
{
while($row = $result->fetch_assoc())
{
?>
<table>
<tr>
<td> HERE IMAGE URL FROM TABLE 2 </td>
<td> <?php echo $row['name']; ?> INFO FROM TABLE 1 </td>
</td>
</table>
<?php
}
}
How can I connect to table 2 and put the info in my while loop?
Thanks a lot.
You are going to have to join your two database tables in your select query. To do that you need an id in your photos table that links it to your cars table.
Example:
$sql = "SELECT name,url FROM cars,photos WHERE cars.id = photos.car_id AND type= '".$cartype."'";
Then use
$row['name']; $row['url'];
In our system they asked us to add research interest but when we add new user, we should assign an interest to him/her. It's adding successfully to the database table, we have problem which is we get zero record in the interest_id database table, why?
Here all research interest added successfully to database:
As you see in picture below when admin add a new user he chooses multiple interests and assign them to a user:
Here is screenshot of user profile as you can see interests that admin assigned to new user:
The problem is that it don't write interest id to database?
Below you can see the codes and SQL table:
<p>
<label>Research Areas</label>
<select name="interest_id[]" class="small-input" multiple>
<?php
$query = "SELECT * FROM research_interest ORDER BY name ASC";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_object($result))
{
?>
<option value="<?php echo $row->id; ?>"><?php echo $row->name; ?></option>
<?php
}
?>
</select>
</p>
Here is also codes for MySQL:
if(isset($_POST['action'])) {
switch($_POST['action']) {
case 'user_add':
$user_id = mysqli_real_escape_string($link,$_POST['user_id']);
$email = mysqli_real_escape_string($link,$_POST['email']);
$password = rand_pass(8);
$title_id = intval($_POST['title_id']);
$user_type_id = intval($_POST['usertype_id']);
$department_id = intval($_POST['department_id']);
$view_publication = mysqli_real_escape_string($link,$_POST['publication']);
$referee = mysqli_real_escape_string($link,$_POST['referee']);
$gender = mysqli_real_escape_string($link,$_POST['gender']);
$creation_date = date('Y.m.d');
//Interest
if(!empty($_POST['interest_id']) && is_array($_POST['interest_id'])) {
foreach ($_POST['interest_id'] as $interest)
{
$query = "INSERT INTO user_interest (user_id, interest_id)
VALUES ('$user_id', '$interest')";
$result = mysqli_query($link,$query);
}
}
//SQL Query
$query = "INSERT INTO user (user_id, email, title, user_type_id, department_id, referee, gender, password, view_publication, creation_date)
VALUES ('$user_id', '$email', '$title_id', '$user_type_id', '$department_id', '$referee', '$gender', '$password', '$view_publication', '$creation_date')";
$result = mysqli_query($link,$query);
echo '<script type="text/javascript">';
echo 'window.location = "mail.php?action=user_mail&user_id='.$user_id.'"';
echo '</script>';
break;
}
}
And this is a user_interest table shows that these three research IDs assign to user 1
but here it show that interest_id is zero , it don't shows ids of research interest that added to user 1
You are not including interest_id in your Insert query to the users table. So the table is assigning a default value of 0.
You're not inserting anything into the "interest_id" column in the second query so it's defaulting to zero. It looks like you're trying to set up a many to many relationship (one user can have many interests and one interest can belong to many users). In that case you'll need to set up a junction table (http://en.wikipedia.org/wiki/Junction_table) to handle the relationship.
I am new to php and trying to learn. I m also trying to make an web application "school management system".
I am getting problem while i am inserting records in student and parents table from the same form, the form is ok and its inserting record in student table but not in parents table.
in parents and student table student_id is common and in student table student_id contain primary key and in parents table it contain foreign key.
my code is given below:
<?php>
if(isset($_POST['submit'])){
$reg = $_POST['reg_no'];
$s_name = $_POST['student_name'];
$s_father = $_POST['student_father'];
$p_last_name = $_POST['parent_lastname'];
$s_birth = $_POST['student_birth'];
$p_phone = $_POST['parent_phone'];
$p_address = $_POST['parent_address'];
$school_name = $_POST['school_name'];
$batch = $_POST['session_batch'];
//filtering variables
$reg_no = mysql_real_escape_string($reg);
$student_name = mysql_real_escape_string($s_name);
$student_father = mysql_real_escape_string($s_father);
$parent_last_name= mysql_real_escape_string($p_last_name);
$student_birth = mysql_real_escape_string($s_birth);
$parent_phone = mysql_real_escape_string($p_phone);
$parent_address = mysql_real_escape_string($p_address);
$school = mysql_real_escape_string($school_name);
$batch = mysql_real_escape_string($batch);
//connecting to db by including db file
include_once('include/dbconnect.php');
$db_select = mysql_select_db($server_db_name,$db_connect);
if ($db_connect)
{
$student_query = "INSERT INTO students (school_id, session_id, student_name,
student_father, student_birthdate, registration_no) VALUES
('$school','$batch','$student_name','$student_father','$student_birth','$reg_no')";
$s_query = mysql_query($student_query) or DIE ("error. while inserting records in
student");
/* here im trying to select student_id which is inserted above to insert data in
parents table*/
$id_query = mysql_query("SELECT * FROM students WHERE student_id = $student_name
LIMIT 1") or DIE ("Could complete the id query");
while ($id_result = mysql_fetch_array($id_query))
{ $s_id = $id_result['student_id'];
$parent_query = "INSERT INTO parents (school_id, student_id, parent_name,
parent_lastname, parent_phone, parent_address)
VALUES('$school','$s_id','$student_father','$parent_last_name',
'$parent_phone','$parent_address')";
$p_query = mysql_query($parent_query);
if (!$parent_query) { echo "error. while inserting records in student"; }
}
mysql_close($db_connect);
header('location:admin.php?student');
}
else {
echo "Error While Connecting to server";
}
}else {
header('location:admin.php?error');
}
?>
Like JOE LEE has mentioned in above snippet,
$generated_key=mysql_insert_id();
// this line of code actually returns the auto generated id, of course I am guessing you want the auto incremented value from the student table for the parent table.
find id u Last inserted, use mysql_insert_id()
<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf ("Last inserted record has id %d\n", mysql_insert_id());
?>
This is my code
echo '<input type="submit" name="submit">';
I am getting the data from another table with this query
if($_POST['submit'])
{
$sql = mysql_query('SELECT q.username, q.firstanme,q.lastname FROM quizgroup q');
foreach($sql as $s)
{
$username = $s->username;
$firstname = $s->firstname;
$lastname = $s->lastname;
$sql = mysql_query('INSERT INTO user(username,firstname,lastname) VALUES('.$username.','.$first.','.$last.')');
}
}
Try this
insert into user (SELECT username, firstanme, lastname FROM quizgroup)
This statement will copy the data from quizgroup to user table
Dont use "values" keyword when copy the data
Look at this
http://dev.mysql.com/doc/refman/5.0/en/insert-select.html