store array of rows into mysql database - php

I have write some php code to retrieve some records from a mysql database in the form of table. the table have three columns where first two were filled up from the database and the third is a drop down list for each row. Now I want to select the drop down list from the populated rows and store the information of each rows in a new database.
Please view the codes and reply for your suggestions.
<html>
<?
// data from the "recordentry.php";
$date = $_POST['date'];
$course = $_POST['course'];
$period = $_POST['period'];
$batch = $_POST['batch'];
$subject = $_POST['subject'];
$faculty = $_POST['faculty'];
?>
<p> Current Date&Time:<? echo $date ?></p>
<form enctype="multipart/form-data" name="f1" method="POST" ACTION="<?=$self ?>"">
<?
$db = "contact";
//mysql_connect(localhost,$_POST['username'],$_POST['pass']);
$link = mysql_connect("localhost", "root", "");
if (!$link)
die("Couldn't connect to MySQL");
mysql_select_db($db, $link) or die("Couldn't open $db: " . mysql_error());
$result = mysql_query("SELECT name,uic FROM student where batch='$batch' AND course='$course' order by name") or die("SELECT ERROR: " . mysql_error());
$num_rows = mysql_num_rows($result);
echo "<table border='1' align='center'><tr><th>Name</th><th>Unique Identification Code</th>
<th>Attendance</th></tr>";
while ($row = mysql_fetch_array($result))
{
//Display the results in different cells
echo "<tr><td align=center>" . $row['name'] . "</td><td align=center>" . $row['uic'] . "</td><td align=center><select name='attendance' style='background-color:#FFC'>
<option>Present
<option>Absent
</select></td></tr>";
$data[] = array(
'name' => $row['name'],
'uic' => $row['uic'],
'attendance' => $row['attendance']
);
}
echo "<tr><td><input type='submit' value='Submit' name='submit_button' />";
echo "</table>";
foreach ($data as $value)
{
$name = mysql_result($value['name']);
$uic = mysql_result($value['uic']);
$a_status = mysql_result($value['attendance']);
$db = "contact";
$link = mysql_connect("localhost", "root", "");
//$link = mysql_connect("localhost",$_POST['username'],$_POST['password']);
if (!$link)
die("Couldn't connect to MySQL");
mysql_select_db($db, $link) or die("Select Error: " . mysql_error());
$result = mysql_query("INSERT INTO attendance(date, course, period, batch, subject, faculty,name, uic, attendance) VALUES ('$date', '$course', '$period', '$batch', '$subject', '$faculty', '$name', '$uic', '$a_status')") or die("Insert Error: " . mysql_error());
mysql_close($link);
}
?>
</form>
</html>
the above code can populate the table off all the retrieved data from the database. but after submit it can not store the last three fields $name, $uic and $attendance. so, please help me.

Try this:
$name = mysql_result($result, $value['name']);
$uic = mysql_result($result, $value['uic']);
$a_status = mysql_result($result, $value['attendance']);
This will get the values once - but you reuse $result in that query (when you insert) so it will get overwritten. Change either the first call or the second.

Related

inserting into SQL with PHP

Essentially I want to:
pull info from mySQL server
create a table of students with their name, phone number, and exam date
I want a checkbox next to each student pulled from mySQL and when the checkbox is clicked and the user hits submit, it inserts a value into mySQL column 'contacted'under that specific student. The value will either be "yes" or "NULL"
I used primary key (id) which auto increments to create unique checkbox names for each student
application: The user will retrieve a table of our students and their exam dates. The user will call (via phone) the students and ask about their exam. Once the user has contacted that student, they check the checkbox to show that that particular student has already been contacted. That information will be stored in mySQL for that particular student to show that student was contacted.
here is my code:
<?php
define('DB_NAME', 'Students');
define('DB_USER', 'admin');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
$sql = sprintf("SELECT id,f_name,l_name,phone,exam_date FROM Student_data");
$result = mysql_query($sql);
$table_count = 0;
$student_id = array();
echo "<script>
function DoTheThing()
{
" .
for($x = 0; $student_id[$x] != NULL; $x++)
{
$in = sprintf("INSERT INTO Student_data (contacted) VALUES ('". $_POST[$row['id']] ."') WHERE id = '" . $row['id'] . "';" );
$db_selected->mysql_query($in)
}
. "
}
</script>";
echo "<table width= 400 border=1><form action=\"DoTheThing()\" method=\"POST\">
<tr>
<th width='175' scope='col'>Name</th>
<th width='150' scope='col'>Phone</th>
<th width='125' scope='col'>Exam Date</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td><center>" . $row['f_name'] . " ". $row['l_name']. "</center></td>";
echo "<td><center>". $row['phone'] ."</center></td>";
echo "<td><center>". $row['exam_date'] ."<input type=\"checkbox\" name=\"" . $row['id'] . "\" value=\"yes\"></center></td>";
echo "</tr>";
$student_id[$table_count] = $row['id']
$table_count = +1;
}
echo "</form></table>
<br/><br/><input style = \"height:35px;width:95px;font-size:20px;\" type=\"submit\" name=\"submit\" value=\"Submit\">
";
mysql_close($link);
?>
edit: Sorry, realized I never posted my question
It stopped working when I attempted to insert the "yes" or "NULL" value into mySQL. I am very new to mySQL and was wondering if any of my statements were wrong.
This should be a very big boost of help, basically a shell. All that is left to do is inserting the data into your SQL server.
I commented the code so you could see what was going on, when, and where.
Also, you should definitely stay AWAY from mysql_* as it's deprecated. My example was made using mysqli_*. Another options would be PDO.
<?php
//Set variables (Can be done on another file for more security)
$Host = "Localhost";
$User = "admin";
$Pass = "password";
$DB = "Students";
//Connect to the databse using mysqli. NOT MYSQL WHICH IS DEPRECATED
$con = mysqli_connect($Host, $User, $Pass, $DB);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//if submitted
if(isSet($_POST['submit'])) {
//submit data using mysqli_query and then reload the page.
//clear POST variables before you reload the page.
unset($_POST);
//reload the page
echo "<META http-equiv='refresh' content='0'>";
} else { //if not submitted
//define search variable, and query it.
$db_selected = mysqli_query($con, "SELECT id,f_name,l_name,phone,exam_date FROM Student_data");
//Start table
echo "<form method='POST'>";
echo " <table>";
echo " <tr>";
echo " <th>Name</th>";
echo " <th>Phone</th>";
echo " <th>Exam Date</th>";
echo " <th></th>";
echo " </tr>";
//Loop through sql database
while($row = mysqli_fetch_array($check)) {
echo " <tr>";
echo " <td>".$row['f_name']." ".$row['l_name']."</td>";
echo " <td>".$row['phone']."</td>";
echo " <td>".$row['exam_date']."</td>";
echo " <td><input type='checkbox' name='checkbox['".$row['id']."']' value='1'></td>";
echo " </tr>";
}
//end table
echo " </table>";
echo "<input type='submit' value='Submit' name='submit'>";
echo "</form>";
}
?>

Getting Selectbox values from the database using PHP and mysqli

I want to pick up peoples names from a phpmyadmin database and place them in a HTML select box, when the user picks a name from the select box it should display the detail from the database for that person in a table. I can't seem to get this to work, I can get the names to pick up from the database and display in a select box but when you click on the name it seems to bring up every record in the database rather than just the one for that person. I am using mysql rather than mysql. Here is my code
This is my back end stuff
<?php
$conn = mysqli_connect("localhost", "root", "root") or die ("No connection");
mysqli_select_db($conn, "flat") or die("db will not open");
$query = "select FlatCode, Address from FLAT";
$result = mysqli_query($conn, $query) or die("Invalid query");
echo "<table border='1'><tr><th>modulecode</th><th>studentnum</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>" . $row[0] . "</td><td>" . $row[1] . "</td></tr>";
}
echo "</table>";
mysqli_close($conn);
?>
this is my front end stuff
<font size="4"> Choose an Owner Name</font><br><br>
<form action="flat.php" method="post">
<select name="name">
<?php
$con = mysqli_connect("localhost", "root", "root") or die ("No connection");
mysqli_select_db($con , "flat") or die ("db will not open");
$query = "SELECT distinct OwnerName, FlatCode, Address from FLAT";
/*$query= $_POST ("name")
function change_guery($query)
mysqli_use_result*/
$result = mysqli_query($con, $query) or die("Invalid query");
while($rows = mysqli_fetch_array($result))
{
echo "<option value=\"" . $rows[0] . "\">" . $rows[0] . "</option>";
}
echo "</select>";
mysqli_close($con);
?>
<input type="submit" value="Submit Value">
</form></body></html>
There is a problem in your flat.php code. You are posting the the info correctly via form but you forgot to receive it via $_POST in flat.php.
See the following code and comments in it, it should work -
<?php
$n = $_POST["name"];//we receive the name passed by the form
$conn = mysqli_connect("localhost", "root", "root") or die ("No connection");
mysqli_select_db($conn, "flat") or die("db will not open");
$query = "select FlatCode, Address from FLAT WHERE `OwnerName` = '$n' LIMIT 1";//see the changes here
$result = mysqli_query($conn, $query) or die("Invalid query");
echo "<table border='1'><tr><th>modulecode</th><th>studentnum</th></tr>";
$row = mysqli_fetch_array($result);
//as the result will return 1 row only so we dont need while loop here
echo "<tr><td>" . $row[0] . "</td><td>" . $row[1] . "</td></tr>";
echo "</table>";
mysqli_free_result($result);//dont forget to free result
mysqli_close($conn);
?>

How to display database value in form list

I've created drop down list with value name from the database. When I select the value from the drop down list, other data will appear in other textfield based on the database. The submit process was doing fine except when I check on the list. The drop down list value didn't appear in the list but other data did.
This is my adding form:
<tr><td width="116">Medicine name</td><td width="221">
<center>:
<select name="name" id="name" >
<option>--- Choose Medicine ---</option>
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("arie");
$sql = mysql_query("SELECT * FROM tabelmedicine ORDER BY name ASC ");
if(mysql_num_rows($sql) != 0){
while($row = mysql_fetch_assoc($sql)){
$option_value = $row['priceperunit'] . ',' . $row['stock'];
echo '<option value="'.$option_value.'">'.$row['name'].'</option>';
}
}
?>
</select ></center>
This is a script to display other database value in other textfield when the drop down list is selected:
<script>
var select = document.getElementById('name');
var priceperunit = document.getElementById('priceperunit');
var stock = document.getElementById('stock');
select.onchange = function()
{
var priceperunit_stock = select.value.split(',');
priceperunit.value = priceperunit_stock[0];
stock.value = priceperunit_stock[1];
}
</script>
This is my inserted data into database process:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "arie";
$connect = mysql_connect($host, $user, $pass) or die ('Failed to connect! ');
mysql_select_db($db);
$name=$_POST['name'];
if ($name === "")
{
echo "Please fill all the data";
}
else
{
$query="INSERT INTO `tabelout`(`name`)
VALUES ('$name');";
$result = mysql_query($query) OR die (mysql_error());
echo "You have successfully added new medicine to the database.";
}
?>
This is my list page, where the name didn't show up:
<?php
$con=mysqli_connect("localhost","root","","arie");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM tabelout");
echo "<table border='1'>
<th>name</th>";
while($row = mysqli_fetch_array($result))
{
echo "<td><center>" . $row['name'] . "</center></td>";
}
echo "</table>";
mysqli_close($con);
?>
Make sure your database table has records, If it has records, then change the table structure, Add tr tags where required.
echo "<table border='1'>
<tr><th>name</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td><center>" . $row['name'] . "</center></td></tr>";
}
echo "</table>";

SELECT * FROM Table Where ID

I am trying to retrieve information from my database depending on the ID a user types into my URL.
For example: If USER A went to www.exampleurl.com/index.php?id=1 it would echo out the user's information which has an ID of 1. Same thing if the id was 2, 3, etc. Users are entering their information via a form in a different file called submit.php.
Here is my code to retrieve data depending on ID :
<?php
$id = $_GET['id'];
//Variables for connecting to your database.
$hostname = "";
$username = "";
$dbname = "";
$password = "";
$usertable = "";
//Connecting to your database
$con = mysql_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname, $con);
$query = "SELECT * FROM $usertable WHERE id = $id LIMIT 1";
$result = mysql_query($query, $con);
echo "Hello, " . $result['name'];
?>
Any ideas on if my SELECT request is wrong?
EDIT
Here is my code for showing the data altogether in a table. This works fine.
<?php
//Variables for connecting to your database.
$hostname = "";
$username = "";
$dbname = "";
$password = "!";
$usertable = "";
//Connecting to your database
$con = mysql_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname, $con);
//Fetching from your database table.
$query = "SELECT * FROM $usertable";
$result = mysql_query($query, $con);
echo "<table border=1>
<tr>
<th> ID </th>
<th> Name </th>
<th> Age </th>
</tr>";
while($record = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $record['id'] . "</td>";
echo "<td>" . $record['name'] . "</td>";
echo "<td>" . $record['age'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
→ Try This:
You should consider using PHP PDO as it is safer and a more object oriented approach:
$usertable = "";
$database = new PDO( 'mysql:host=localhost;dbname=DB_NAME', 'DB_USER_NAME', 'DB_USER_PASS' );
$statement = $database->prepare('SELECT * FROM $usertable');
$statement->execute();
$count = $statement->rowCount();
if( $count > 0 ) {
$R = $statement->fetchAll( PDO::FETCH_ASSOC );
for( $x = 0; $x < count($R); $x++ ) {
echo "<tr>";
echo "<td>" . $R[ $x ]['id'] . "</td>";
echo "<td>" . $R[ $x ]['name'] . "</td>";
echo "<td>" . $R[ $x ]['age'] . "</td>";
echo "</tr>";
}
}
else { echo "Error!"; }
you need to use mysql_fetch_assoc function for retrieve the results.
$result = mysql_fetch_assoc(mysql_query($query, $con));
echo "Hello, " . $result['name'];
You should be error checking your mysql_querys:
$query = "SELECT * FROM $usertable WHERE id = $id LIMIT 1";
$result = mysql_query($query, $con);
if(!result)
echo mysql_error();
You should also retrieve the results:
$array = mysql_fetch_assoc($result);
I'll consider some secure features like
Check if $_GET['id'] is set and if is int
Apply Mysql escape with mysql_escape_string() function

comparing two variables using IF/IF..ELSE statement for PHP and inserting into MYSQL

i am doing a count validation on two variables , $row2 with a value of 7 and $row3 with a value of 11. What i want to achieve is that the higher value can only be insert into the DB. The problem now is that $row3 value is bigger than $row2. however it always insert $row2 value into the DB. Is there any wrong with my validation codes?
function tweetCount($hashtag) {
$url = 'http://search.twitter.com/search.atom?q='.urlencode($hashtag).'&rpp=100&result_type=recent';
//echo "<p>Connecting to <strong>$url</strong> ...</p>";
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
$xml = curl_exec ($ch);
curl_close ($ch);
//If you want to see the response from Twitter, uncomment this next part out:
//echo "<p>Response:</p>";
//echo "<pre>".htmlspecialchars($xml)."</pre>";
$affected = 0;
$twelement = new SimpleXMLElement($xml);
foreach ($twelement->entry as $entry) {
$text = trim($entry->title);
$author = trim($entry->author->name);
$time = strtotime($entry->published);
$id = $entry->id;
//echo count($entry->text);
// echo "<em>Posted ".date('n/j/y g:i a',$time)."</em><p>Tweet from <b><u>".$author."</u></b>: <strong>".$text."</strong> </p>";
//echo "<br/>";
}
//echo count($twelemtnt);
//echo count($entry);
echo $number_of_tweets = count($twelement->entry);
}
on my html table , i echo the data out like this:
<?php echo tweetCount($row[2]); ?>
<input type="hidden" name="row2" value="<?php echo tweetCount($row2[2]);?>" />
<input type="hidden" name="row2Ini" value="<?php echo $row2[1];?>" />
<input type="hidden" name="row2Sch" value="<?php echo $row2[2];?>" />
using a POST form i post it to another page where i need to do a count validation to see if which variable $row2 or $row3 have a higher count value and then i will insert the higher value into the DB
admin.php page
$row2 = $_POST['row2'];
$row2Ini = $_POST['row2Ini'];
$row2Sch = $_POST['row2Sch'];
if ( $row2 > $row3 )
{
echo "<br>row2 is more than row 3";
$con = mysql_connect("localhost","root","password");
if (!$con)
{ die('Could not connect: ' . mysql_error());}
mysql_select_db("schoutweet", $con);
$sql2="INSERT INTO matchTable (schInitial, schName,position)VALUES
('$_POST[row2Ini]','$_POST[row2Sch]','top4')";
if (!mysql_query($sql2,$con)){die('Error: ' . mysql_error());}echo "ROW2 record added!<BR>";
mysql_close($con);
}
else if ($row2 < $row3)
{
echo "row3 count is more than row 2";
$con = mysql_connect("localhost","root","password");
if (!$con)
{ die('Could not connect: ' . mysql_error());}
mysql_select_db("schoutweet", $con);
$sql="INSERT INTO matchTable (schInitial, schName,position)VALUES('$_POST[row3Ini]','$_POST[row3Sch]','top4')";
if (!mysql_query($sql,$con)){die('Error: ' . mysql_error());}echo "ROW3 record added!<BR>";
mysql_close($con);
}
Never write connection twice... You should take connect part out of if..else statement...
Check below if it works...
$con = mysql_connect("localhost","root","password");
if (!$con)
{ die('Could not connect: ' . mysql_error());}
mysql_select_db("schoutweet", $con);
if ( $row2 > $row3 )
{
echo "<br>row2 is more than row 3";
$sql2="INSERT INTO matchTable (schInitial, schName,position)VALUES
('$_POST[row2Ini]','$_POST[row2Sch]','top4')";
if (!mysql_query($sql2,$con)){die('Error: ' . mysql_error());}echo "ROW2 record added!<BR>";
}
else
{
$sql="INSERT INTO matchTable (schInitial, schName,position)VALUES('$_POST[row3Ini]','$_POST[row3Sch]','top4')";
if (!mysql_query($sql,$con)){die('Error: ' . mysql_error());}echo "ROW3 record added!<BR>";
}
mysql_close($con);

Categories