This piece of code is working fine, what I want to is why if I remove the foreach($rows as $row) I gt an error, is there a way to display the data without using it.
<?php
require("coneccion.php");
if(empty($_SESSION['user']))
{
header("Location: index.php");
die("Redirecting to index.php");
}
$id = $_GET['id'];
$nombre = $_SESSION['user']['username'];
$query = "SELECT c.coursename FROM courses as c WHERE c.courseid = $id and c.id = (SELECT id FROM users WHERE username = '$nombre') ";
try
{
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
die("Error");
}
$rows = $stmt->fetchAll();
?>
<?php
foreach($rows as $row):
echo '<input type="text" name="coursename" value="' .htmlentities($row['coursename']) . '" />';
endforeach;
Assuming you're working with the standard PDO settings, you can access the first returned result like so:
echo '<input type="text" name="coursename" value="' .htmlentities($rows[0]['coursename']) . '" />';
To return the first row in your array you could do:
echo '<input type="text" name="coursename" value="'
.htmlentities($rows[0]['coursename']) . '" />';
Which will return the first row, but I dont recommend this. PHP array are hashtables they are incredibly fast you don't save yourself any style points by making your code less maintainable.
Related
I have the facility to update what I call 'documents' (ver similar to creating a post) on my cms which works fine but I have introduced categories where the documents are associated to them. Now I have managed to bind them when creating the doc from new but when trying update them I am getting a bit stuck. I am using checkboxes to show the list of categories and when selected it updates a join table which uses the doc_id and the cat_id.
Here is the script for updating the doc:
<?php
include ('includes/header.php');
require ('../../db_con.php');
echo '<h1>Document Edit</h1>';
// Check for a valid document ID, through GET or POST:
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) ) { // From view_docs.php
$id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) ) { // Form submission.
$id = $_POST['id'];
} else { // No valid ID, kill the script.
echo '<p class="error">This page has been accessed in error.</p>';
exit();
}
// Check if the form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array();
// Check for a document name:
if (empty($_POST['doc_name'])) {
$errors[] = 'You forgot to enter your document name.';
} else {
$dn = mysqli_real_escape_string($dbc, trim($_POST['doc_name']));
}
// Check for a document content:
if (empty($_POST['doc_content'])) {
$errors[] = 'You forgot to enter your last name.';
} else {
$dc = mysqli_real_escape_string($dbc, trim($_POST['doc_content']));
}
if (empty($errors)) { // If everything's OK.
// Test for unique doc title:
$q = "SELECT doc_id FROM docs WHERE doc_name='$dn' AND doc_id != $id";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) == 0) {
// Make the query:
$q = "UPDATE docs SET doc_name='$dn', doc_content='$dc', doc_name='$dn' WHERE doc_id=$id LIMIT 1";
$r = mysqli_query ($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
$doc_id = mysqli_insert_id($dbc);
$query = "UPDATE doc_cat_join (cat_id,doc_id) VALUES ";
$cat_ids = $_POST['cat_id'];
$length = count($cat_ids);
for ($i = 0; $i < count($cat_ids); $i++) {
$query.='(' . $cat_ids[$i] . ',' . $doc_id . ')';
if ($i < $length - 1)
$query.=',';
}
// Print a message:
echo '<p>The document has been edited.</p>';
} else { // If it did not run OK.
echo '<p class="error">The document could not be edited due to a system error. We apologize for any inconvenience.</p>'; // Public message.
echo '<p>' . mysqli_error($dbc) . '<br />Query: ' . $q . '</p>'; // Debugging message.
}
} else { // Already used.
echo '<p class="error">The document name has already been used.</p>';
}
} else { // Report the errors.
echo '<p class="error">The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo " - $msg<br />\n";
}
echo '</p><p>Please try again.</p>';
} // End of if (empty($errors)) IF.
} // End of submit conditional.
// Always show the form...
// Retrieve the document's information:
$q = "SELECT * FROM docs WHERE doc_id=$id";
$r = mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) == 1) { // Valid document ID, show the form.
// Get the document's information:
$row = mysqli_fetch_array ($r, MYSQLI_NUM);
// Create the form:
echo '<form action="edit_doc.php" method="post">
<p>Document Name: <input type="text" name="doc_name" size="15" maxlength="15" value="' . $row[1] . '" /></p>
<textarea name="doc_content" id="doc_content" placeholder="Document Content" style="display: none;"></textarea>
<iframe name="editor" id="editor" ></iframe>'
?>
<div class="row">
<div class="col-group-1">
<?php
$q = "SELECT * FROM cats";
$r = mysqli_query ($dbc, $q); // Run the query.
echo '<div class="view_body">';
// FETCH AND PRINT ALL THE RECORDS
while ($row = mysqli_fetch_array($r)) {
echo '<br><label><input type="checkbox" name="cat_id[]" value="' . $row['cat_id'] . '">' . $row["cat_name"] . '</label>';
}
echo '</div>';
?>
</div>
</div>
<br><br>
<input onclick="formsubmit()" type="submit" value="Update Document" name="submit"/>
<?php echo'
<input type="hidden" name="id" value="' . $id . '" />
</form>
<br><br>Back to docs list';
} else { // Not a valid document ID.
echo '<p class="error">This page has been accessed in error.</p>';
}
?>
<?php
mysqli_close($dbc);
?>
So I have three tables:
docs
doc_id
doc_name
doc_content
cats
cat_id
cat_name
doc_cat_join
doc_id
cat_id
the join table related the doc_id and cat_id which then associates them together. I am guessing in my script when I update a doc it will need to delete the rows and then re-insert them? I just need to know a way or the easiest way of updating the join table as I am a tad stuck...
In case of checkbox update you need to delete previous stored checkbox of with appropriate id and insert new one you can't update checkbox as we can't predict how many checkbox will be selected by user....
Case:
It may happen that user remove one checkbox at update time so you will never know which one to be deleted.......
In your code...
docs
doc_id
doc_name
doc_content
cats
cat_id
cat_name
doc_cat_join
id
doc_id
cat_id
here you have to delete old checkbox of updation doc,
DELETE FROM doc_cat_join WHERE cat_id = some_id
next you can insert selected checkbox as you are inserting first time...
How do I insert to the database when you click a button?
I also need to insert in the same command, the row [id] and SESSION [id]
I use an html page that calls the php, then the variaves SESSION are not in my php page. I'm stuck here .. please help
<?php
session_start();
if(!isset($_SESSION["email"]) || !isset($_SESSION["senha"])) {
header("Location: login.php");
exit;
}
?>
<?php
$deets = $_POST['deets'];
$deets = preg_replace('#[^0-9/]#i', '', $deets);
include ("connect.php");
$events = '';
$query = mysql_query('SELECT hora, status FROM horario');
$num_rows = mysql_num_rows($query);
if($num_rows > 0) {
$events .= '<div id="eventsControl"><button class="btn2" style=" float:right;" onMouseDown="overlay()"><b>Fechar</b></button><p><b> ' . $deets . '</b></p></div> <br />';
while($row = mysql_fetch_array($query)) {
$desc = $row['hora'];
$desc1 = "<input type='submit' class='btn1' name='insert' value='Marcar Hora' />";
$events .= '<div id="eventsBody">' . $desc . ' | '.$desc1. '<br /><hr><br /></div>';
}
}
echo $events;
if(isset($_REQUEST['insert']))
{
$SQL = "INSERT INTO eventos (id, data, idhora,) VALUES ('', '.$deets.', '$row[id]', 'session[id]')";
$result = mysql_query($SQL);
}
?>
2 Problems I initially see, although I don't have full context of your code.
First, I don't see you starting the session anywhere, this requires you to run session_start(); before you try to grab the session ID or save any variables into the session.
Second, as far as I understand it you'll need to reference the session id by doing something like this.
$id = session_id();
How can I update a row in my mySql database from a HTML form. I have tried every technique and nothing seems to work. I would like that users could update their own profile page information.
I have a form on my page but the data doesn't get sent through.
What am i missing?
Here is my code:
------------INDEX.php
<?php
require_once("inc/database.php");
require_once("inc/query.php");
?>
<div class="wrapper">
<div class="content">
<h1>User Profiles</h1>
<?php
while ($row = $results->fetch()) {
$id = ($row["id"]);
$name = ($row["name"]);
$age = ($row["age"]);
$password = ($row["password"]);
print '<div ' . 'class= id-' . ($id) . '">';
print "<p>" . ($name) . "</p>";
print "<p>" . ($password) . "</p>";
print "<p>" . ($age) . "</p>";
print "</div>";
}
?>
</div>
</div>
<form action="inc/addnew.php" method="post">
<p>Name: <input type="text" name="name" required></p>
<p>ID: <input type="text" name="id" value="<?php echo $id; ?>"></p>
<p><input type="submit" value="Lisää"></p>
</form>
------------QUERY.php
<?php
try{
$results = $db->query("SELECT name, password, age, id FROM users");
$results->execute();
// echo "Our query ran successfully.";
} catch (Exception $e){
echo "Data could not be retrived from the database.";
exit;
}
------------DATABASE.php
<?php
try{
$db = new PDO('mysql:host=localhost;dbname=user_profile;port=8889', 'User_profile','bFeLcZjMmVw4PBaF');
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch (Exception $e){
echo "Could not connect to the database.";
exit;
}
------------UPDATE.php
<?php
require_once("database.php");
if( isset( $_POST['name'] ) && strlen( $_POST['id'] )){
$id = $_POST['id'];
$name = $_POST['name'];
$results=("UPDATE users SET name='$name' WHERE id=$id");
}
header("Location: ../index.php");
}
else
{
//error either $_POST['login'] is not set or $_POST['login'] is empty form field
echo 'Name or ID field was empty. Please fill out those fields. Back to site <br>';
}
How you expect this query to execute?
$results=("UPDATE users SET name='$name' WHERE id=$id");
you are just generating a query here on UPDATE.php without actually doing anything with it.
Replace this line with:
$results = $db->query("UPDATE users SET name='$name' WHERE id=$id");
You need to prepare and execute your query, not just define it as a string:
$sth = $db->prepare("UPDATE users SET name=:name WHERE id=:id")
$sth->execute(array("name" => $_POST["name"], "id" => $_POST["id"]));
You should be using placeholders to insert your data. Your query uses string interpolation which is extremely dangerous due to SQL injection bugs. Do not put $_POST data directly into a query, it's never safe.
Dear friends i am not an expert in php and need your help to solve an issue.
I am trying to create a page where i can call data from MySql and can edit/update it. The first part to display the data is done but i am unable to update it ... friends kindly help me solve this.
function Get_pages($mysql) {
$PageQuery = $mysql->query("SELECT * FROM pages WHERE PageID = '$pageID'");
while (($row = $PageQuery->fetch_assoc()) !== null)
{
echo '<form action="page.php" method="post">';
echo '<span class="lbl">Page Title</span>';
echo '<input name="PageTitle" type="text" value="' . $row["PageTitle"] . '" />';
echo '<span class="lbl">Page Content</span>';
echo '<textarea class="txt-area" name="PageContent" cols="" rows="18">' . $row["PageContent"] . '</textarea>';
echo '<input name="UpdateBtn" value="Update Page" type="submit" class="submit_btn"></form>';
}
// WHEN BUTTON CLICKED
if ($_REQUEST['UpdateBtn'])
{
$pageID = $_REQUEST["$pageID"];
$PageTitle = addslashes($_REQUEST['PageTitle']);
$PageContent = addslashes($_REQUEST['PageContent']);
$sql = mysql_query ("UPDATE pages SET PageTitle='$PageTitle', PageContent='$PageContent' WHERE pageID='$pageID'") or die ("Not Updating");
}
}
$sql = mysql_query ("UPDATE
should be
$sql = $mysql->query("UPDATE
You are making connection with mysqli_* function and using mysql_* function for update , because of that your UPDATE is failing.
http://localhost/?area=characters&name=Michal+Stroganof
$result = mysql_query("SELECT * from players WHERE name = '$_GET[name]'");
while ($row = mysql_fetch_assoc($result)) {
echo "Name: " .$row['name']. "<br>";
echo "Level: " .$row['level']. "<br>";
}
This is all code of my characters.php
If the get variable "name" is not included in the URL i want to show a search form that searches the table players. How would I do this?
Do you mean just to change your SQL string like so?
$sql = 'SELECT * from players';
if (isset($_GET['name'])) {
$safename = mysql_real_escape_string($_GET['name']);
$sql .= " WHERE name='$safename'";
}
$result = mysql_query($sql);
Be sure to sanitize your SQL!
Use isset():
if (isset($_GET['name'])) {
// your above code
} else {
// display form
}
Quick and dirty:
<?php
if (!isset($_GET['name']))
{
echo '<form action="'. $_SERVER['PHP_SELF'] .'" method="GET">'
.'<input type="text" name="name" />'
.'</form>';
}
else
{
// your current code that queries your database here
}
?>