I want to get some data from my oracle database into php through a html form where I search by a string which exists into a column. I have the following php code and the search form retuns nothing:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<?php
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("/^[A-Z0-9]+/", $_POST['name'])){
$name=$_POST['name'];
// Connects to the XE service (i.e. database) on the "localhost" machine
$conn = oci_connect('user', 'pwd', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT deejays.name,available_dates.data,available_dates.venue,available_dates.location FROM deejays,available_dates WHERE deejays.name LIKE '%W&W%' and pk_id=fk_id');
oci_execute($stid);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
}
else{
echo "<p>Please enter a search query</p>";
}
}
}
?>
<body>
</body>
</html>
The result I want is for i.e the following:
You need to modify your query to include bindable parameters. Here is part of example 4 from the documentation for the oci_bind_name function, which you simply need to adapt to suit your application:
$sql = 'SELECT last_name FROM employees WHERE department_id = :didbv ORDER BY last_name';
$stid = oci_parse($conn, $sql);
$didbv = 60;
oci_bind_by_name($stid, ':didbv', $didbv);
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_ASSOC)) != false) {
echo $row['LAST_NAME'] ."<br>\n";
}
The documentation includes a very good description of what binding is, how to do it, and why it's important for application performance and security.
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 :)
Please refer to the following code:
<?php
//error_reporting(E_ALL);
//ini_set('display_errors', '1');
// 1. Create a database connection
$dbhost = "localhost";
$dbuser = "name";
$dbpass = "password";
$dbname = "widget_corp";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
?>
<?php
// 2. Perform database query
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
// Test if there was a query error
if (!$result) {
die("Database query failed.");
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<title>Databases</title>
</head>
<body>
<?php
while($row = mysqli_fetch_row($result))
{
echo "<pre>";
print_r($row);
echo "</pre>";
echo "<hr />";
}
?>
<?php
while($row = mysqli_fetch_assoc($result))
{
echo "<pre>";
print_r($row);
echo "</pre>";
echo "<hr />";
}
?>
<?php
// 4. Release returned data
mysqli_free_result($result);
?>
</body>
</html>
<?php
// 5. Close database connection
mysqli_close($connection);
?>
I want the returned data to be printed twice in different formats.
However, when I run the program, only mysqli_fetch_row is printed (mysqli_fetch_assoc is not printed).
Can you please clarify why?
Your first loop steps through to the end of the result set, so there is nothing more to fetch. You need to reset the pointer (the cursor's position in the result set) between loops using mysqli_data_seek().
Example:
while($row = mysqli_fetch_row($result))
{
echo "<pre>";
print_r($row);
echo "</pre>";
echo "<hr />";
}
mysqli_data_seek($result, 0); // this resets the cursor to the first row
while($row = mysqli_fetch_assoc($result))
{
echo "<pre>";
print_r($row);
echo "</pre>";
echo "<hr />";
}
Also, please note that you do not need so many <?php ... ?> blocks -- you can combine adjacent blocks of code. Just delete any of these combos:
?>
<?php
I am trying to write a page in php with the goal of counting the specified data from the database and showing that data. It seems like a simple enough task, but I cannot get this to work correctly and I'm at the limits of my very limited PHP/SQL knowledge. This is my code for the whole page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Counter Test</title>
</head>
<body>
<div id="counter">
<?php
$advance = "(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = xxx.xx.xx.xxx)(PORT = 1521)))
(CONNECT_DATA =
(SERVICE_NAME = domain.domain)))";
$conn = oci_connect('xxx', 'xxx', xxx);
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT count(distinct(b.id_number)) as total FROM bio b WHERE (b.alum_memb_type) is not null AND b.record_status_code NOT IN ('D', 'X', 'R')' );
oci_execute($stid);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
?>
</div>
</body>
</html>
You can expect one result back, so don't have to fetch in a loop.
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
$count = $row['total'];
i have a problem about getting data from oracle database. How to get data in utf-8? browser shows symbols with echo, but data from oracle has ? marks instead of letters
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"></meta>
</head>
<?php
$tns2 = "(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = hostname)(PORT = 1521)) (CONNECT_DATA = (SID = sidname)))";
if ($conn = oci_connect("user","pass", $tns2))
{
echo "YAY!";
//oci_close($conn);
}
else
{
die("Nesiseka");
}
$stid = oci_parse($conn, 'SELECT * rowname where rownum<=10');
oci_execute($stid);
oci_close($conn);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
echo"įęėšųį";
?>
Simple solution. Only add 'AL32UTF8' to line if ($conn = oci_connect(username,pass, $tns2 , 'AL32UTF8')) Everything works now.
Thank you for help
Use this to make database connection:
$conn = oci_connect(username,pass, $tns2 , 'AL32UTF8')
set php encoding to utf 8
mb_internal_encoding("UTF-8");
link for more
http://php.net/manual/en/function.mb-internal-encoding.php
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