Sorry if my english is not correct. I will try my best..
The question is how can I insert record from existing table with insert button. Everything work fine except variable $book. It records value 0 to database. Here is code..
//if the user press "INSERT BOOK" button there will be new record in database
<?php
$reader=$_SESSION['user_id'];
$book=$row['book_id'];
if (isset($_POST['update'])){
$sql = "INSERT INTO `read` (`read_id`, `book`, `reader`) VALUES (LAST_INSERT_ID(), '$book' '$reader')";
$result = mysql_query($sql) or die(mysql_error());
if ($result) {
echo " Yes, it works!";
}
else{
echo "noup!";
}
}
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("/^[ a-zA-Z]+/", $_POST['name'])){
$name=$_POST['name'];
$result = mysql_query("SELECT * FROM book b JOIN `read` r ON (b.book_id = r.book) JOIN users u ON (r.reader = u.user_id) WHERE b.book_name LIKE '%" . $name . "%' or b.writer LIKE '%" . $name . "%' AND u.user_id !=". $_SESSION['user_id']);
$num_rows = mysql_num_rows($result);
if($num_rows>=1){
echo "<table id='table1'>
<tr>
<th>book_id</th>
<th>BOOKNAME</th>
<th>WRITER</th>
<th>PAGES</th>
</tr>";
while($row=mysql_fetch_array($result)){
echo "<form action=add_book.php method='post'>";
echo "<tr>";
echo "<td>" . $row['book_id'] . "</td>";
echo "<td>" . $row['book_name'] . "</td>";
echo "<td>" . $row['writer'] . "</td>";
echo "<td>" . $row['pages'] . "</td>";
//echo "<td>" . "<input type = 'hidden' name = 'hidden' value =" . $row['book_id'] . " </td>";
echo "<td>" . "<input class = 'field' type = 'submit' name = 'update' value = 'INSERT BOOK'>" . " </td>";
echo "</tr>";
echo "</form>";
}//WHILE LOOP
echo "</table>";
}
else{
echo "NO RESULTS";
}//else
}//if(preg_match..)
} //if(isset($_GET['go'])){
} //if(isset($_POST['submit'])){
?>
Related
I wrote this code to retrieve some rows form database
session_start();
$con = mysqli_connect('localhost', 'root', '');
if(!$con)
{
die("not ok");
}
mysqli_select_db($con,"uoh");
$q = " SELECT * FROM student WHERE id = " . $_SESSION['user_id'] ." and password = " . $_SESSION['user_pass'];
$result = mysqli_query($con , $q ) ;
if($row = mysqli_fetch_array($result))
{
echo "this academic transcripts for " . $row["name"];
echo " and the id is " . $row["id"];
}
$q1 = " SELECT student_record.course,student_record.grade,student_record.term,coe_courses.crd
FROM student_record INNER JOIN coe_courses ON student_record.course_number = coe_courses.course_number
where student_record.id = ".$_SESSION['user_id'] ;
$result = mysqli_query($con , $q1 ) ;
if($row = mysqli_fetch_array($result))
{
echo "<br />";
echo "<table border=\"1\" style=\"width:500\">";
echo "<tr>";
echo "<th>coe_courses</th>";
echo "<th>terms</th>";
echo "<th>Grades</th>";
echo "<th>CRD</th>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row["course"]. "</td>";
echo "<td>" . $row["term"]. "</td>";
echo "<td>" . $row["grade"]. "</td>";
echo "<td>" . $row["crd"]. "</td>";
echo "</tr>";
echo "</table>";
}
The problem is that only shows the first row while I have three rows in phpMyAdmin.
enter image description here
You need to call fetch_* repeatedly to retrieve all rows from your result set; each time you call it it retrieves the next row in the result set.
In your sample code above, you would replace
if ($row = mysqli_fetch_array($result))
{
with
while ($row = mysqli_fetch_array($result))
{
This will loop until fetch_array tries to read beyond the last record in $result, at which point fetch_array returns false and the loop exits.
I have this code of a table here:
while($record=mysql_fetch_array($myData) ) {
echo "<form action=mydata3.php method=post>";
echo"<tr>";
echo "<td>" . $record['Id'] . "</td>";
echo "<td>" . $record['Name'] . "</td>";
echo "<td>" . $record['Surname'] . "</td>";
echo "<td align='center'>" . "<input type=checkbox name=attendance value=". $record['Attendance'] . " </td>";
echo "</form>";
echo"<tr>";
}
I would like I click the attendance button to update the records of the sql database.
If the checkbox of each student is checked the the value of attend should be Yes if is not checked it should be No. I managed to do something but is getting the checkbox value of the first student and it gives it to all the students.
Function:
if (isset($_POST['updatesec'])) {
$sql = " SELECT * FROM students";
$con = mysql_connect("localhost", "root", "");
if (!$con) {
die("Cannot connect: " . mysql_error());
}
$myData = mysql_query($sql, $con);
while ($students = mysql_fetch_array($myData)) {
$UpdateQuery = "UPDATE students SET Attendance=' " . check() . " ' WHERE Id=$students[Id]";
mysql_query($UpdateQuery, $con);
}
}
Function check() {
if (isset($_POST['attendance'])) {
return 'yes';
} else {
return 'no';
}
}
update: I have change the code as follows
while($record=mysql_fetch_array($myData) ) {
echo "<form action=studentstable.php method=post>";
echo"<tr>";
echo "<td>" . $record['Id'] . "</td>";
echo "<td>" . $record['Name'] . "</td>";
echo "<td>" . $record['Surname'] . "</td>";
echo "<td align='center'>" . "<input type=checkbox name='attendance[".$record['Id']."]' value='". $record['Attendance'] . "' /> </td>";
echo "</form>";
echo"<tr>";
}
if (isset($_POST['updatesec'])) {
$myData = mysql_query( $sql,$con);
while ($students = mysql_fetch_array($myData)) {
$UpdateQuery = "UPDATE students SET Attendance= '" . check($students['Id']) . " ' WHERE id=$students[Id]";
mysql_query($UpdateQuery, $con);
}
}
Function check($id) {
if (isset($_POST['attendance'][$id])) {
return 'yes';
} else {
return 'no';
}
}
But is still only working for the first check box of the table
U need to change the name of your checboxes and your check function:
function check($id) {
if (isset($_POST['attendance'][$id])) {
return 'yes';
} else {
return 'no';
}
}
echo "<td align='center'>" . "<input type=checkbox name='attendance[".$record['Id']."]' value='". $record['Attendance'] . "' /> </td>";
This way will u have an array of all the checkboxes with a link to the id of the attendant.
while ($students = mysql_fetch_array($myData)) {
$UpdateQuery = "UPDATE students SET Attendance=' " . check($students['Id']) . " ' WHERE Id=$students[Id]";
mysql_query($UpdateQuery, $con);
}
On a sidenote. mysql_* functions are deprecated. U should move on to mysqli or PDO and start using prepared statements
Scenario : The administrator is to assign different companies to different student.
Problem : All student is given the same company of the last student in the form.
How do i make my hidden input work so that the correct selected drop down values of companies for each estudent to reflect correctly on the database?
$result = mysqli_query($con,"SELECT student_id, admin_no, name, GPA, gender FROM student_details WHERE jobscope1= 'Information Technology' ORDER BY `GPA` DESC; ");
$result2 = mysqli_query($con,"SELECT job_title FROM job_details WHERE jobscope='Information Technology' ORDER BY `job_title` ASC;");
/*options sections start*/
$options= '';
while ($row2 = mysqli_fetch_assoc($result2))
{
$options .='<option value="'. $row2['job_title'] .'"> '. $row2['job_title'] .'</option>';
}
/*options sections end*/
//return the array and loop through each row
while($row = mysqli_fetch_assoc($result))
{
$adminno = $row['admin_no'];
$name = $row['name'];
$gpa = $row['GPA'];
$gender = $row['gender'];
echo "<tr>";
echo '<input type=hidden name=admin_no value='. $adminno . '/>';
echo "<td>" . $adminno . "</td>";
echo "<td>" . $name . "</td>";
echo "<td>" . $gpa . "</td>";
echo "<td>" . $gender . "</td>";
echo "<td><select name='ddl' { myform.submit('') }'>".$options."</select></td>";
}
echo "</tr>";
The php form action :
$query = mysqli_query($con, "SELECT * FROM student_details WHERE jobscope1 = 'Information Technology';");
while ($row = mysqli_fetch_assoc($query))
$complist = $_POST['ddl'];
$result4 = mysqli_query($con, "UPDATE `student_details` SET `company`= '" . $complist . "' WHERE `jobscope1` = 'Information Technology';");
Try this:
//return the array and loop through each row
while($row = mysqli_fetch_assoc($result))
{
$adminno = $row['admin_no'];
$name = $row['name'];
$gpa = $row['GPA'];
$gender = $row['gender'];
echo "<tr>";
//changed here (this is called an input array which makes it hold multiple
//values with same name)
echo "<input type='hidden' name='admin_no[]' value='". $adminno ."'/>"; //edited
echo "<td>" . $adminno . "</td>";
echo "<td>" . $name . "</td>";
echo "<td>" . $gpa . "</td>";
echo "<td>" . $gender . "</td>";
//changed here too
echo "<td><select name='ddl[]' >".$options."</select></td>"; //edited
}
In your PHP:
if(isset($_POST['ddl'])){
foreach( $_POST['ddl'] as $index => $val ) //edited extra { here
{
$result4 = mysqli_query($con, "UPDATE `student_details`
SET `company`= '" . $val . "'
WHERE `jobscope1` = 'Information Technology'
AND `admin_no` = '".$_POST['admin_no'][$index]."';");
}
}
In this all your values will be updated (whether you changed any dropdown or not). If you want to limit only the changed dropdowns to be updated then you can have a hidden input variable which changes its value on change of dropdown and update your query only if the hidden input matches.
Here is the page show table from database and every row has textbox, and b_id to update table.
$result2 = mysqli_query($con,"SELECT * FROM zahialga WHERE bid IN ($imp)");
while($row = mysqli_fetch_array($result2))
{
echo "<tr>";
echo "<td>" . $row['b_id'] . "</td>";
echo "<td>" . $row['materials'] . "</td>";
echo "<td>" . $row['num'] . "</td>";
echo "<td> <input type='text' name='sh_num[]' maxlength='10'></td>";
echo "</tr>";
echo "<input type='hidden' name='b_id[]' value='" . $row['bid'] . "'>";
}
echo "</table>";
echo "<input type='submit' value='Илгээх'/>";
this is update page.
$con=mysqli_connect("localhost","root","","login");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sh_id_query = mysqli_query($con,"SELECT sh_id FROM zahialga order by bid desc limit 1");
$sh_id1 = $sh_id_query->fetch_object()->sh_id;
$sh_id2 = $sh_id1 + 1;
$count = count(array_filter($_POST["sh_num"]));
for($i=0;$i<$count;$i++)
{
$insert = mysqli_query($con,"UPDATE table SET
sh_id='{$sh_id2}',
sh_num='{$_POST['sh_num'][$i]}'
WHERE bid = '{$_POST['$b_id'][$i]}'");
}
this is getiing Notice: Undefined index: $b_id error. What im missed?
BTW sorry about my bad english.
There should be no $ sign:
$_POST['b_id'][$i]
$insert = mysqli_query($con,"UPDATE table SET
sh_id='{$sh_id2}',
sh_num='{$_POST['sh_num'][$i]}'
WHERE bid = '{$_POST['$b_id'][$i]}'");
// ^ additional $ sign here
should be
$insert = mysqli_query($con,"UPDATE table SET
sh_id='{$sh_id2}',
sh_num='{$_POST['sh_num'][$i]}'
WHERE bid = '{$_POST['b_id'][$i]}'");
I have an admin area in an ecommerce website whereby the admin can view all users on the allusers.php page. The users are listed in a table with their personal information, however i have a 'view profile' button near each user whereby if you was to click on it, it would take you to another page where you can view that specific users past orders.
the following is the code i have for allusers.php:
<?php
$result = mysql_query("SELECT * FROM customers ")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'There Arent Any Orders Yet';
} else {
echo "<table border='0'><table border width=100%><tr><th>First Name</th><th>Surname</th><th>Address</th><th>E-Mail</th><th>Username</th><th>View Profile</th>";
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name']. "</td>";
echo "<td>" . $info['surname']. "</td>";
echo "<td>" . $info['address1']. $info['address2']. $info['city']. $info['postcode']." </td>";
echo "<td>" . $info['email']. "</td>";
echo "<td>" . $info['username']. "</td>";
echo "<td>" . " <a href='view.php'>View</a> </td>";
}
}
echo "</tr>";
echo "</table>";
?>
the view.php page is as follows:
<?php
$result = mysql_query("SELECT * FROM order WHERE ......dont know what to enter here")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'There Arent Any Orders For This Customer Yet';
} else {
echo "<table border='0'><table border width=100%><tr><th>Product</th><th>Quantities</th><th>Date</th>";
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name']. "</td>";
echo "<td>" . $info['quantity']. "</td>";
echo "<td>" . $info['date']. " </td>";
}
}
echo "</tr>";
echo "</table>";
?>
I have a mysql database with the following fields & tables:
Customers - id, name, surname, address1, address2, city, postcode, email, username, password
Products - serial, name, description, price, picture
Order - id, name, quanitity, price, date, username
Thanks for any help provided
Your code lacks any sort of security mechanisms... This is very bad, especially in an e-commerce setting.
Excusing that, you would pass the username to the view page in the URL.
echo "<td>" . " <a href='view.php?user=" . $info['username'] . "'>View</a> </td>";
In your view page, you would get the parameter from the URL and include it with your query.
if (isset($_GET) && isset($_GET['user'])) {
$user = mysql_real_escape_string($_GET['user']);
} else {
header('Location: allusers.php');
exit(); // boot them back to the previous page.
}
$result = mysql_query("SELECT * FROM order WHERE username = '" . $user . "'")
A simple method could be the follow. Replace this line in alluser.php
echo "<td>" . " <a href='view.php'>View</a></td>";
with this one
echo '<td>View</td>';
and then, in your view.php have
if (isset($_GET['username']) && $_GET['username'] != '')
{
$username = mysql_real_escape_string($_GET['username']);
$result = mysql_query("SELECT * FROM order WHERE username = '$username'");
}
else
{
// No user specified. Do other statements
}
Please note the use of:
The user of the mysql_real_escape_string() function to protect from Sql injection (would be better the use of a prepared statements)
The use of the parameter username in the first page to pass the value of the username to the second page
The use of the $_GET global array to retrieve the parameter
Try this:
allusers.php
<?php
$result = mysql_query("SELECT * FROM customers ")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'There Arent Any Orders Yet';
} else {
echo "<table border='0'><table border width=100%><tr><th>First Name</th><th>Surname</th><th>Address</th><th>E-Mail</th><th>Username</th><th>View Profile</th>";
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name']. "</td>";
echo "<td>" . $info['surname']. "</td>";
echo "<td>" . $info['address1']. $info['address2']. $info['city']. $info['postcode']." </td>";
echo "<td>" . $info['email']. "</td>";
echo "<td>" . $info['username']. "</td>";
echo "<td>" . " <a href='view.php?user={$info['username']}'>View</a> </td>";
}
}
echo "</tr>";
echo "</table>";
?>
view.php
<?php
$user = mysql_real_escape_string($_GET['user']);
$result = mysql_query("SELECT * FROM order WHERE user = '$user'")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'There Arent Any Orders For This Customer Yet';
} else {
echo "<table border='0'><table border width=100%><tr><th>Product</th><th>Quantities</th><th>Date</th>";
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name']. "</td>";
echo "<td>" . $info['quantity']. "</td>";
echo "<td>" . $info['date']. " </td>";
}
}
echo "</tr>";
echo "</table>";
?>