This is my HTML code:
<input type='checkbox' name='cbox[]' value='Jaywalking'/>
Jaywalking<br/>
<input type='checkbox' name='cbox[]' value='Littering'/>
Littering<br/>
<input type='checkbox' name='cbox[]' value='Illegal Vendor'/>
Illegal Vendor
This is my posting code:
if(is_array($_POST['cbox']))
$violation_save=implode(',',$_POST['cbox']);
else
$violation_save=$_POST['cbox'];
mysql_query("UPDATE tblcitizen SET violation='$violation_save' WHERE id='$id'") or die mysql_error());
How can I fetch the selected values from the database?
First of all you should NOT use the mysql_* functions of php anymore. These functions are marked as deprecated and will be removed in the next major php release.
So if $_POST['cbox'] is an array, you must handle it as an array.
// how to save checked values
try {
$db = new PDO(...);
$stmt = $db->prepare("UPDATE yourTable SET myField = :myField WHERE id = :id");
$stmt->bindParam(':id' , $id, PDO::PARAM_INT);
foreach ($_POST['cbox'] as $myField) {
$stmt->bindParam(':myField', $myField);
$stmt->execute();
}
} catch (PDOException $e) {
// error handling
}
// how to fetch checked values
try {
$myValues = array();
$db = new PDO(...);
$stmt = $db->prepare("SELECT myField FROM myTable WHERE id = :id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$myValues[] = $row['myField'];
}
} catch (PDOException $e) {
// error handling
}
// HTML Part
<input type="checkbox" name="cbox[]" value="bla"<?php if (in_array('bla', $myValues)) { ?> checked="checked"<?php } ?> />
Just have a look at the php manual for PDO or the MySQLi extension.
Related
I am currently trying to make a multi select list where items can be added and removed based on two columns. The left column is the full list and the right column where all the selected items are displayed. On submit the right column adds all newly selected items into the USERVIDEOS database.
The issue however is removing items from the USERVIDEOS database if they are removed from the right column. When pressing submit the USERVIDEOS database should only have rows for items currently in the right column and remove those no longer in there.
Example image
I have several items however I am unable to solve the issue. I've tried the following code:
if($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['user-videos'])) {
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("DELETE FROM USERVIDEOS WHERE userID = :userID AND videoID NOT IN (:videos)");
$stmt->bindParam(':userID', $userID);
$stmt->bindValue(':videos', implode(",", $_POST['user-videos']));
$stmt->execute();
// Add the new Videos
$stmt = $conn->prepare("INSERT INTO USERVIDEOS (userID, videoID) VALUES (:userID, :videoID)");
$stmt->bindParam(':userID', $userID);
$selected = $_POST['user-videos'];
foreach ($selected as $videoID) {
$stmt->bindParam(':videoID', $videoID);
$stmt->execute();
}
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
however, this results in removing everything but the newly selected items. The goal is to only remove those that got removed from the right column and add those that got added to the right column.
HTML
<div class="form_container">
<form name="videos" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="lvids">
<label for="video-list">Database Videos:</label>
<select class="videolist" id="video-list" size="10" name="video-list[]" multiple>
<?php
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Retrieve all video IDs from the USERVIDEOS table
$stmt1 = $conn->prepare("SELECT videoID FROM USERVIDEOS WHERE userID = :userID");
$stmt1->bindParam(':userID', $userID);
$stmt1->execute();
$filterVideos = $stmt1->fetchAll(PDO::FETCH_COLUMN, 0);
if(sizeof($filterVideos) != 0) {
$stmt2 = $conn->prepare("SELECT ID, videotitle FROM VIDEOS WHERE ID NOT IN (".implode(',', $filterVideos).") ORDER BY categorie ASC");
$stmt2->execute();
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC)) {
echo "<option value='" . $row['ID'] . "'>" . $row['videotitle'] . "</option>";
}
} else {
$stmt = $conn->prepare("SELECT ID, videotitle FROM VIDEOS ORDER BY categorie ASC");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<option value='" . $row['ID'] . "'>" . $row['videotitle'] . "</option>";
}
}
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
$conn = null;
$stmt = null;
?>
</select>
</div>
<div class="button_container">
<input class="btn" type="button" value=">>" id="add-btn">
<input class="btn" type="button" value="<<" id="remove-btn">
</div>
<div class="uvids">
<label for="user-videos">Selected Videos:</label>
<select class="uservideos" id="user-videos" size="10" name="user-videos[]" multiple>
<?php
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT VIDEOS.ID, VIDEOS.videotitle FROM VIDEOS
JOIN USERVIDEOS ON USERVIDEOS.videoID = VIDEOS.ID
WHERE USERVIDEOS.userID = :userID");
$stmt->bindParam(':userID', $userID);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row) {
echo "<option value='" . $row['ID'] . "'>" . $row['videotitle'] . "</option>";
}
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
?>
</select>
</div>
<br><br>
<input type="submit" value="Upload Videos">
</form>
</div>
If more information is required, just ask.
I've found a solution (non ideal) to the problem.
I've utilized javascript to select all options within the right column on the button submit. After this PHP removed all entries within the database where userID = $userID and after this adds all selected options back in.
The problem has been solved with a workaround. However, ideally, the database should remove everything and add items back that were there before.
Javascript utilized to select all options within the select:
$('#submit-button').click(function(event) {
event.preventDefault(); // prevent the form from being submitted
$('#user-videos option').prop('selected', true);
$('#videos').submit();
});
I am writing a web application and I believe one of the parts requires a
multidimensional array. The array holds a list of applications in a database.
I want to be able to display the list of applications by the individuals name or
a unique ID. I have this part working. Then I want to click on an individual
application and only pull up that particular row of information to fill in a form.
Currently when I do this it either brings up all of the rows from the database or
the first row only. Does anyone have any suggestions?
I am not great with explanations so I am including parts of my code. I am sorry
it's so long. I tried to reduce it as much as possible. Even though its included
in the code, i didn't include config.php because it's just my database connection.
userList.php:
<?php
include("config.php");
?>
<!DOCTYPE html>
<html>
<body>
<h1>Test</h1>
<p><b><u>Users</b></u></p>
</body>
</html>
<?php
require_once("/class/users.php");
$rowt = array(array());
$rowt = users::fillForm($rowt);
foreach($rowt as $test) {
if(is_array($test))
{
echo "<a href='userDisplay.php'>".$test['name']."</a><br/>";
}
}
?>
userDisplay.php:
<!DOCTYPE html>
<html>
<body>
<h1>Tester</h1>
<?php
include("config.php");
//declare array
$rowt = array(array());
//pass array into class function
//since functions can't return more than one variable, you have to pass the
//array and set it equal to the original variable while calling the pdo function
$rowt = users::fillForm($rowt);
foreach($rowt as $test=> $rowt){
?>
<h2>Application for <?php echo $rowt['name']?></h2>
<table>
<tr><th><b>Name</b></th>
<th><b>Phone Number</b></th>
<th><b>Best Time to Call<b></th>
</tr>
<tr></tr>
<tr><td><output type='text' maxlength="30" required name='name'><?php echo $rowt['name']?></output></td>
<td><output type="text" maxlenth="30" required name="p_num"><?php echo $rowt['phone_number']?></output></td>
<td><output type='text' maxlength="30" required name='bc_time'><?php echo $rowt['best_call_time']?></output></td></tr>
<tr></tr>
<tr>
<th><b>Visa Status<b></th>
<th><b>IT Experience<b></th>
<th><b>Relevant Experience<b></th>
</tr>
<tr></tr>
<tr><td><output type='text' maxlength="30" required name='v_status'><?php echo $rowt['visa_status']?></output></td>
<td><output type='text' maxlength="30" required name='it_exp'><?php echo $rowt['it_exp']?></output></td>
<td><output type='text' maxlength="30" required name='rel_exp'><?php echo $rowt['relevant_exp']?></output></td>
</tr>
<tr></tr>
<tr>
<th colspan="3"><b>Description<b></th>
</tr>
<tr></tr>
<tr>
<td colspan="3"><output name="description" rows="4" cols="100"></output><?php echo $rowt['description']?>></td>
</tr>
</table>
</body>
</html>
<?php
}
echo "<a href='userList.php'>Back</a>";
?>
Functions from users.php users class:
public function insertForm() {
$correct = false;
try {
$con = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO user(name, phone_number, best_call_time, description,
visa_status, it_exp, relevant_exp) VALUES(:name, :p_num, :bc_time, :description,
:v_status, :it_exp, :rel_exp)";
$stmt = $con->prepare($sql);
$stmt->bindValue("name", $this->name, PDO::PARAM_STR);
$stmt->bindValue("p_num", $this->p_num, PDO::PARAM_STR);
$stmt->bindValue("bc_time", $this->bc_time, PDO::PARAM_STR);
$stmt->bindValue("v_status", $this->v_status, PDO::PARAM_STR);
$stmt->bindValue("it_exp", $this->it_exp, PDO::PARAM_STR);
$stmt->bindValue("rel_exp", $this->rel_exp, PDO::PARAM_STR);
$stmt->bindValue("description", $this->description, PDO::PARAM_STR);
$stmt->execute();
return "Entry Successful <br/> <a href='userForm.php'>Home</a>";
}catch(PDOException $e) {
return $e->getMessage();
}
}
public static function fillForm($rowt) {
$successt = false;
try{
$conn = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql1 = "SELECT * FROM user";
$stmt1 = $conn->prepare($sql1);
$stmt1->execute();
$rowt = $stmt1->fetchAll(PDO::FETCH_NUM&PDO::FETCH_ASSOC);
return $rowt;
}catch (PDOException $et) {
echo $et->getMessage();
return $successt;
}
}
There is a lot going on here, but if I get the gist of your question you want to be able to return one individual user when a row in a list of users is clicked. To do that you would need to update your SQL query to pull a particular user. Something along the lines of:
// Formatting into a class to cut down on repetition.
<?php
class User {
private $dbConnect;
// functionally these two are similar but I separated users and user
// for clarity of purpose.
public function getUsers()
{
// Enumerating your select columns is clearer, and more efficient.
$sql = "SELECT name, phone_number, best_call_time, description,
visa_status, it_exp, relevant_exp
FROM user";
$result = $this->makeQuery($sql);
return ($result) ? $result : array();
}
public function getUser($name)
{
// Enumerating your select columns is clearer, and more efficient.
$sql = "SELECT name, phone_number, best_call_time, description,
visa_status, it_exp, relevant_exp
FROM user
WHERE name = :name";
$param = $this->prepareUserInfo(array('name' => $name));
$result = $this->makeQuery($sql, $param);
return ($result) ? $result : array();
}
public function createUser($userInfo)
{
$sql = "INSERT INTO user(name, phone_number, best_call_time, description,
visa_status, it_exp, relevant_exp) VALUES(:name, :p_num, :bc_time, :description,
:v_status, :it_exp, :rel_exp)";
$params = $this->prepareUserInfo($userInfo);
try {
$this->connect();
$stmt = $this->dbConnect->prepare($sql);
$stmt = $this->bindParams($stmt, $data);
$stmt->execute();
return "Entry Successful <br/> <a href='userForm.php'>Home</a>";
} catch(PDOException $e) {
return $e->getMessage();
}
}
private function prepareUserInfo($userInfo)
{
$infoArray = array();
foreach ($userInfo as $key => $value) {
// Going with your original code I'm hardcoding param type here, but
// you could easily write a check for data type and set param dynamically.
$infoArray[] = array(
'key' => $key,
'value' => $value,
'type' => PDO::PARAM_STR,
);
}
return $infoArray;
}
private function makeQuery($sql, $data = array())
{
try{
$this->connect();
$stmt = $this->dbConnect->prepare($sql);
if (!empty($data)) {
$stmt = $this->bindParams($stmt, $data);
}
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_NUM&PDO::FETCH_ASSOC);
return (!empty($result)) ? $result : false;
} catch (PDOException $e) {
echo $e->getMessage();
return false;
}
}
private function bindParams($stmt, $data)
{
foreach ($data as $item) {
$stmt->bindValue("name", $this->name, PDO::PARAM_STR);
$stmt->bindValue($item['key'], $item['value'], $item['type']);
}
return $stmt;
}
private function connect()
{
$dbConnect = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
$dbConnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->dbConnect = $dbConnect;
}
}
?>
From there your click handler would need to trigger a User->getUser('some name'); request. You could take this abstraction further by separating your PDO connect into it's own class and handle query building and execution from there.
Seconding the above comment about not mixing your presentation with your data layer. Check out a templating engine like Twig or (less advisable but sometimes necessary) roll your own by building a view loader that loads template files to an output buffer, adds dynamic variables, and returns a rendered string.
I have a problem , i want to create with autocomplete to get back suggested information e.g A11 - some text, but i get back only e.g A11. I think that definetly problem is passing values from query in array and how to pass and structure array to display wanted data with autocomplete.
HTML
<form action='' method='post'>
<p><label>MKB dijagnoze: </label><input type='text' name='sifra_mkb' value='' class='auto'></p>
</form>
PHP
if (isset($_GET['term'])){
$return_arr = array();
try {
$conn = new PDO("mysql:host=".DB_SERVER.";port=3306;dbname=".DB_NAME, DB_USER, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT sifra_mkb,naziv_mkb FROM i_dijagnoze WHERE sifra_mkb LIKE :term');
$stmt->execute(array('term' => '%'.$_GET['term'].'%'));
while($row = $stmt->fetch()) {
$return_arr[] = $row['sifra_mkb'].' '.$row['naziv_mkb'];
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo json_encode($return_arr);
}
i'm building an website using php and html, im used to receiving data from a database, aka Dynamic Website, i've build an CMS for my own use.
Im trying to "simplify" the receiving process using php and functions.
My Functions.php looks like this:
function get_db($row){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$row = $stmt->fetchAll();
foreach ($row as $row) {
echo $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
}
Where i will get the rows content like this: $row['row'];
I'm trying to call it like this:
the snippet below is from the index.php
echo get_db($row['session_id']); // Line 22
just to show whats in all the rows.
When i run that code snippet i get the error:
Notice: Undefined variable: row in C:\wamp\www\Wordpress ish\index.php
on line 22
I'm also using PDO just so you would know :)
Any help is much appreciated!
Regards
Stian
EDIT: Updated functions.php
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
}
Instead of echoing the values from the DB, the function should return them as a string.
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
$result = '';
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$result .= $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
return $result;
}
Then call it as:
echo get_db();
Another option would be for the function to return the session IDs as an array:
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
$result = array();
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$result[] = $row['session_id'];
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
return $result;
}
Then you would use it as:
$sessions = get_db(); // $sessions is an array
and the caller can then make use of the values in the array, perhaps using them as the key in some other calls instead of just printing them.
As antoox said, but a complete changeset; change row to rows in two places:
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo $row['session_id'] . ", ";
}
Putting this at the start of the script after <?php line will output interesting warnings:
error_reporting(E_ALL|E_NOTICE);
To output only one row, suppose the database table has a field named id and you want to fetch row with id=1234:
$stmt = $pdo->prepare("SELECT * FROM lp_sessions WHERE id=?");
$stmt->bindValue(1, "1234", PDO::PARAM_STR);
I chose PDO::PARAM_STR because it will work with both strings and integers.
I need to make a PHP code that gets data from server, updates it and echos that updated data to user. I am beginner with PHP so I have no idea how to do this. This is the code I have have now.
So how do I change the code to make it update data ?
<?php
include 'config.php';
$ID = $_GET['ID'] ;
$sql = "select * from table where ID = \"$ID\" and condition = false ";
// This is what I need the table to be updated "Update table where where ID = \"$ID\" set condition = true" ;
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
echo '{"key":'. json_encode($data) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>
one idea is to create a different database connection file consisting of a pdo connection and reuse it in your application. on how to do that.
in database.php you can do it like
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
//catch the exception here and do whatever you like to.
}
and everywhere you want to use the connection you can do
require_once 'Database.php';
and some of the sample CRUD (Create, Read, Update, Delete) using PDO are.
//Create or Insert
$sth = $dbh->prepare("INSERT INTO folks ( first_name ) values ( 'Cathy' )");
$sth->execute();
//Read or Select
$sth = $dbh->query('SELECT name, addr, city from folks');
//Update
$sth = $dbh->prepare("UPDATE tablename SET col = val WHERE key = :value");
$sth->bindParam(':value', $value);
$sth->execute();
//Delete
$dbh->query('DELETE FROM folks WHERE id = 1');
you should also study about named and unnamed placeholders, to escape SQL injections etc. you can read more about PDO with a very easy to understand tutorial by nettuts here
hope this helps you.
Try this. I think it is along the lines of what you are looking for:
$query = "select * from table where ID = \"$ID\" and condition = false ";
$query_result = #mysql_query($query);
$query_row = mysql_fetch_assoc($query_result);
$update_query = "UPDATE table SET condition = true WHERE ID = {$row['ID']};";
if( #mysql_query($update_query) ) {
echo "Update succeeded!";
} else {
echo "Update failed!";
}
<?php
$ID = 1;
try {
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$select_statement = $db->prepare('select * from table1 where id = :id and `condition` = false');
$update_statement = $db->prepare('update table1 set `condition` = true where id = :id');
$select_statement->execute(array(':id' => $ID));
$results = $select_statement->fetchAll();
$update_statement->execute(array(':id' => $ID));
echo '{"key":' . json_encode($results) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>