I am using the following code to query my database but the page shows blank!
I can't see where the problem is! Please help.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Extract Student Data</title>
</head>
<body bgcolor="white">
<?php
include 'db.inc';
// Show all student data in a <table>
function displayStudentsList($connection,$query,$Year)
{
// Run the query on the DBMS
if (!($result = # mysql_query ($query, $connection)))
showerror( );
// Find out how many rows are available
$rowsFound = # mysql_num_rows($result);
// If the query has results ...
if ($rowsFound > 0)
{
// ... print out a header
echo "Students data Of Year $Year<br>";
// and start a <table>.
echo "\n<table>\n<tr>" .
"\n\t<th>Admission No.</th>" .
"\n\t<th>Last Name</th>" .
"\n\t<th>First Name</th>" .
"\n\t<th>Gender</th>" .
"\n\t<th>Orphan</th>" .
"\n\t<th>District</th>\n</tr>";
// Fetch each of the query rows
while ($row = # mysql_fetch_array($result))
{
// Print one row of results
echo "\n<tr>" .
"\n\t<td>" . $row["Admission"] . "</td>" .
"\n\t<td>" . $row["last_name"] . "</td>" .
"\n\t<td>" . $row["first_name"] . "</td>" .
"\n\t<td>" . $row["Gender"] . "</td>" .
"\n\t<td>" . $row["Orphan"] . "</td>" .
"\n\t<td>" . $row["District"] . "</td>" .
"\n</tr>";
} // end while loop body
// Finish the <table>
echo "\n</table>";
} // end if $rowsFound body
// Report how many rows were found
echo "$rowsFound records found matching your
criteria<br>";
} // end of function
$scriptName = "combined.php";
// Has the user provided the parameter?
if (empty($Year))
{
// No, the user hasn't provided a parameter
?>
<form action="<?=$scriptName;?>" method="GET">
<br>Enter Year Of Admission :
<input type="text" name="Year" value="All">
(type All For All Years)
<br>
<input type="submit" value="Show Data">
</form><br>
Home
<?php
} // end of if empty($Year) body
else
{
// Secure the user parameter $Year
$Year = clean($Year, 30);
// Connect to the MySQL DBMS
if (!($connection = # mysql_connect($hostName,
$username,
$password)))
die("Could not connect");
if (!mysql_select_db($databaseName, $connection))
showerror( );
// Start a query ...
$query = "SELECT Admission,
last_name,
first_name,
Gender,
Orphan,
District
FROM osasaasasaalumni_index;"
// ... then, if the user has specified a year,
// add the Year as an AND clause ...
if ($Year != "All")
$query .= " AND year = \"$Year\"";
// ... and then complete the query.
$query .= " ORDER BY last_name";
// run the query and show the results
displayStudentsList($connection, $query, $Year);
// Close the DBMS connection
mysql_close($connection);
} // end of else if empty($Year) body
?>
</body>
</html>
My db.inc is
<?
$hostName = "xxxxxx";
$databaseName = "xxxxx";
$username = "xxxxx";
$password = "xxxxx";
?>
Whats wrong with the code because when I call it, it displays a blank page?
You are missing ; at the end of this statement:
Original:
$query = "SELECT Admission,
last_name,
first_name,
Gender,
Orphan,
District
FROM osasaasasaalumni_index;"
Updated:
$query = "SELECT Admission,
last_name,
first_name,
Gender,
Orphan,
District
FROM osasaasasaalumni_index;";
If you see a blank page and no errors, then you should turn on error reporting. It can be done for example by putting this code in the beginning of your script, right after <?php:
error_reporting(E_ALL);
ini_set('display_errors', '1');
Related
I'm new to PHP/SQL, and I'm attempting to create a form that would insert the given data into a formatted table. After fiddling with it for a bit, I have managed to get the primary functions working, however, it seems my script is inserting data one column over, and I can't for the life of me understand why. Here is the script I've made:
#!/usr/local/bin/php -d display_errors=STDOUT
<?php
// begin this XHTML page
print('<?xml version="1.0" encoding="utf-8"?>');
print("\n");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8" />
<title>Accessing a SQLite 3 Database using PHP</title>
</head>
<body>
<p>
<?php
$database = "students.db";
try
{
$db = new SQLite3($database);
}
catch (Exception $exception)
{
echo '<p>There was an error connecting to the database!</p>';
if ($db)
{
echo $exception->getMessage();
}
}
// define tablename + fieldnames
$table = "bruins";
$field1 = "name";
$field2 = "sid";
$field3 = "gpa";
// Create the table
$sql= "CREATE TABLE IF NOT EXISTS $table (
$field1 varchar(100),
$field2 int(9),
$field3 decimal(3,1)
)";
$result = $db->query($sql);
print "<h3>Creating the table</h3>";
print "<p>$sql</p>";
// Extract SID and GPA from the $_GET data.
$name = $_GET['name'];
$SID = $_GET['SID'];
$GPA = $_GET['GPA'];
// Insert a new record to DB with name = $name, sid = $SID and gpa = $GPA
$sql = "INSERT INTO $table ($field1, $field2, $field3)
VALUES ('$name', '$SID', '$GPA')";
print "Inserting a new record to the bruins table the command I am using is:</br>";
print "$sql";
$result = $db->query($sql);
// print an XHTML table to display the current table
$sql = "SELECT * FROM $table";
$result = $db->query($sql);
print "<table border='border'>\n";
print " <tr>\n";
print " <th>" . $field1 . "</th>\n";
print " <th>" . $field2 . "</th>\n";
print " <th>" . $field3 . "</th>\n";
print " </tr>\n";
// obtain the results from the SELECT query as an array holding a record
while($record = $result->fetchArray())
{
print " <tr>\n";
print " <td>" . $record[$field1] . "<td>\n";
print " <td>" . $record[$field2] . "<td>\n";
print " <td>" . $record[$field3] . "<td>\n";
print " </tr>\n";
}
print "</table>\n";
?>
</body>
</html>
Upon submitting the data, the table is created, but all SID strings are in the GPA column, and the GPA strings are placed into their own blank column. Any advice/insight would be great :-)
I'm just posting the answer here again just in case somebody doesn't see it in the comments.
Closing the s properly at the end of the code resolved the problem :)
I am trying to write a php code that changes the availability of a certain apartment. Here is my code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
$servername = "localhost";
$username = "bla";
$password = "blabla";
$dbname = "testDB";
// Create connection
$connect = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}else{
echo "Connected successfully to the database: " . $dbname . "<br><br>";
}
$query = "SELECT * FROM test";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_array($result);
echo "id: " . $row["id"] . " // Address: " . $row["address"] . " // Rooms: " . $row["rooms"] . " // Availability: " . $row["availability"] . ".<br>";
?>
<form method ="post" action ="<?php $_PHP_SELF ?>">
<input name="update" type="submit" value="Change Availability">
</form>
<?php
if(isset($_POST["update"])) {
$avail = mysqli_query($connect,"SELECT availability FROM test WHERE id='1'");
$availCheck = mysqli_fetch_array($avail);
settype($availCheck, "int");
if($availCheck == 1){
$upAvail = mysqli_query($connect,"UPDATE test SET availability='0' WHERE id='1'");
}else{
$upAvail = mysqli_query($connect,"UPDATE test SET availability='1' WHERE id='1'");
}
}
?>
</body>
</html>
And this is the output I get:
Connected successfully to the database: testDB
id: 1 // Address: 3787 cote des neiges // Rooms: 2 // Availability: 1.
Change Availability
So here is my issue. When the availability is 1 and I press the button it changes to 0. But after that, when I press the button again, it doesn't change back to 1.
Why is that?
Thank you for the help.
You're not toggling the availability. The mysqli_fetch_array fetches the row from the test table matching the id (id=1). As a result, $availCheck will always equal 1 after you cast the non-empty array to an integer.
You can replace all that logic with a single MySQL query to toggle the value.
UPDATE test SET availability = IF(availability = 1, 0, 1) WHERE id=1
I think what you wanted to do:
$availCheck = mysqli_fetch_array($avail)['availability'];
I'm starting to build a very simple product display system, mainly to build my own skills, but also for use on my website for work.
List.php
<html>
<head>
<title>Retrieve data from the database</title>
<?php
$username='';
$password='';
$database='';
?>
</head>
<body>
<ul>
<?php
// Connect to database server
mysql_connect(localhost,$username,$password);
// Select database
#mysql_select_db($database) or die( 'Unable to select database');
// SQL query
$sql = "SELECT * FROM products WHERE category = 30";
// Execute the query (the recordset $rs contains the result)
$result = mysql_query($sql);
// Loop the recordset $rs
while($row = mysql_fetch_array($result)) {
// Name of the person
$strName = $row['make'];
// Create a link to person.php with the id-value in the URL
$strLink = "<a href = 'product.php?id = " . $row['ID'] . "'>" . $strName . "</a>";
// List link
echo "<li>" . $strLink . "</li>";
}
// Close the database connection
mysql_close();
?>
</ul>
</body>
</html>
Product.php
<html>
<head>
<title>Retrieve data from database</title>
</head>
<body>
<?php
$username="";
$password="";
$database="";
// Connect to database server
mysql_connect(localhost,$username,$password);
// Select database
#mysql_select_db($database) or die( "Unable to select database");
// Get data from the database depending on the value of the id in the URL
$sql = mysql_query('SELECT * FROM products WHERE ID=' . $_GET["ID"]);
$result = mysql_query($sql);
if(!$result)
die(mysql_error());
// Loop the recordset
while($row = mysql_fetch_array($result)) {
// Write the data of the product
echo $row['category'];
echo "<p>";
echo $row["make"];
echo "<p>";
echo $row["description"];
echo "<p>";
echo $row["picture"];
}
// Close the database connection
mysql_close();
?>
<p>Return to the list</p>
</body>
</html>
Can be seen messing up HERE
If someone can help get this working for me I'd be very grateful!
Try this way, but not fully sure about this stubborn issue. You can try by changing the case of all keys of the $_GET array to lowercase using the array_change_key_case()
$get = array_change_key_case($_GET);
$id = $get['id'];
$sql = mysql_query('SELECT * FROM products WHERE ID=' . $id);
NB: Make first sure SELECT * FROM products WHERE ID=your_row_id return results or not?
I turned out that the link that the page 'list.php' was generating was incorrectly formatted.
Changed this:
$strLink = "<a href = 'product.php?id = " . $row['ID'] . "'>" . $strName . "</a>";
To
$strLink = "<a href = 'product.php?id=".$row['ID']."'>" . $strName . "</a>";
And it's now working exactly as it should!
I am not sure why this hasn't been answered yet will not that I know of, I am wondering if it's possible to add a insert query with in a while loop I have tried,
but it keeps inserting the comment more then it should (say if it finds 4 status updates it will post the comment in the database 4 times)
I know I have the insert query twice this is not the problem as I had the query where it submits a comment to the database the current query is there for testing purposes.
<?php
require_once ("core/connection.php");
require_once ("core/group_functions.php");
//We need to post the message update in to the database
if(isset($mybb->input['post_message_submit'])) {
$post_message_submit = $mybb->input['post_message_submit'];
$post_message = $mybb->input['post_message'];
$comment_post = $mybb->input['comment_post'];
if(($post_message_submit) && ($post_message)) {
$insert_query = $db->query("INSERT INTO " . TABLE_PREFIX . "groups_posts" . "(posted_by, group_name, post_body)
VALUES ('$mybb_username', '$get_group_url' ,'$post_message')");
} else {
echo "<text style='color:red;'> You Must Specify A Message</a></text>";
}
}
echo "
<form action='' method='POST'>
<textarea name='post_message' id='post_message' placeholder='Whats Going On?'></textarea><br>
<input type='submit' name='post_message_submit' value='Post'>
</form>
";
$fetch_index_query = $db->query("SELECT post_id,posted_by,post_body,post_active,group_name FROM " . TABLE_PREFIX . "groups_posts WHERE group_name='$get_group_url'");
while($fetch_index_groups_array = $db->fetch_array($fetch_index_query)) {
$post_id_row = $fetch_index_groups_array['post_id'];
$posted_by = $fetch_index_groups_array['posted_by'];
$g_name = $_fetch_index_groups_array['g_name'];
$g_body = $fetch_index_groups_array['post_body'];
echo"<br>" . "<a href=''> $posted_by </a>" . "<br>" . $gname
. "<br>____________";
$fetch_comments_query = $db->query("SELECT g_name,post_body,comment_by FROM spud_groups_comments WHERE post_id='$post_id_row'");
while($fetch_groups_comments = $db->fetch_array($fetch_comments_query)) {
$post_body = $fetch_groups_comments['post_body'];
echo ("<br>" . $post_body);
}
$insert_query2 = $db->query("INSERT INTO " . TABLE_PREFIX . "groups_comments" . "(comment_by, post_id, post_body)
VALUES ('$mybb_username', '$post_id_row' ,'$comment_post')");
echo "<br>
<form action='' method='POST'>
<input type='text' name='comment_post' placeholder='Comment then Hit Enter'>
</form>
";
}
//We have done everything we need to do we can now exit and not execute anything beyond this point
exit();
?>
Try to instantiate other $DB object for the insert query. i.e. do not use the same one you are using to fetch the array, as the next use will overwrite the result of the first query that you are looping through.
i will use my old posted codes, coz i am working on the same program. what i want is how could i make it possible to save all selected values in one row which the studentid of a user will not be repeated. pls help...
<?php session_start(); ?>
<?php
//server info
$server = 'localhost';
$user = 'root';
$pass = 'root';
$db = 'user';
// connect to the database
$mysqli = new mysqli($server, $user, $pass, $db);
// show errors (remove this line if on a live site)
mysqli_report(MYSQLI_REPORT_ERROR);
?>
<?php
$_SESSION['username'];
$voter = $_SESSION['username'];
echo 'Student ID: '. $voter.'';
echo "<br />";
if ($_POST['representatives']){
$check = $_POST['representatives'];
foreach ($check as $ch){
global $voter;
$mysqli->query("INSERT INTO sample (studentid, candidate1) VALUES ('".$voter."', '". $ch ."')");
echo $ch. "<br>";
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<html>
<head>
<script type="text/javascript">
<!--
function get_representatives_value()
{
for (var i=0; i < document.list.representatives.length; i++)
{
if (document.list.representatives[i].checked)
{
return document.getElementById('candidates').innerHTML = document.list.representatives[i].value
}
}
}
//-->
</script>
title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link href="candidate.css" rel="stylesheet" type="text/css">
</head>
<body> <p id="txt"></p>
<form name="list" action="president2.php" method="post" onSubmit="return get_representatives_value()">
<div id="form">
<?php
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM candidate_info WHERE position= 'representatives' AND department ='CCEITE' ORDER BY cand_id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// display records in a table
echo "<table border='1' cellpadding='10'>";
// set table headers
echo "<tr><th>Student ID</th><th>Candidate ID</td><th>Course</th><th colspan = '3'>Name</th></tr>";
while ($row = $result->fetch_object())
{
// set up a row for each record
echo "<tr>";
echo "<td>" . $row->cand_studid . "</td>";
echo "<td>".$row->cand_id."</td>";
echo "<td>" . $row->course . "</td>";
echo "<td coslpan ='5'>" . $row->fname . " ". $row->mname ." ". $row->lname ." </td>";
echo "<td><input type ='checkbox' name='representatives[]' id='". $row->cand_studid ."' value='" . $row->cand_studid . "' onchange='get_representatives_value()' /></td>";
echo "</tr>";
}
echo "</table>";
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
echo "<input type='submit' name='representatives value='Submit' />";
?>
</div>
</form>
<table>
<tr><td>Preview List</td></tr>
<tr><td>Candidates: </td><td id="candidates"> </td></tr>
</table>
</body>
</html>
this the preview of my output and selected checkbox
now this is the preview of my database. this one is the result of my selection from the above preview which the student ID is repeated on my table.
what i want is to save like this
and one more thing, how could i make a preview of all i selected on the checkboxes, here is my preview output, below the table is the preview list of candidates as the user click on the checkbox. but it returns only one and only the last selected value as selecting multiple checkboxes will be printed. how could i apply this method in an array coz this preview, i remove the '[]' on my input type name='representative' and it works, but not in the presence of '[]'.
I don't know if I read your questions correctly, but...
For your Insert Issue
I don't know if the way you're storing the data in the database is the best method, but if you want to use what you have, you can just insert your record like this (assuming you've put in some validation script to prevent users from selecting more than 2 candidates):
<?php
$_SESSION['username'];
$voter = $_SESSION['username'];
if ($_POST['representatives']){
$check = $_POST['representatives'];
$mysqli->query("INSERT INTO sample (studentid, candidate1, candidate2) VALUES ('". $voter ."', '". $check[0] ."', '". $check[1] ."')");
}
}
?>
For your Preivew Issue:
I'm assuming you wanted something like this for your preview to show the studentid with the choices for candidate1 and candidate2:
<h3>Preview List</h3>
<table>
<tr><th>StudentID</th><th>Candidate 1</th><th>Candidate 2</th></tr>
<?php
$result = $mysqli->query("SELECT * FROM candidate_info");
while ($row = $result->fetch_object())
{
echo "<tr><td>" . $row->studentid . "</td><td>" . $row->candidate1 . "</td><td>" . $row->candidate2 . "</td></tr>";
}
$mysqli->close();
?>
</table>
Here is some pseudo code you can use to update the sample table:
$candidate=array(null,null);
$candidateCounter=0;
foreach ($check as $ch){
$candidate[$candidateCounter]=$ch;
$candidateCounter++;
if(candidateCounter>1){
something wrong, only 2 candidates can be selected
}
}
UPDATE sample set $candidate1=candidate[0], $candidate2=candidate[1] WHERE
studentid=$voter