Delete multiple rows from mysql with checkbox - php

I've got a query that displays a table with information about a message, I also have a column that gives the option to select the messages that the user wants to delete with a checkbox, once they have ticked the messages they want to delete, they then click on a submit button which takes them to the process page where the SQL statement to delete each selected message is made; however, the statement doesn't seem to work, this is what I have so far:
THE MESSAGE DISPLAY PAGE:
if ($_SESSION['user_session'] == "$current_user")
{
{
echo "<table border='1'>
<tr>
<th>Message ID</th>
<th>Username</th>
<th>Subject</th>
<th>Message</th>
<th>Delete?</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['message_id'] . "</td>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['sub'] . "</td>";
echo "<td>" . $row['message'] . "</td>";
echo "<td><input type='checkbox' name='check_list[]' value='" . $row['message_id'] . "' /></td>";
echo "</tr>";
}
echo "</table>";
}
}
THE PROCESS PAGE WITH SQL STATEMENT:
if(!empty($_POST['check_list']))
{
foreach($_POST['check_list'] as $check)
{
//connection to the database
$dbhandle = mysql_connect("XXX", "XXX", "XXX")
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("XXX",$dbhandle)
or die("Could not select examples");
//execute the SQL query to update the "returned" field to 1 wherever the loan_id is checked.
$result = mysql_query("DELETE FROM message WHERE message_id='$check'");
}
if ($result)
{
echo 'Messages Deleted';
}
}

if(!empty($_POST['check_list']))
{
$dbhandle = mysql_connect("XXX", "XXX", "XXX") or die("Unable to connect to MySQL");
$selected = mysql_select_db("XXX",$dbhandle) or die("Could not select examples");
$result = mysql_query("DELETE FROM message WHERE message_id IN (" . implode(',', $_POST['check_list']) . ")", $dbhandle);
if ($result !== false)
echo 'Messages deleted.';
}
You obviously should implement some more testing of the contents of $_POST['check_list'] before executing the query. We don't want evil people to do silly stuff.

As far as I can see there's nothing wrong with your code, you should really try a var_dump($check) before the SQL query to output what it contains, and a var_dump($_POST['check_list']) at the very beggining of the second page.
Also, I suggest you to take out the database connection of the foreach as you are doing multiple innecesary connections, like this:
if(!empty($_POST['check_list'])) {
// Output the variable $_POST['check_list']
var_dump($_POST['check_list']);
//connection to the database
$dbhandle = mysql_connect("XXX", "XXX", "XXX") or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("XXX",$dbhandle) or die("Could not select examples");
foreach($_POST['check_list'] as $check) {
// Output the $check variable to see what it contains
var_dump($check);
//execute the SQL query to update the "returned" field to 1 wherever the loan_id is checked.
$result = mysql_query("DELETE FROM message WHERE message_id='$check'");
// For each $check, verify what message_id got deleted
if ($result) {
echo 'Message ID Deleted: ' . $check;
}
}
}

Related

Run a MySQL query trough pressing a link and escaping backslash

I have this PHP code below that prints the result of a MySQL query in a HTML table. Furthermore, in the table, I create a link of the result that will be used in another query. Lets take a look at the code:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "root", "DB1");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
$sql = "SELECT * FROM fileDB";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>filename</th>";
echo "<th>filepath</th>";
echo "<th>size</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td><a href='http://mysecreturl.com/test.php?path=" . $row['filepath'] . "'>" . $row['filename'] . "<a/></td>";
echo "<td>" . $row['filepath'] . "</td>";
echo "<td>" . $row['size'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
This code works as intended, but now comes the problem: I want to implement the following: Once you click on the link, another query should be executed, this one to be specific: SELECT * FROM fileDB WHERE filepath = 'the one sent from the link'. I thought to use something like $_GET["filepath"] from the link to set the filepath in the second query. I have two main problems with this:
I don't know any PHP so I have no idea how clicking a link could run another query and generate a new table with results.
This is important to point out, filepath is a string of a Windows path, therefore it contains backslashes like this: C:\something\something etc. When I query this manually in phpMyAdmin I escape the backslashes by writing C:\\something\\something but when getting my result in the table from the code above, the string filepath will have one pair of backslash of course (as it is saved in the database). How could I then perform my second query if the backslashes apparently need to be escaped?
Any help is very appreciated!
I thought you want to download a file. well this is much simpler:
if (isset($_GET["path"])) {
$stmt = mysqli_prepare($link, "SELECT * FROM fileDB WHERE filepath = ?");
mysqli_stmt_bind_param($stmt, "s", $_GET["path"]);
}else{
$stmt = mysqli_prepare($link, "SELECT * FROM fileDB");
}
mysqli_stmt_execute($stmt);
if ($result = mysqli_stmt_get_result($stmt)) {
if(mysqli_num_rows($result) > 0){
...
oh and one more thing you should escape query component in your URL
echo "<td><a href='http://mysecreturl.com/test.php?path=" . urlencode($row['filepath']) . "'>" . $row['filename'] . "<a/></td>";
Now this could be done using get method like <a href="yourpage.php?path='your_filepath'"> then in your php use this <?php if(isset($_GET['filepath'])){//Run your php query here}?>
You can do something like this:
echo '<tr>
<td><form method="get" action="test.php">
<button type="submit" name="path" value="'.$row['filepath'].'">
'.$row['filename'].'</button>
</form></td>
<td>'.$row['filepath'].'</td>
<td>'.$row['size'].'</td>
</tr>';
Untested, but should in theory work. Why you have the link in the filename-table-cell, instead of in the table-cell with the actual path in it, god knows, but you can test it and see if it works.
I would, however, just make this into a $_POST, unless it's important to show the URI in the address bar.
To answer the first question, you can add variables to a link, e.g. if you want to pass a first name and last name in a link you would do this
<?php
$fname = "John"; // First name
$lname = "Doe"; // Last Name
echo "<a href='next_table.php?fname=$fname&lname=$lname'>Next Table</a>";
?>
Then to retrieve the first name and last name on another page you would use this:
<?php
$fname = $_GET["fname"];
$lname = $_GET["lname"];
?>
Let me know if this helps.
Just an if statement to check whether the filepath is set or not and str_replace function to escape backlashes.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "root", "DB1");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
// Check If filpath is set or not
if(!isset($_GET['filepath']))
{
$sql = "SELECT * FROM fileDB";
}
else
{
$filepath=$_GET['filepath'];
//replace backlashes with double backlashes using str_replace
$filepath=str_replace('\\','\\\/',$filepath);
$sql = "SELECT * FROM fileDB WHERE filepath='$filepath'";
}
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>filename</th>";
echo "<th>filepath</th>";
echo "<th>size</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td><a href='http://mysecreturl.com/test.php?path=" . $row['filepath'] . "'>" . $row['filename'] . "<a/></td>";
echo "<td>" . $row['filepath'] . "</td>";
echo "<td>" . $row['size'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
Change the code:
// Attempt select query execution
$sql = "SELECT * FROM fileDB";
if($result = mysqli_query($link, $sql)){
To:
// Attempt select query execution
if(isset($_REQUEST['file']) && $_REQUEST['file'] !='') {
$sql = "SELECT * FROM fileDB WHERE `file` = '".$_REQUEST['file']."';";
} else {
$sql = "SELECT * FROM fileDB";
}
if($result = mysqli_query($link, $sql)){
This should convey the basic idea, but take to heart about using parameterized queries.

Two many records showing when h_id is identified

I am trying to filter a mysql table using PHP, My aim is when the url is History.php?h_id=1 it only shows the rows that have one in the h_id (H_id is not a unique number)
My code is as below.
<html>
<head>
<title></title>
</head>
<body >
<?php
mysql_connect('localhost', 'root', 'matl0ck') or die(mysql_error());
mysql_select_db("kedb") or die(mysql_error());
$h_id = (int)$_GET['h_id'];
$query = mysql_query("SELECT * FROM Hist WHERE H_ID = '$h_id'") or die(mysql_error());
if(mysql_num_rows($query)=1){
while($row = mysql_fetch_array($query)) {
$id = $row['ID'];
$name = $row['Name'];
$datemod = $row['DateMod'];
$h_id = $row['H_ID'];
}
?>
<?php
$con=mysqli_connect("localhost","root","matl0ck","kedb");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Hist");
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Date</th>
<th>H_ID</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['DateMod'] . "</td>";
echo "<td>" . $row['H_ID'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<?php
}else{
echo 'No entry found. Go back';
}
?>
</body>
</html>
When I try to use this it shows all records that has a number in the h_id when I delete a number in this column it shows an error.
My table layout is as below.
Thank you
This is your syntactically incorrect statement
if(mysql_num_rows($query)=1){
A test is done using == and = is a value assignment
if(mysql_num_rows($query) == 1){
//------------------------^^
while($row = mysql_fetch_array($query)) {
$id = $row['ID'];
$name = $row['Name'];
$datemod = $row['DateMod'];
$h_id = $row['H_ID'];
}
Also
Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared parameterized statements and therefore stick to the mysqli_ or PDO database extensions
Your general code seemed to get a bit confused, and you were getting data from a query "SELECT * FROM Hist" that you never seemed to use.
Also the while loop was being terminated before you actually consumed and output the results of the first query.
I also amended the code to use parameterized and prepared queries, and removed the use of the mysql_ which no longer exists in PHP7
<?php
// Use one connection for all script, and make it MYSQLI or PDO
$con=mysqli_connect("localhost","root","matl0ck","kedb");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
// if connection fails there is no point doing anything else
exit;
}
//$h_id = (int)$_GET['h_id'];
// prepare and bind values to make the code safe from SQL Injection
// also only select the rows you want
$sql = "SELECT ID, Name, DateMod, H_ID FROM Hist WHERE H_ID = ?";
$stmt = $con->prepare($sql);
if ( ! $stmt ) {
echo $con->error;
exit;
}
$stmt->bind_param("i", $_GET['h_id']);
$stmt->execute();
if ( ! $stmt ) {
echo $con->error;
exit;
}
// bind the query results 4 columns to local variable
$stmt->bind_result($ID, $Name, $DateMod, $H_ID);
echo "<table border='1'>
<tr><th>ID</th><th>Name</th><th>Date</th><th>H_ID</th></tr>";
if($con->affected_rows > 0){
echo "<table border='1'>
<tr><th>ID</th><th>Name</th><th>Date</th><th>H_ID</th></tr>";
while($stmt->fetch()) {
while($row = $stmt->fetch_array()) {
echo "<tr>";
echo "<td>$ID</td>";
echo "<td>$Name</td>";
echo "<td>$DateMod</td>";
echo "<td>$H_ID</td>";
echo "</tr>";
}
echo "</table>";
}else{
echo 'No entry found. Go back';
}
?>

How to add a button to my PHP form that deletes rows from my MYSQL database [duplicate]

This question already has answers here:
How to add a delete button to a PHP form that will delete a row from a MySQL table
(5 answers)
Closed 1 year ago.
I am new to php coding.
I am adding each row delete button, but it should not working.
This is my html code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$connection = mysql_connect('localhost', 'root','');
if (!$connection)
{
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db( "emp",$connection);
if (!$select_db)
{
die("Database Selection Failed" . mysql_error());
}
$sql = "SELECT * FROM venu ";
$result = mysql_query($sql) or die(mysql_error());
?>
<table border="2" style= " margin: 0 auto;" id="myTable">
<thead>
<tr>
<th>name</th>
<th>id</th>
<th>rollnumber</th>
<th>address</th>
<th>phonenumber</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['rollnumber'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['phonenumber'] . "</td>";
echo "<td><form action='delete.php' method='POST'><input type='hidden' value='".$row["address"]."'/><input type='submit' name='submit-btn' value='delete' /></form></td></tr>";
echo "</tr>";
}
?>
</tbody>
</table>
</body>
</html>
This is my delete code:
<?php
$connection = mysql_connect('localhost', 'root','');
if (!$connection)
{
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db( "emp",$connection);
if (!$select_db)
{
die("Database Selection Failed" . mysql_error());
}
error_reporting(0);
session_start();
$name = $_POST['name'];
$id = $_POST['id'];
$rollnumber = $_POST['rollnumber'];
$address = $_POST['address'];
$phonenumber = $_POST['phonenumber'];
if($name!='' and $id!='')
{
$sql = mysql_query("DELETE FROM 'venu' WHERE name='balaji'AND id='93'AND rollnumber='93'AND address='bangalore'AND phonenumber='1234567890'");
echo "<br/><br/><span>deleted successfully...!!</span>";
}
else{
echo "<p>ERROR</p>";
}
mysql_close($connection);
?>
I am trying to delete each row using a button, but it is not working.
In your html view page some change echo "<td><a href='delete.php?did=".$row['id']."'>Delete</a></td>"; like bellow:
<?php
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['rollnumber'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['phonenumber'] . "</td>";
echo "<td><a href='delete.php?did=".$row['id']."'>Delete</a></td>";
echo "</tr>";
}
?>
PHP delete code :
<?php
if(isset($_GET['did'])) {
$delete_id = mysql_real_escape_string($_GET['did']);
$sql = mysql_query("DELETE FROM venu WHERE id = '".$delete_id."'");
if($sql) {
echo "<br/><br/><span>deleted successfully...!!</span>";
} else {
echo "ERROR";
}
}
?>
Note : Please avoid mysql_* because mysql_* has beed removed from
PHP 7. Please use mysqli or PDO.
More details about of PDO connection http://php.net/manual/en/pdo.connections.php
And more details about of mysqli http://php.net/manual/en/mysqli.query.php
First you need to change your button like
echo "<td>Delete</td>";
this will send the ID of the row which you want to delete to the delete.php
Secondly you need to change a bit your delete.php currently is wide open for SQL injections. Try using MySQLi or PDO instead
if(isset($_GET['id'])) {
$id = $_GET['id'];
$stmt = $mysqli->prepare("DELETE FROM venu WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->close();
}
Of course if you need to add more parameters in delete query you should pass them also with the button..
EDIT: Simple example for update record
You can put second button on the table like
echo "<td>Update</td>";
Then when you click on it you will have the ID of the record which you want to update. Then in update.php
if(isset($_GET['id'])) {
$id = $_GET['id'];
$stmt = $mysqli->prepare("UPDATE venu SET name = ?, rollnumber = ?, address = ? WHERE id = ?");
$stmt->bind_param('sisi', $name, $rollnumber, $address, $id);
$stmt->execute();
$stmt->close();
}
Here ( in update.php ) you can have form which you can fill with new data and pass to variables $name, $rollnumber, $address then post it to update part.
Something to start with: PHP MySqli Basic usage (select, insert & update)
change up your query to use the dynamic value entered by the user, right now it is hard coded in there.
session_start();
require_once 'conn.php';
class myClass extends dbconn {
public function myClassFunction(){
try {
$id = $_GET['id'];
if(isset($_GET['id'])) {
$sql = "DELETE FROM tablename WHERE id = ?";
$stmt = $this->connect()->query($sql);
$stmt->bind_param('i', $id);
header("location: ../filepath/index.php");
}
} catch (PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
}
}
This line is wrong, you need to set the WHERE clause to the data you get from the hidden input value
$sql = mysql_query("DELETE FROM 'venu' WHERE name='balaji'AND id='93'AND rollnumber='93'AND address='bangalore'AND phonenumber='1234567890'");
Should be:
$sql = mysql_query("DELETE FROM 'venu' WHERE address='"._POST['address']."'");
And in the little form you are using, change:
<input type='hidden' value='".$row["address"]."'/>
to:
<input type='hidden' name='address' value='".$row["address"]."'/>

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>";
}
?>

SQL server php login script

I have created the script to validate my login system but i am having trouble figuring out how to make it specifically log in to my sqlserver account to my specific work space my log in script so far goes as the following
<?php
session_start();
if(!isset($_SESSION["user_id"])){
header("location:../../login.html");
}
$username = $_POST['txt_username'];
$user_id = $_POST['txt_password'];
mysql_connect($server, $username, $password) or die("No Server Found");
mysql_select_db($schema) or die("No Connection");
?>
Read: http://php.net/manual/en/function.mssql-connect.php
Below is the code for connecting to a MSSQL Server database
//connection to the database
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
//select a database to work with
$selected = mssql_select_db($myDB, $dbhandle)
or die("Couldn't open database $myDB");
//declare the SQL statement that will query the database
$query = "SELECT id, name, year ";
$query .= "FROM cars ";
$query .= "WHERE name='BMW'";
//execute the SQL query and return records
$result = mssql_query($query);
$numRows = mssql_num_rows($result);
echo "<h1>" . $numRows . " Row" . ($numRows == 1 ? "" : "s") . " Returned </h1>";
//display the results
while($row = mssql_fetch_array($result))
{
echo "<li>" . $row["id"] . $row["name"] . $row["year"] . "</li>";
}
//close the connection
mssql_close($dbhandle);
?>
Connect with a DSN
ODBC Functions
DSN stands for 'Data Source Name'. It is an easy way to assign useful and easily rememberable names to data sources which may not be limited to databases alone.
In the example below we will show you how to connect with a DSN to a MSSQL Server database called 'examples' and retrieve all the records from the table 'cars'.
<?php
//connect to a DSN "myDSN"
$conn = odbc_connect('myDSN','','');
if ($conn)
{
//the SQL statement that will query the database
$query = "select * from cars";
//perform the query
$result=odbc_exec($conn, $query);
echo "<table border=\"1\"><tr>";
//print field name
$colName = odbc_num_fields($result);
for ($j=1; $j<= $colName; $j++)
{
echo "<th>";
echo odbc_field_name ($result, $j );
echo "</th>";
}
//fetch tha data from the database
while(odbc_fetch_row($result))
{
echo "<tr>";
for($i=1;$i<=odbc_num_fields($result);$i++)
{
echo "<td>";
echo odbc_result($result,$i);
echo "</td>";
}
echo "</tr>";
}
echo "</td> </tr>";
echo "</table >";
//close the connection
odbc_close ($conn);
}
else echo "odbc not connected";
?>

Categories