export mysql query to csv on button click - php

so i have a php code that shows a table from the mysql database
there is also a filter field which filters the table.
i need help exporting the results of the table to a csv file when the button "export data" is clicked.
how do i do that?
below is the code
<?php
error_reporting(0);
include("config.php");
?>
<!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>TAD Customer Search</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<style>
BODY, TD {
font-family:Arial, Helvetica, sans-serif;
font-size:12px;
}
</style>
</head>
<body>
<form id="form1" name="form1" method="post" action="index.php">
<label>Search: </label>
<input type="text" name="string" id="string" size="20" value="<?php echo $_REQUEST["string"]; ?>" />
<label>Country: </label>
<select name="country">
<option value="">--</option>
<?php
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." GROUP BY country ORDER BY country";
$sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
while ($row = mysql_fetch_assoc($sql_result)) {
echo "<option value='".$row["country"]."'".($row["country"]==$_REQUEST["country"] ? " selected" : "").">".$row["country"]."</option>";
}
?>
</select>
<input type="submit" name="button" id="button" value="Filter" />
</label>
Reset
</form>
<br />
<table style="text-align: left; width: 100%;" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td style="text-align: left;"><input type="submit" name="btnexportdata" value="Export Data" /></td>
<td style="text-align: right;">
<form method="post" action="input.php">
<input type="submit" value="Add" />
</form></td>
</tr>
</tbody>
</table>
<br />
<table width="100%" border="1" cellspacing="0" cellpadding="4">
<tr>
<td width="150" bgcolor="#CCCCCC"><strong>Account Number</strong></td>
<td width="150" bgcolor="#CCCCCC"><strong>Company Name</strong></td>
<td width="150" bgcolor="#CCCCCC"><strong>Country</strong></td>
<td width="150" bgcolor="#CCCCCC"><strong>Email</strong></td>
<td width="150" bgcolor="#CCCCCC"><strong>Phone Number</strong></td>
<td width="150" bgcolor="#CCCCCC"><strong>Brands</strong></td>
</tr>
<?php
if ($_REQUEST["string"]<>'') {
$search_string = " AND (cname LIKE '%".mysql_real_escape_string($_REQUEST["string"])."%' OR email LIKE '%".mysql_real_escape_string($_REQUEST["string"])."%' OR accnumber LIKE '%".mysql_real_escape_string($_REQUEST["string"])."%' OR pnumber LIKE '%".mysql_real_escape_string($_REQUEST["string"])."%' OR brands LIKE '%".mysql_real_escape_string($_REQUEST["string"])."%')";
}
if ($_REQUEST["country"]<>'') {
$search_country = " AND country='".mysql_real_escape_string($_REQUEST["country"])."'";
}
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." WHERE id>0".$search_string.$search_country;
$sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
if (mysql_num_rows($sql_result)>0) {
while ($row = mysql_fetch_assoc($sql_result)) {
?>
<tr>
<td><?php echo $row["accnumber"]; ?></td>
<td><?php echo $row["cname"]; ?></td>
<td><?php echo $row["country"]; ?></td>
<td><?php echo $row["email"]; ?></td>
<td><?php echo $row["pnumber"]; ?></td>
<td><?php echo $row["brands"]; ?></td>
</tr>
<?php
}
} else {
?>
<tr><td colspan="6">No results found.</td>
<?php
}
?>
</table>
</body>
</html>

here is the code you can try
// Define database connection variable dynamically
$DB_Server = "localhost"; //MySQL Server
$DB_Username = "root"; //MySQL Username
$DB_Password = ""; //MySQL Password
$DB_DBName = "test1"; //MySQL Database Name
$DB_TBLName = "tabletest"; //MySQL Table Name
$filename = "excelfilename"; //File Name
//create MySQL connection
$sql = "Select * from csvtable";
$Connect = #mysqli_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL:<br>" . mysqli_error() . "<br>" . mysql_errno());
//select database
$Db = #mysqli_select_db( $Connect,$DB_DBName) or die("Couldn't select database:<br>" . mysqli_error() . "<br>" . mysql_errno());
//execute query
$result = #mysqli_query( $Connect,$sql) or die("Couldn't execute query:<br>" . mysqli_error() . "<br>" . mysql_errno());
function cleanData(&$str)
{
if ($str == 't')
$str = 'TRUE';
if ($str == 'f')
$str = 'FALSE';
if (preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
$str = "'$str";
}
if (strstr($str, '"'))
$str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "file_" . date('Ymd') . ".csv";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: text/csv;");
$out = fopen("php://output", 'w');
$flag = false;
while ($row = mysqli_fetch_assoc($result))
{
if (!$flag)
{
// display field/column names as first row
fputcsv($out, array_keys($row), ',', '"'); $flag = true;
}
array_walk($row, 'cleanData');
// insert data into database from here
fputcsv($out, array_values($row), ',', '"');
}
fclose($out);
exit;
//end

Related

PHP Mysql Pasing as parameter TextArea more than 1 line

I am having an issue to pass a textarea to another page when contains more than one line.
I have 3 pages:
1.-_testInsertText.php = INSERT a new text in Database
2.-_testShowText.php = SELECT the texts from Database and redirect to Modify Page
3.-_testTextModify.php = UPDATE the text passed by _testShowText.php
My structure from my table from Database:
CREATE TABLE `tblTest`
(
`clmSerie` int (11) NOT NULL
,`clmTextArea` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
If I insert a text with two lines through _testInsertText.php I am able to display correctly through _testShowText.php
My problem is in redirecting (through href) those records with more than one line to _testTextModify.php page (For 1 line is working fine). It is not redirecting.
Could you please help me?
My code can be found below:
1.-_testInsertText.php
<?php
$txtEvolucion = '';
if(isset($_POST['Insert']) && isset($_POST["txtEvolucion"]))
{
$txtEvolucion = $_POST["txtEvolucion"];
require_once('mysqli_connect.php');
echo "<br>". "txtEvolucion={" . $txtEvolucion ."}";
$query = "INSERT INTO tblTest (clmTextArea) VALUES (?)";
$stmt = mysqli_prepare($dbc, $query);
mysqli_stmt_bind_param($stmt, "s", $txtEvolucion);
mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
echo $affected_rows;
if($affected_rows == 1)
{
$txtEvolucion = '';
echo "Inserted";
mysqli_stmt_close($stmt);
}
else
{
ini_set('display_errors', 'On');
mysqli_stmt_close($stmt);
}
}
?>
<html>
<head>
<title>Insert TextArea</title>
</head>
<body>
<h1>Insert TextArea</h1>
<div id="divAgenda">
<form id="contact" action="" method="post">
<fieldset>
<textarea id="txtEvolucion" name="txtEvolucion" tabindex="4" cols="90" rows="7"
value="<?= $txtEvolucion ?> "
><?= $txtEvolucion ?></textarea><br><br>
<button name="Insert" type="submit" id="contact-submit" data-submit="...Sending">Insert</button><br>
</fieldset>
</form>
</body>
</html>
2.-_testShowText.php
<?php
$output = '';
require_once('mysqli_connect.php');
$query = mysqli_query($dbc,"SELECT clmSerie
,clmTextArea
FROM tblTest
"
) or die('Error to select!: {' . mysqli_error($dbc) . '}');
$count = mysqli_num_rows($query);
$output .= '<table border="1" align="left" cellspacing="5" cellpadding="8">
<tr><td align="left"><b>MODIFY </b></td>
<td align="left"><b>Id </b></td>
<td align="left"><b>Text Area </b></td>
</tr>';
while($row = mysqli_fetch_array($query))
{
$serie = $row['clmSerie'];
$descripcion = utf8_encode($row['clmTextArea']);
$descripcion = nl2br($descripcion);
$output .= '<tr><td align="left"><a href="_testTextModify.php?descripcion=' . $descripcion .
'&serie=' . $serie .
'">Modify
</a></td>
<td align="left">' .$serie . '</td>
<td align="left">' .$descripcion . '</td>
';
$output .= '</tr>';
}
?>
<html>
<head>
<title>Show TextArea</title>
</head>
<body>
<h1>Show TextArea</h1>
<?php echo $output;?>
</body>
</html>
3.-_testTextModify.php
<?php
$txtEvolucion = '';
$txtEvolucionOld = $_GET['descripcion'];
$idSerie = $_GET['serie'];
echo "<br>". "txtEvolucionOld={" . $txtEvolucionOld ."}";
if(isset($_POST['Modify']) && isset($_POST["txtEvolucion"]))
{
$txtEvolucion = $_POST["txtEvolucion"];
require_once('mysqli_connect.php');
echo "<br>". "txtEvolucion={" . $txtEvolucion ."}";
$query = "UPDATE tblTest
SET clmTextArea = ?
WHERE clmTextArea = ?
AND clmSerie = ?
";
$stmt = mysqli_prepare($dbc, $query);
mysqli_stmt_bind_param($stmt, "sss", $txtEvolucion, $txtEvolucionOld, $idSerie);
mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
echo $affected_rows;
if($affected_rows == 1)
{
$txtEvolucion = '';
echo "Modified";
mysqli_stmt_close($stmt);
}
else
{
ini_set('display_errors', 'On');
mysqli_stmt_close($stmt);
}
}
?>
<html>
<head>
<title>Modify TextArea</title>
</head>
<body>
<h1>Modify TextArea</h1>
<div id="divAgenda">
<form id="contact" action="" method="post">
<fieldset>
<textarea id="txtEvolucion" name="txtEvolucion" tabindex="4" cols="90" rows="7"
value="<?= $txtEvolucion ?> "
><?= $txtEvolucionOld ?></textarea><br><br>
<button name="Modify" type="submit" id="contact-submit" data-submit="...Sending">Modify</button><br>
</fieldset>
</form>
</body>
</html>
Thanks to comment by Sloan Thrasher, I modified _testTextModify.php and _testShowText.php
And now I am passing content to a hidden TextArea instead of a href to the modify page and it is working fine now when it comes with more than one line.
Thank you everyone :)
The new code below:
_testTextModify.php
<?php
if(isset($_POST['fromTestShowText']))
{
$txtEvolucionOld = $_POST['descripcion'];
$idSerie = $_POST['serie'];
}
if(isset($_POST['Modify']) && isset($_POST["txtEvolucionOld"]))
{
$txtEvolucionOld = $_POST["txtEvolucionOld"];
require_once('mysqli_connect.php');
$query = "UPDATE tblTest
SET clmTextArea = ?
WHERE clmSerie = ?
";
$stmt = mysqli_prepare($dbc, $query);
mysqli_stmt_bind_param($stmt, "ss", $_POST['txtEvolucionOld'], $_POST['idSerie']);
mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
echo "<br>". "affected_rows={" . $affected_rows ."}";
if($affected_rows == 1)
{
$txtEvolucionOld = $recibeSerieEvolucion = '';
echo "Modified";
mysqli_stmt_close($stmt);
}
else
{
ini_set('display_errors', 'On');
mysqli_stmt_close($stmt);
}
}
?>
<html>
<head>
<title>Modify TextArea</title>
</head>
<body>
<br>Show
<br>Insert
<h1>Modify TextArea</h1>
<div id="divAgenda">
<form id="contact" action="" method="post">
<fieldset>
<input type="hidden" readonly id="idSerie" name="idSerie" size="2" type="text" maxlength="100" tabindex="3"
value="<?= $idSerie ?>"
><br>
<textarea id="txtEvolucionOld" name="txtEvolucionOld" tabindex="4" cols="90" rows="7"
value="<?= $txtEvolucionOld ?> "
><?= $txtEvolucionOld ?></textarea><br><br>
<button name="Modify" type="submit" id="contact-submit" data-submit="...Sending">Modify</button><br>
</fieldset>
</form>
</body>
</html>
_testShowText.php
<?php
$output = '';
require_once('mysqli_connect.php');
$query = mysqli_query($dbc,"SELECT clmSerie
,clmTextArea
FROM tblTest
"
) or die('Error to select!: {' . mysqli_error($dbc) . '}');
$count = mysqli_num_rows($query);
$output .= '<table border="1" align="left" cellspacing="5" cellpadding="8">
<tr><td align="left"><b>MODIFY </b></td>
<td align="left"><b>Id </b></td>
<td align="left"><b>Text Area </b></td>
</tr>';
while($row = mysqli_fetch_array($query))
{
$serie = $row['clmSerie'];
$descripcion = utf8_encode($row['clmTextArea']);
//$descripcion = nl2br($descripcion);
$output .= '<tr><td align="left"><form action="_testTextModify.php" method="post">
<button name = "fromTestShowText" type="image"
value="Submit">Modify
</button>
</td>
<td align="left">' .$serie . '</td>
<td align="left"><input hidden readonly id="serie" name="serie" type="text"
value="'. $serie . '"
>
<textarea id="descripcion" name="descripcion" cols="50" rows="6"
value = "'.$descripcion.'"
readonly>'. $descripcion .'</textarea>
</td>
</form>';
$output .= '</tr>';
}
?>
<html>
<head>
<title>Show TextArea</title>
</head>
<body>
<br>Show
<br>Insert
<h1>Show TextArea</h1>
<?php echo $output;?>
</body>
</html>

fetch a foreign key data from mysql database into select dropdownlist using php

I want to create a select dropdownlist which retrieves data from a table "teamtable" and displays it on a page where the user enters his choice and the corresponding ID for the choice is submitted in other database "user" where the column is a foreign key.
Tables and their contents-
teamtable-
idTeam(INT)(PK) - 1,2,3
teamName(VARCHAR) - Team-1, Team-2, Team-3
user-
team(INT)(FK)
<html>
<head>
<script type="text/javascript">
function validateForm()
{
var f=document.forms["reg"]["team"].value;
if ((f==null || f==""))
{
alert("All Field must be filled out");
return false;
}
}
</script>
<form name="reg" action="user_exec.php" onsubmit="return validateForm()" method="post">
<table width="274" border="0" align="center" cellpadding="2" cellspacing="0">
<tr>
<td colspan="2">
<div align="center">
<?php
$remarks=$_GET['remarks'];
if ($remarks==null and $remarks=="")
{
echo 'Register a new user';
}
if ($remarks=='success')
{
echo 'Registration Success';
}
?>
</div></td>
</tr>
<tr>
<td><div align="right">Team:</div></td>
<td>
<?php
$mysqli_hostname = "localhost";
$mysqli_user = "root";
$mysqli_password = "my_pass";
$mysqli_database = "my_db";
$prefix = "";
$bd = mysqli_connect($mysqli_hostname, $mysqli_user, $mysqli_password) or die("Could not connect database");
mysqli_select_db($mysqli_database, $bd) or die("Could not select database");
$sql = "SELECT idTeam,teamName FROM teamtable ";
$result = mysqli_query($sql);
echo "<select name='team'>";
while ($row=mysqli_fetch_array($result))
{
echo "<option value='" . $row['idTeam'] ."'>" . $row['teamName'] ."</option>";
}
echo "</select>";
?>
</td>
</tr>
<tr>
<td><div align="right"></div></td>
<td><input name="submit" type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</head>
</html>
<?php
include('connection.php');
$sql = "SELECT idTeam, teamName FROM team";
$result = $conn->query($sql);
echo "<select name='team'>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row['idTeam'] ."'>" . $row['teamName'] ."</option>";
}
echo "</select>";
} else {
echo "0 results";
}
$conn->close();
?>

selection of query using multiple selection

I am beginner to php.I want to select the department from the options and after the selection of the department, I want to display the roll no in the next drop down box belong to that department. Help me by providing some ideas related to my questions.
<!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>Untitled Document</title>
</head>
<body>
<?php include('C:\wamp\www\fms\background.php'); ?>
<?php include('C:\wamp\www\fms\adminmenu.php'); ?>
<?php
if (isset($_POST['delete'])) {
$con = mysql_connect("localhost", "root", "");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
$cid = $_POST['cid'];
$sql = "DELETE from addpassenger WHERE rno='$rno'";
mysql_select_db('fms');
$retval = mysql_query($sql, $con);
if (!$retval) {
die('Could not delete data: ' . mysql_error());
}
echo "Deleted data successfully\n";
mysql_close($con);
} else {
?>
<p></p>
<p></p>
<p></p>
<p></p>
<center>
<form method="post">
<table width="344" border="0" cellspacing="1" cellpadding="2">
<tr>
<td>SELECT THE DEPARTMENT</td>
<td><?php
$con = mysql_connect("localhost", "root", "") or die(mysql_error());
$db = #mysql_select_db("fms", $con) or die(mysql_error());
$str = "select dept from addpassenger";
$res1 = #mysql_query($str);
echo '<select name="dept">';
echo '<option selected="----------"></option>';
while ($row = mysql_fetch_array($res1)) {
echo '<option value="' . $row['dept'] . '">' . $row['dept'] . '</option>';
}
echo '</select>';
?></td>
</tr>
<tr>
<td width="208">SELECT THE ROLL NO</td>
<td width="125">
<?php
$con = mysql_connect("localhost", "root", "") or die(mysql_error());
$db = #mysql_select_db("fms", $con) or die(mysql_error());
$str = "select rno from addpassenger ";
$res1 = #mysql_query($str);
echo '<select name="rno">';
echo '<option selected="----------"></option>';
while ($row = mysql_fetch_array($res1)) {
echo '<option value="' . $row['rno'] . '">' . $row['rno'] . '</option>';
}
echo '</select>';
?>
</select>
</td>
</tr>
<tr>
<td width="208"></td>
<td></td>
</tr>
<tr>
<td width="208"></td>
<td>
<input name="delete" type="submit" id="delete" value="Delete">
</td>
</tr>
</table>
</form>
</center>
<?php
}
?>
</body>
</html>
select rno from addpassenger
needs to have a where clause which selects based on previous selection

No results during a search through Mysqli

I'm having the problem to pull out data from my database through a search field. I'm trying to protect my searchfield against Sql injection at the same time. Adding data to my database is working fine, and I think i did fine safetywise. Yet, pulling the data out seems to be harder.
All i'm trying to achieve is getting all the data from the person. I'm looking for "Bart" in my search field, so show me all the data from all the Barts in my database.
This is my HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
<link rel="stylesheet" href="style.css">
<link href='http://fonts.googleapis.com/css?family=Raleway:200' rel='stylesheet' type='text/css'>
<script src="script.js"></script>
</head>
<body>
<table class="table_form">
<form method="POST" action="test.php">
<tr>
<td>Voornaam: </td><td><input type="text" name="Voornaam"></td>
</tr>
<tr>
<td>Achternaam: </td><td><input type="text" name="Achternaam"></td>
</tr>
<tr>
<td>Adres: </td><td><input type="text" name="Adres"></td>
</tr>
<tr>
<td>Discipline: </td><td><input type="text" name="Discipline"></td>
</tr>
<tr>
<td>Graad: </td><td><input type="text" name="Graad"></td>
</tr>
<tr>
<td>Voeg toe aan databank: </td><td><input type="submit" name="Adddb" value="Bevestigen"></td>
</tr>
</form>
</table>
<table class="table_form">
<form method="POST" action="test.php">
<tr>
<td>Zoeken</td><td><input type="text" name="Voornaam" /></td>
</tr>
<tr>
<td>Bevestigen</td><td><input type="submit" name="zoeken" /></td>
</tr>
</form>
</table>
<div class="field">
<?php
require_once 'isset.php';
?>
</div>
</body>
</html>
This is the PHP
<?php
require_once 'login.php';
$db_con= new mysqli($db_host, $db_username, $db_password, $db_database);
$db_con->set_charset("utf8");
if($db_con->connect_error) die ("(" . $db_con->connect_error . " Error during connection");
if(isset($_POST['Adddb'])){
$stmt = $db_con->prepare("INSERT INTO customers (Voornaam, Achternaam, Adres, Actief, Discipline, graad) VALUES(?,?,?,NOW(),?,?)");
$stmt->bind_param("sssii",$voornaam, $achternaam, $adres, $discipline,$graad);
$voornaam = $_POST['Voornaam'];
$achternaam = $_POST['Achternaam'];
$adres = $_POST['Adres'];
$discipline = $_POST['Discipline'];
$graad = $_POST['Graad'];
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$db_con->close();
}
if(isset($_POST['zoeken'])){
$stmte = $db_con->prepare="SELECT * FROM customers WHERE Voornaam = (?)";
$stmte->bind_param("s", $zoeknaam);
$zoeknaam = $_POST['Voornaam'];
$stmte->execute();
echo $zoeknaam;
}
?>
Am i wrong to think that i'm not fetching something? And that is the reason i'm not getting anything?
EDIT ------>
Edited version as suggested below: Errors are gone but no results show up:
<?php
require_once 'login.php';
$db_con= new mysqli($db_host, $db_username, $db_password, $db_database);
$db_con->set_charset("utf8");
if($db_con->connect_error) die ("(" . $db_con->connect_error . " Error during connection");
if(isset($_POST['zoeken'])){
$zoeknaam = $_POST['Zoek']; // declare the input here
$stmte = $db_con->prepare("SELECT * FROM customers WHERE Voornaam = ?");
$stmte->bind_param("s", $zoeknaam); // then use inside here
$stmte->execute();
$rows = $stmte->num_rows;
for($i=0; $i < $rows; $i++){
$row=mysqli_fetch_array($stmte, MYSQLI_ASSOC);
echo $row['Voornaam'] . '<br/>';
}
/*if($stmte->num_rows > 0) {
$results = $stmte->get_result();
while($row = $results->fetch_assoc()) {
echo $row['Achternaam'] . '<br/>';
// and other columns
}*/
}
?>
You should fetch the results properly by using ->get_result(). After that, you would be able to use ->fetch_assoc(). Example:
$zoeknaam = $_POST['Voornaam']; // declare the input here
$stmte = $db_con->prepare("SELECT * FROM customers WHERE Voornaam = ?");
$stmte->bind_param("s", $zoeknaam); // then use inside here
$stmte->execute();
if($stmte->num_rows > 0) {
$results = $stmte->get_result();
while($row = $results->fetch_assoc()) {
echo $row['Voornaam'] . '<br/>';
echo $row['Achternaam'] . '<br/>';
// and other columns
}
}
If unfortunately, you do not have mysqlnd in your environment (if ->get_result() turns out the be Call to undefined method). Here's another way:
$zoeknaam = $_POST['Voornaam'];
$stmte = $db_con->prepare("SELECT * FROM customers WHERE Voornaam = ?");
$stmte->bind_param("s", $zoeknaam);
$stmte->execute();
// get all columns
$meta = $stmte->result_metadata();
while ($field = $meta->fetch_field()) {
$params[] = &$row[$field->name];
}
call_user_func_array(array($stmte, 'bind_result'), $params);
while ($stmte->fetch()) {
echo $row['Voornaam'] . '<br/>';
echo $row['Achternaam'] . '<br/>';
}

Form is failing to update mysql table

So I'm currently working with a form where the admin can select multiple users from the database via a tickbox system, then change the welcome message or general message to a client when they log in:
<?php
session_start();
include_once("isadmin.php");
?>
<!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>Update Client Message</title>
<link href="loginmodule.css" rel="stylesheet" type="text/css" />
</head>
<body>
<?php
if( isset($_SESSION['ERRMSG_ARR']) && is_array($_SESSION['ERRMSG_ARR']) && count($_SESSION['ERRMSG_ARR']) >0 ) {
echo '<ul class="err">';
foreach($_SESSION['ERRMSG_ARR'] as $msg) {
echo '<li>',$msg,'</li>';
}
echo '</ul>';
unset($_SESSION['ERRMSG_ARR']);
}
?>
<form id="updateform" name="updateform" method="post" action="updateexec.php">
<table width="500" border="0" align="center" cellpadding="2" cellspacing="0">
<tr>
<th width="200">Select User</th>
<td>
<?php
require_once('config.php');
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
$useruploadids = mysql_query("SELECT member_id, firstname, lastname FROM members");
while ($row = mysql_fetch_assoc($useruploadids)) {
$userid = $row['member_id'];
$firstname = $row['firstname'];
$lastname = $row['lastname'];
?>
<input type="checkbox" name="userid_<?php echo $userid ?>" value="y" /><?php echo $firstname ?><?php echo $lastname ?><br />
<?php } ?>
</td>
</tr>
<tr>
<th>Message For Client </th>
<td>
<textarea input name="otherdeets" type="textarea" class="textfield" id="otherdeets" style="width: 356px; height: 176px">
</textarea>
</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Update" /></td>
</tr>
</table>
</form>
</body>
</html>
So this is the form, and it works fine, it calls all users from the database and displays them in tickbox fasion.
I can only assume my issue is in the exec script:
<?php
echo( "<pre>" );
print_r( $_POST );
echo( "</pre>" );
include ("config.php");
$tbl_name="members";
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
//This gets all the other information from the form
$update = $_POST['otherdeets'];
$id = $_POST['userid'];
// Cycle through each member and check that it needs to be added to the db
$useruploadids = mysql_query( "SELECT member_id FROM members" );
while ($row = mysql_fetch_assoc($useruploadids))
{
// Check that the member was sent from the last form
if( isset( $_POST['userid_'.$row['member_id']] ) && $_POST['userid_'.$row['member_id']] == "y" )
{
// update data in mysql database
$sql="UPDATE $tbl_name SET otherdeets='$update' WHERE id='$id'";
$result=mysql_query($sql);
}
}
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='admin-welcome.php'>Admin Home</a>";
}
else {
echo "ERROR";
}
?>
When I run the script it simply says:
Array
(
[userid_1] => y
[otherdeets] => Blah Blah
[Submit] => Update
)
ERROR
Any idea what is wrong? Knowing my luck it would probabaly be a spelling mistake
Thank you
Hey your query is wrong there should be where condition with appropriate column name i.e. "member_id"
And one more thing
you are fetching the $id = $_POST['userid']; which is an error as there is no value exist with that key
rather you do in the if condition before doing the update query, i.e.
$id = $POST['userid'.$row['member_id']];

Categories