Selected text from database does not update - php

I'm trying to update text I've selected and displayed in a TextArea to my database. The text is selected and displayed so nothing wrong with the connection.php. But when I change the text and press save it does not update the text in the database, however it shows that the data is stored in the variables $tekstArea and $tekstIDArea. Could anyone help me out?
Here is my code:
<?php
session_start();
include "connection.php";
?>
<?php
//Get Resulsts from database
$query = "SELECT * FROM tekst";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($result)) {
$tekstID = $row['tekstID'];
$text = $row['text'];
echo "<form method='POST' action=''>
<input name='tekstIDArea' value=" . $tekstID . ">
<br />
<textarea name='textArea' rows='20'>" . $text . "</textarea>
<br />
<button type='submit' name='submit' class='btn'>Save</button><br /><br />";
}
if (isset($_POST['submit'])) {
$tekstArea = $_POST['textArea'];
$tekstIDArea = $_POST['tekstIDArea'];
$sql = "UPDATE tekst SET 'text' = '$tekstArea'";
$res = mysqli_query($conn, $sql);
if(!$res)
{
echo "Could not update" . mysql_error() . "<br />";
echo $tekstArea . "<br />";
echo $tekstIDArea . "<br />";
}
mysqli_close($conn);
}
?>
Thanks in advance,
Ahnkheg
EDIT: Added form closing tag.
Changed mysql_error() to mysqli_error($conn).

"Okay, that fixed my error output! Thank you! The error I'm getting is: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''text' = 'test'' at line 1. – Ahnkheg"
This line:
$sql = "UPDATE tekst SET 'text' = '$tekstArea'";
The text column has regular quotes and isn't the correct identifiers. This is a column and not a value.
Either use ticks:
$sql = "UPDATE tekst SET `text` = '$tekstArea'";
or remove them:
$sql = "UPDATE tekst SET text = '$tekstArea'";
Sidenote: Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
You also have a missing </form> tag. That will have adverse effects. You're also mixing with mysql_error(). That should be mysqli_error($conn).
Those different MySQL APIs do not intermix with each other.

Related

PHP script displaying a blank page

This is my script and it's displaying a blank, I have no idea what the problem is. HELP!!!! #new to PHP
<?php include "connection.php";
// Get the ID from URL.
if(isset($_GET['id']));
$id = $_GET['id'];
$query="SELECT * FROM module WHERE id= '$id'";
$result= mysqli_query($m, $query);
while ($row = mysqli_fetch_array($result)){
$title=$row['title'];
$level=$row['level'];
$credits=$row['credits'];
$school=$row['school'];
echo $title. " " . $level. " " . $credits. "<br />";
}
?>
Error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE id= 'Careers'' at line 1
One obvious problem here is that you've included an "end of statement" character being a semi-colon.
The semi-colon (if that isn't a typo), is doing just that, "ending" the statement.
if(isset($_GET['id']));
^ right there.
It should be a brace { for it instead and to read as:
if(isset($_GET['id'])){
and there should be a closing brace } for that conditional statement for it.
Sidenote: The semi-colon is considered a valid character in PHP, which won't throw you an error for it, should the GET array have a value.
However, you should check for errors for the rest of your code.
Add error reporting to the top of your file(s) right after your opening PHP tag
for example <?php error_reporting(E_ALL); ini_set('display_errors', 1); then the rest of your code, to see if it yields anything,
as well as or die(mysqli_error($m)) to mysqli_query().
While making sure you are indeed using the MySQLi_ API to connect with (different MySQL APIs do not intermix) and that the GET array has a value.
Here's a rewrite, and assuming a successful DB connection using the MySQLi_ API for it.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_GET['id'])){
$id = $_GET['id'];
} else{
echo "ID is not set. You need to investigate it.";
exit; // This will stop your script, dead in its tracks.
}
$query="SELECT * FROM module WHERE id= '$id'";
$result= mysqli_query($m, $query) or die(mysqli_error($m));
while ($row = mysqli_fetch_array($result)){
$title=$row['title'];
$level=$row['level'];
$credits=$row['credits'];
$school=$row['school'];
echo $title. " " . $level. " " . $credits. "<br />";
}
References:
http://php.net/manual/en/function.mysqli-connect.php
http://php.net/manual/en/mysqli.error.php
Edit:
Taken from comments:
"this is my query, $query="SELECT id, title module WHERE id= '$id'"; – user5579012 38 mins ago"
Link to that comment...
That isn't what was posted in your original question.
You posted SELECT * FROM module WHERE id= '$id'.
You have a syntax error here, being a missing comma after title.
It should read as:
$query="SELECT id, title, module WHERE id= '$id'";
All columns need to be seperated by commas but not the last one being module here.
Ensure everything is ok. Echo errors if possible.
<?php include "connection.php";
// Get the ID from URL.
if(isset($_GET['id'])){
$id = $_GET['id'];
$query="SELECT * FROM module WHERE id= '$id'";
$result= mysqli_query($m, $query);
if($result){ //query is ok
if(mysqli_num_rows($result) > 0){//check if a record exists
while ($row = mysqli_fetch_array($result)){
$title=$row['title'];
$level=$row['level'];
$credits=$row['credits'];
$school=$row['school'];
echo $title. " " . $level. " " . $credits. "<br />";
}
}else{ //no result found
echo "no results found!";
}
}else{ //some error in querying
echo mysqli_error($m);
}
}
?>

Use POST method to display data from database PHP

I am using this SQL query in a link to retrieve data from database
<div class="nav-laptop">Laptop
and display it using
$sql = $_REQUEST['upit'];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<div class='proizvodi'>";
// output data of each row
$result->data_seek(0);
while($row = $result->fetch_assoc()) {
echo "<div class='row'>";
foreach($row as $key => $value){
echo "<div class='" . $key . "'>" . $value . "</div>";
}
echo "</div>";
echo "<hr />";
}
echo "</div>";
}
else {
echo "<div class='search-query-none'><img src='index/no result.png' width='754' height='198' /></div>";
}
I realized this is very vulnerable and that I should use POST method to hide parameters from URL. I tried reading online forums, but I found nothing that would help me to convert this to POST way of retrieving data.
So, how do I use POST method to achieve the same result as I am achieving right now using GET?
This will give you a general idea on how to do this.
HTML form:
<form method="post" action="your_handler.php">
<input type = "text" name = "search_query">
<input type = "submit" name = "submit" value = "Search">
</form>
SQL/PHP and assuming a successful connection using the MySQLi API.
$conn = mysqli_connect("your_host", "user", "password", "db");
if (!$conn) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
if(isset($_POST['submit'])){
if(!empty($_POST['search_query'])){
$search_query = mysqli_real_escape_string($conn, $_POST['search_query']);
$result = mysqli_query($conn, "SELECT * FROM TABLE WHERE col = '$search_query' ");
if(!$result) { echo "Error: " . mysqli_error($conn); }
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// perform what you want here
// and check for errors on your query
}
}
}
}
You can substitute SELECT * with the said columns also.
Ideally, a prepared statement is nice to work with.
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/pdo.prepared-statements (if you want to look into PDO).
Sidenote: Do not intermix different MySQL APIs such as mysqli_ with PDO. They just don't mix together.
Check for errors also against your query:
http://php.net/manual/en/mysqli.error.php
Add or die(mysqli_error($conn)) to mysqli_query().
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Plus, make sure that no whitespace gets introduced into your input, otherwise your query may fail.
Use trim() against the input.
You don't need to use POST for a SELECT query. You can, but it's really better suited for INSERT / UPDATE / DELETE, things that actually change your data. A possible advantage to using a link like that for search results is that it can be saved, bookmarked, emailed, etc., where a form submission cannot. But you are right that putting your entire query into a link like that definitely is extremely vulnerable.
Instead of passing the entire query through the link, you can just pass the parameters, like this:
Laptop
Then in your display code you can use a prepared statement and safely bind the parameter:
$kategorija = $_GET['kategorija'];
$sql = 'SELECT Slika, Naziv, Opis, Cijena FROM Proizvodi
WHERE Kategorija=? ORDER BY Proizvodac';
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $kategorija);
$stmt->execute();
// etc.

Displaying MySQL query in html select

I am still a beginner with php and MySQL. I am having trouble getting rows from my database to display in an html select drop down box. I have researched it and it seems like my code should be good. The campaigns table as a row titled name. This is the row I am wanting to echo into the drop down. The drop down shows, however there is no content in it. Not sure what I am missing here...
Here is the code
<?php
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = mysqli_query($con,"SELECT * FROM campaigns");
echo '<select name="campaignChange">';
while ($row = mysql_fetch_array($query)) {
echo "<option value='" . $row['name'] ."'>" . $row['name'] ."</option>";
}
echo '</select>';
?>
You are mixing mysql and mysqli syntax.
You should change:
$query = mysql_query($con,"SELECT * FROM campaigns");
to:
$query = mysqli_query($con,"SELECT * FROM campaigns");
and:
while ($row = mysql_fetch_array($query)) {
to:
while ($row = mysqli_fetch_array($query)) {
By the way, you should add error handling. If you add this to the top:
mysqli_report(MYSQLI_REPORT_ALL);
mysqli will throw exceptions so you will always know what goes wrong exactly. As long as you use mysqli functions of course...

mysqli dynamic generated table with link that opens form with all values from row

I have this table:(megaoverzicht.php) (I left out the part where it connects to the db)
echo "<table border='1'><tr><th>Formulier Id</th><th>Domeinnaam</th><th>Bedrijfsnaam</th><th>Datum</th><th>Periode</th><th>Subtotaal</th><th>Dealernaam</th><th>Offerte Maken</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['formuliernummer'] . "</td>";
echo "<td>" . $row['domeinnaam'] . "</td>";
echo "<td>" . $row['bedrijfsnaam'] . "</td>";
echo "<td>" . $row['datum'] . "</td>";
echo "<td>" . $row['periode'] . "</td>";
echo "<td> € " . $row['subtotaal'] . "</td>";
echo "<td>" . $row['dealercontactpersoon'] . "</td>";
echo "<td><a href='offertemaken.php?id=" . $row->id . "'>Offerte Maken </a></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
I want to open offertemaken.php when the user clicks on Offerte Maken. It needs to open the form with the data from that row(id).
This is the code from (offertemaken.php)(I left out the part where it connects to the db)
<?php
$id=$_POST['id'];
$data = 'SELECT * FROM cypg8_overzicht WHERE id="$id"';
$query = mysqli_query($con,$data) or die("Couldn't execute query. ". mysqli_error());
$data2 = mysqli_fetch_array($query);
?>
<form>
<div class="formcontainer" onmousemove="">
<input type="text" name="datum" id="datum" value="<?php echo $data2[datum]?>">
<input type="text" name="formuliernummer" id="formuliernummer" value="<?php echo $data2[formuliernummer]?>">
<input type="text" name="periode" id="periode" value="<?php echo $data2[periode]?>">
<input type="text" name="domeinnaam" id="domeinnaam" value="<?php echo $data2[domeinnaam]?>">
<input type="text" name="bedrijfsnaam" id="bedrijfsnaam" value="<?php echo $data2[bedrijfsnaam]?>">
<input type="text" name="dealercontactpersoon" id="dealercontactpersoon" value="<?php echo $data2[dealercontactpersoon]?>">
</div><!--/.formcontainer-->
</form>
I cant get it to work. I am missing something I think! I make an error in the codes below:
echo "<td><a href='offertemaken.php?id=" . $row->id . "'>Offerte Maken </a></td>";
$id=$_POST['id'];
$data = 'SELECT * FROM cypg8_overzicht WHERE id="$id"';
I have been looking at a lot of tutorials but cant understand what i am doing wrong. Here a list to show that i am not just asking but actually have been looking for a solution by myself.
http://www.daniweb.com/web-development/php/threads/341921/-php-mysqli-update-database-using-id-syntax-help-requested-
http://www.codeofaninja.com/2012/01/phpmysqli-update-record.html
I have looked at many more but i don’t want to bother all of you with an extreme long list of links. And i am not allowed because my rep is not big enough! Dont downvote me please!
Question
I want to open offertemaken.php when the user clicks on Offerte Maken. It needs to open the form with the data from that row(id)?
Edit 1 Getting closer to the endresult
I found out(thanks to Cuba32) that the link in megaoverzicht.php was doing nothing so i changed the following
<a href='offertemaken.php?id=" . $row->id . "'>
to
<a href='offertemaken.php?id=" . $row['id'] . "'>
Now it is creating these kind of links:
something/formulieren/overzichten/offertemaken.php?id=24
This is a good thing(i think) but the form that opens is blank so offertemaken.php is doing nothing with the id???
Edit 2 (Thanks to Cube32)
Since yesterday the code has changed quite a bit. I belive that megaoverzicht.php is finished it sends the link as described in edit 1. The only problem is know in offertemaken.php. Below i will put in the code.
$con = mysqli_connect($server,$username,$password,$database);
if (!$con){
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,$database);
$id=$_GET['id'];
if($data = mysqli_prepare($con, 'SELECT * FROM cypg8_overzicht WHERE id="?"'))
{
/* bind parameters for markers */
mysqli_stmt_bind_param($data, "s", $id);
/* execute query */
mysqli_stmt_execute($data);
$data2 = mysqli_stmt_fetch($data);
But this code gives me the following error.
Warning: mysqli_stmt_bind_param(): Number of variables doesn't match number of parameters in prepared statement in line 31. Line 31:
mysqli_stmt_bind_param($data, "s", $id);
I dont know how to solve this part. I will offcourse be looking on the internet to try and find a solution but if anyone knows it please post it. Thanks in advance.
Edit 3<= No more error (Thanks to Your Common Sense)
by changing WHERE id="?"' into WHERE id=?' i no longer have the error. But still it is not showing anything in the input fields
Edit 4<= Getting to confused and going back to original code.
Thanks for everyone who got me so far. But I can't see the forest anymore through the trees. I am going back to the original code and try to solve that. So the code is now as follows:
$id=$_GET['id'];
$data = 'SELECT * FROM cypg8_overzicht WHERE id="$id"';
$query = mysqli_query($con,$data) or die("Couldn't execute query. ". mysqli_error());
$data2 = mysqli_fetch_array($query);
error_reporting(E_ALL);
But this gives the following errors inside the input fields:
Notice: Use of undefined constant formuliernummer - assumed 'formuliernummer' in offertemaken.php on line 37
This error goes for all the input fields.
Edit 5
Fixed this by changing <?php echo $data2[formuliernummer]?> to <?php echo $data2['formuliernummer']?> but it is still not showing the information.
Edit 6 THE SOLUTION
I added the answer to the question below. Just look for answer written by HennySmafter.
Thanks to:
Cube32, SITDGNymall, Your Common Sense. Thanks all of you for helping me find the solution.
It took me a while but i found the answer.
megaoverzicht.php
echo "<td><a href='offertemaken.php?id=" . $row['id'] . "'>Offerte Maken </a></td>";
offertemaken.php
// Check whether the value for id is transmitted
if (isset($_GET['id'])) {
// Put the value in a separate variable
$id = $_GET['id'];
// Query the database for the details of the chosen id
$result = mysqli_query($con,"SELECT * FROM cypg8_overzicht WHERE id = $id");
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = "Invalid query: " . mysqli_error($result) . "\n";
$message .= "Whole query: " . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(),etc.
while ($row = mysqli_fetch_assoc($result)) {
echo $row['formuliernummer'] . "\n";
echo $row['domeinnaam'] . "\n";
echo $row['bedrijfsnaam'] . "\n";
echo $row['datum'] . "\n";
echo $row['periode'] . "\n";
}
} else {
die("No valid id specified!");
}
It is not showing the values in the input boxes because there are no input boxes into the echo but those can be easily added I imagine.
In reference to the edit 1:
You are referencing the variables by association, but are outputing the mysql as a default array. instead of
$data2 = mysqli_fetch_array($query);
Try this:
$data2 = mysqli_fetch_assoc($query);
Or:
$data2 = mysqli_fetch_array($query, MYSQLI_ASSOC);
Also, do you have error reporting turned on? If so, then if the array contains no data you should be getting warnings of some kind. If not, a good test is:
error_reporting(E_ALL);
This will warn you about any places where a variable is unset or a array is empty. Another good test is to simply echo out your query, which will tell you if there's any errors in the query itself(which can save some time). If you're not going to go the Prepared Statements route(which is highly encouraged), you can simply echo out $data into your script.

Error in PHP with Mysql

Im starting to learn PHP. When I run the script it had an error that said: "Assigned Employee:resource(6) of type (mysql result)" . Please help me and sorry for my bad English Here is the code:
include_once 'rnheader.php';
include_once 'rnfunctions.php';
</tr><tr><td><label for="AssignedEmp"> Assigned Employee:</label></td><td>';
$query = "SELECT UserName FROM employee where Classification_ClassificationID = '2'";
$result = queryMysql($query);
if (!queryMysql($query)) {
echo "Query fail: $query<br />" .
mysql_error() . "<br /><br />";
}
else
{
var_dump($result);
exit;
<select name = "UserName", "Name" size = "1">'; // or name="toinsert[]"
while ($row = mysqli_fetch_array($result)) {
'<option value="' . htmlspecialchars($row['UserName']) . '" >'
. htmlspecialchars($row['UserName'])
. '</option>';
}
}
'</select>';
?>
I isn't error. That output is produced by this line:
var_dump($result);
exit;
Since you are dumping the result of a query directly it is dumping a resource object and then you are immediately exiting the application. See after a query, you get data in a resource object, which is why we use the while loop that you have later. Remove the
exit;
And see what you get after you see
resource(6) of type (mysql result)
What is the queryMysql function that you have build? Can we see that?
Also, you have quotes here:
Classification_ClassificationID = '2'
Quotes are for strings, varchars, blobs, etc. An ID is typically an integer. Is your Classification_ClassificationID a varchar in your database or an integer. If it is an integer, take out the single quotes.

Categories