updation of table through php mysql - php

This is my code to update a table. My problem is that after submitting a fresh record I'm unable to update the first time (it shows blank), but the second time it works fine.
One more thing: when I remove the include statement then it is working fine on submessage.php there is no any phpcode. [annakata: I have no idea what this means]
$pid = $_GET['id'];
$title = $_POST['title'];
$summary = $_POST['summary'];
$content = $_POST['content'];
$catid = $_POST['cid'];
$author = $_POST['author'];
$keyword = $_POST['keyword'];
$result1= mysql_query("update listing set catid='$catid',title='$title',
summary='$summary',content='$content', author='$author', keyword='$keyword' where pid='$pid'",$db);
include("submessage.php");

The things that are wrong with that piece of code are hard to enumerate. However, at the very least, you should establish a connection to the database before you can query it.

Why not just redirect to submessage.php rather than inlining it? Redirecting also prevents duplicate db operations when user refreshed the page. Just replace include statement with:
header('Location: submessage.php?id=' . $pid);
die();
Also, before you deploy your application: DO NOT EVER PUT USER INPUT DIRECTLY IN SQL QUERY. You should used bound parameters instead. Otherwise, you could just as well publicly advertise your database admin password. Read more on PDO and prepared statements at http://ie.php.net/pdo
Here's how I would do it:
$pdo = new PDO(....); // some configuration parameters needed
$sql = "
UPDATE listing SET
catid=:catid, title=:title, summary=:summary,
content=:content, author=:author, keyword=:keyword
WHERE pid=:pid
";
$stmt = $pdo->prepare($sql);
$stmt->bindValue('catid', $_POST['catid']);
$stmt->bindValue('title', $_POST['title']);
$stmt->bindValue('summary', $_POST['summary']);
$stmt->bindValue('content', $_POST['content']);
$stmt->bindValue('author', $_POST['author']);
$stmt->bindValue('keyword', $_POST['keyword']);
$stmt->bindValue('pid', $pid = $_GET['id']);
$stmt->execute();
header('Location: submessage.php?id=' . $pid);
die();
Or in fact, I would use some ORM solution to make it look more like that:
$listing = Listing::getById($pid = $_GET['id']);
$listing->populate($_POST);
$listing->save();
header('Location: submessage.php?id=' . $pid);
die();

Other than the usual warnings of SQL injection - very likely given your code and where you're obtaining the query parameters from (sans any kind of validation) - then it's quite possible your problem has nothing to do with the queries, particularly if it's working on subsequent attempts. Are you sure $_GET['id'] is set the first time you call the script?
Just to note, there is absolutely no reason to have to perform several update queries for each field you need to update - just combine them into a single query.

Related

PHP SQL query doesnt return a result

I have a button in a webapp that allows users to request a specially formatted number. When a user click this button 2 scripts run. The first that is fully functional, looks at a number table finds the largest number and increments it by 1. (This is not the Primary Key) the second script which is partially working gets the current date and runs a SQL query to get which period that date falls in. (Periods in this case not always equaling a full month) I know this script is at least partially working because I can access the $datetoday variable called in that script file. However it is not returning the requested data from the periods table. Anyone that could help me identify what I am doing wrong?
<?php
include 'dbh.inc.php';
$datetoday = date("Ymd");
$sql = "SELECT p_num FROM periods where '$datetoday' BETWEEN p_start AND p_end";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../quote.php?quotes=failed_to_write");
exit();
} else {
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
$pnum = $row;
mysqli_stmt_close($stmt);
}
If it helps any one I published my code to https://github.com/cwilson-vts/Quote-Appliction
So first off, I do not use msqli and never learned it. However, I believe I get the gist of what you want to do. I use PDO because I FEEL that it is easier to use, easier to read and it's also what I learned starting off. It's kinda like Apple vs. Samsung... no one product is exactly wrong or right. And each have their advantages and disadvantages. What I'm about to provide you will be in PDO form so I hope that you will be able to use this. And if you can't then no worries.
I want to first address one major thing that I saw and that is you interlacing variables directly into a mysql statement. This is not considered standard practice and is not safe due to sql injections. For reference, I would like you to read these sites:
http://php.net/manual/en/security.database.sql-injection.php
http://php.net/manual/en/pdo.prepared-statements.php
Next, I'm noticing you're using datetime as a variable name. I advise against this as this is reserved in most programming languages and can be tricky. So instead, I am going to change it something that won't be sensitive to it such as $now = "hello world data";
Also I'm not seeing where you would print the result? Or did you just not include that?
Another thing to consider: is your datetime variable the same format as what you are storing in your db? Because if not, you will return 0 results every time. Also make sure it is the right time zone too. Because that will really screw with you. And I will show you that in the code below too.
So now on to the actual code! I will be providing you with everything from the db connection code to the sql execution.
DB CONNECTION FILE:
<?php
$host = '127.0.0.1';
$user = 'root';
$pw = '';
$db = 'test'; // your db name here (replace 'test' with whatever your db name is)
try {
// this is the variable will call on later in the main file
$conn = new PDO("mysql:host=$host;dbname=$db;", $user, $pw);
} catch (PDOException $e) {
// kills the page and returns mysql error
die("Connection failed: " . $e->getMessage());
}
?>
The data file:
<?php
// calls on the db connection file
require 'dbconfig.php';
// set default date (can be whatever you need compared to your web server's timezone). For this example we will assume the web server is operating on EST.
date_default_timezone('US/Eastern');
$now = date("Ymd");
// check that the $now var is set
if(isset($now)) {
$query = $conn->prepare("SELECT p_num FROM periods WHERE p_start BETWEEN p_start AND :now AND p_end BETWEEN p_end AND :now");
$query->bindValue(':now', $now);
if($query->execute()) {
$data = $query->fetchAll(PDO::FETCH_ASSOC);
print_r($data); // checking that data is successfully being retrieved (only a troubleshooting method...you would remove this once you confirm it works)
} else {
// redirect as needed and print a user message
die("Something went wrong!");
}
$query->closeCursor();
}
?>
Another thing I want to mention is that make sure you follow due process with troubleshooting. If it's not working and I'm not getting any errors, I usually start at the querying level first. I check to make sure my query is executing properly. To do that, I go into my db and execute it manually. If that's working, then I want to check that I am actually receiving a value to the variable I'm declaring. As you can see, I check to make sure the $now variable is set. If it's not, that block of code won't even run. PHP can be rather tricky and finicky about this so make sure you check that. If you aren't sure what the variable is being set too, echo or print it with simply doing echo $now
If you have further questions please let me know. I hope this helps you!
I think I know what I was doing wrong, somebody with more PHP smarts than me will have to say for sure. In my above code I was using mysqli_stmt_store_result I believe that was clearing my variable before I intended. I changed that and reworked my query to be more simple.
<?php
include 'dbh.inc.php';
$datetoday = date("Ymd");
$sql = "SELECT p_num FROM periods WHERE p_start <= $datetoday order by p_num desc limit 1";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../quote.php?quotes=failed_to_write");
exit();
} else {
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while( $row = mysqli_fetch_assoc($result)) {
$pnum = $row['p_num'];
echo $pnum;
}
mysqli_stmt_close($stmt);
}
Thanks to #rhuntington and #nick for trying to help. Sorry I am such an idiot.

When adding fields to my database i get blank data

im trying to add data to my database but this code seems to just add blank data. Any solutions would be much appreciated. Thanks in advance.
<?php
session_start();
include 'dbh.php';
$start = $_POST['starttime'];
$finish = $_POST['finishtime'];
$dat = $_POST['date'];
$id = $_POST['userid'];
$sql = "INSERT INTO shift (shiftStart, shiftFinish, shiftDate)
VALUES ('$start', '$finish', '$dat')";
$result = mysqli_query($conn, $sql);
if ($result->affected_rows){
$row=$result->fetch_assoc();
echo'<pre>',print_r($row),'</pre>';
}else{
echo"didnt work";
}
//header("Location: index.php");
?>
$sql = "INSERT INTO shift (shiftStart, shiftFinish, shiftDate)
VALUES (".$start.", ".$finish.", ".$dat.")";
$result = mysqli_query($conn, $sql);
Try the above if any are string values you will need to add quotation marks around them single one ('".$start."').
First of all, use var_dump() to check all $_POST variables - do they have values?
If the method of your form is "get" you should use $_GET.
Step 2. After finding the (probably missing) variables please change you SQL query, otherwise you will have big risk of injection.
You should use prepared statements everywhere dealing with database. Check manual - http://php.net/manual/ru/mysqli.quickstart.prepared-statements.php .
And, by the way, you missing execute () function in your code.

Submit variable in URL to MySQL Database

I would like to have a page that, when someone clicks a pre-formatted link I've sent, writes a variable in the URL to a MySQL database and just displays "Thank You" or something to the user.
Example:
The user would click a link formatted something like http://www.example.com/click.php?id=12345
When the page loads the 12345 would be written to a table in a MySQL database, it would show a Thank you, and that is it.
Seems like it should be simple enough but I can't find anything on it. I'm probably searching wrong, since this is all new to me.
Your best bet is to utilise $_GET['id'] which will take in the value from your url.
After grabbing the id from your url you will want to use PDO or mysqli prepared statements in order to protect yourself from sql injection.
I hope this helps.
Updated as per Kevin Voorn's comment.
if(isset($_GET['id']) && !empty($_GET['id'])) {
$logged_id = $_GET['id'];
$stmt = $mysqli->prepare("INSERT INTO tableName (`logged_id`) VALUES (?)");
$stmt->bind_param('i', $logged_id);
$stmt->execute();
if($stmt->affected_rows > 0){
echo "Thank You.";
}
$stmt->close();
}
User $_GET to retrive the value and put into your table.
Example:
code inside click.php
<?php
$id=$_GET['id'];
$sql="Insert into table1 VALUES ($id)";
mysqli_query($connect,$sql);
echo "<script>alert('Thank you')</script>";
?>
Thanks for the responses. I ended up finding this page: https://www.binpress.com/tutorial/using-php-with-mysql-the-right-way/17 that described the process for using mysqli to connect to my database. I used that page to create the necessary functions in ../db.php and included it in the actual PHP script that would catch the url. My script ended up looking like this:
<?php
require '../db.php';
date_default_timezone_set('UTC');
$date = date("Y-m-d H:i:s T");
$db = new Db();
$db_id = $db -> quote($_GET['id']);
$db_date = $db -> quote($date);
$result = $db -> query("INSERT INTO `table` (`id`,`GUID`,`AccessTime`) VALUES (NULL, " . $db_id . "," . $db_date . ")");
if($result === false) {
exit();
} else {
echo "<html><body><center><br><h1>Thank You!</h1></center></body></html>";
}
?>

SQL database not inserting data?

I am working on a program that takes HTML code made by a WYSIWYG editor and inserting it into a database, then redirecting the user to the completed page, which reads the code off the database. I can manually enter code in phpmyadmin and it works but in PHP code it will not overwrite the entry in the code column for the ID specified. I have provided the PHP code to help you help me. The PHP is not giving me any parse errors. What is incorrect with the following code?
<?php
//POST VARIABLES------------------------------------------------------------------------
//$rawcode = $_POST[ 'editor1' ];
//$code = mysqli_real_escape_string($rawcode);
$code = 'GOOD';
$id = "1";
echo "$code";
//SQL VARIABLES-------------------------------------------------------------------------
$database = mysqli_connect("localhost" , "root" , "password" , "database");
//INSERT QUERY DATA HERE----------------------------------------------------------------
$queryw = "INSERT INTO users (code) VALUES('$code') WHERE ID = '" . $id . "'";
mysqli_query($queryw, $database);
//REDIRECT TO LOGIN PAGE----------------------------------------------------------------
echo "<script type='text/javascript'>\n";
echo "window.location = 'http://url.com/users/" . $id . "/default.htm';\n";
echo "</script>";
?>
Your problem is that mysql INSERT does not support WHERE. Change the query to:
INSERT INTO users (code) VALUES ('$code')
Then to update a record, use
UPDATE users SET code = '$code' WHERE id = $id
Of course, properly prepare the statements.
Additionally, mysqli_query requires the first parameter to be the connection and second to be the string. You have it reversed. See here:
http://php.net/manual/en/mysqli.query.php
It should also be noted that this kind of procedure should be run before the output to the browser. If so, you can just use PHP's header to relocate instead of this js workaround. However, this method will still work as you want. It is just likely to be considered cleaner if queries and relocation is done at the beginning of the script.

Edit mysql database from "GET" index.php?id=XX

I'm currently learning PHP. I've code a simple bucketlist script with a admin panel, sessions etc just to see if I can do it.
The last page I am coding is the "edit.php" & "editone.php" I have a table which returns all data within the database "ID, Goal & Rating" my fourth column returns "EDIT" as a link which will link off to: editone.php?id=xx
editone.php currently is not a page. For the life of me I cannot figure out how I code the editone so I can grab the data and UPDATE mysql. I'm almost there just cannot piece together the puzzle.
Here's the core of my code for the edit page.
<?php
while ($query_row = mysql_fetch_array($query))
{
echo "<tr>";
echo "<td>".$query_row['id']."</td><td>". $query_row['goals']."</td><td><span class='label label-inverse'>". $query_row['rating']."</span></td><td><a href='editone.php?id=".$query_row['id']."'>Edit</a></td>";
echo "<tr>";
}
?>
Any assistance would be really appreciated.
Send all the parameters through POST method to editone page. I mean in your edit page, you are getting all the variables from database. You can show them in a form having a submit button and of type "POST". So now when someone submits, it goes to editone.php page.
Get all the variables first through $_POST method. Then write a update query.
$sql = "UPDATE tablename SET goals = '$goal', rating='$rating' WHERE id = $id";
make sure to escape your post variables as said in the comment.
This is how should be your PDO Update statement.
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$goals = 'Some goals';
$rating = 'whatever rating';
$id = 3;
// query
$sql = "UPDATE tablename
SET goals=?, rating=?
WHERE id=?";
$q = $conn->prepare($sql);
$q->execute(array($goals,$rating,$id));
If I understood you correctly, what you want is a page that first displays a single row (so it can be edited) and then saves it once you're done. So you start out by writing the HTML form with no data in it.
Next, you read the ID from the query string:
<?php
$rowId = $_GET['id'];
and then query for the data:
// database connection example borrowed from Abhishek
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$sql = "SELECT goals, rating FROM tablename WHERE id = ?";
$query = $conn->prepare($sql);
$query->execute(array($rowId));
$row = $query->fetch();
Now, you can use the data to populate your form. This gets you about halfway there. :-)
You'll want the actual save to be in response to a POST request, not GET. There's a long and somewhat complicated explanation on why that is, but the simplified version is that you use POST whenever you're making changes for the user, and GET when you're just reading data -- there's a bunch of browser and proxy behavior and whatnot tied to these assumptions, so it's a good idea to start doing things the right way early on.
When you process the POST request -- you can do it on the same page -- you'll have the updated form values for grabs, and you can use them to update your database:
// This can be a hidden field on the form...
$rowId = $_POST['id'];
$goals = $_POST['goals'];
$rating = $_POST['rating'];
// database connection example borrowed from Abhishek
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$sql = "UPDATE tablename SET goals = ?, rating = ? WHERE id = ?";
$query = $conn->prepare($sql);
$query->execute(array($goals, $rating, $rowId));
After this, your database should be updated. To finish things off, you'll probably want to redirect back to the page to make sure the form can't be double-submitted accidentally.
I haven't covered quite everything here, a bit on purpose. It's more fun when there are some blanks to fill in. :-)
You probably want your second <tr> to be </tr>.
The most common solution is to use an html form. The input values of this form are a select with the id in query string. When a submit button is pressed to save this, make a update. But I want share with you a good and complete web 2.0 example.

Categories