So as the title suggests, I am having trouble executing a MySQL query. The query works almost successfully, as all data fields are stored into my database except for one. The query itself is a commenting system for signed in users to comment on any given blog post. The issue I am having is that the variable '$post_id' is not recognized, and therefore '$comment_post_ID' is not stored in my database.
'$post_id' is defined in blogs.php, and after echoing this variable it does exist and is successfully defined. However, this variable is not passed onto commentsubmit.php, which is included in the same file where the variable is defined. Why is this happening?
Here are all the pieces of my code:
blogs.php (shows all posts from all users, or just one post if ?id is set in the url. If ?id is set, users can comment on the single post they are viewing.)
<?php
if (isset($_GET['id'])) {
$conn = mysqli_connect("localhost", "root", "mypassword", "mydbname");
if (mysqli_connect_errno($conn)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
$post_id = mysqli_real_escape_string($conn, $_GET['id']);
$blog_post = "SELECT * FROM blogs WHERE id = '$post_id'";
$blog_query = mysqli_query($conn, $blog_post);
while ($row = mysqli_fetch_array($blog_query)) {
$title = $row['title'];
$body = $row['body'];
$author = $row['author'];
$author_username = $row['author_username'];
$datetime = time_ago($row['datetime'], $granularity=2);
}
include ("./fullpageblog.php");
if (isset($_SESSION['id'])) {
include ("./blogcomment.php");
include ("./commentsubmit.php");
}
echo "$post_id";
mysqli_close($conn);
}
?>
blogcomment.php (form for users to make a comment)
<div class="row col-sm-12">
<div id="fullPageBlog">
<div id="center-border"></div>
<form action="commentsubmit.php" method="post">
<textarea maxlength="1000" id="blogComment" name="content" placeholder="Write your response..."></textarea>
<input type="submit" name="comment" value="Publish" />
</form>
<script type="text/javascript">$('#blogPost').elastic();</script>
</div>
</div>
commentsubmit.php (comment query itself)
<?php
session_start();
if (isset($_POST['comment'])) {
$conn = mysqli_connect("localhost", "root", "mypassword", "mydbname");
if (mysqli_connect_errno($conn)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
$comment_post_ID = $post_id;
$comment_author = $_SESSION['full_name'];
$comment_author_email = $_SESSION['email'];
$comment_author_username = $_SESSION['username'];
$comment_date = date("Y-m-d H:i:s");
$comment_content = mysqli_real_escape_string($conn, $_POST['content']);
$user_ID = $_SESSION['id'];
$comment_submit = "INSERT INTO comments (comment_ID, comment_post_ID, comment_author, comment_author_email, comment_author_username, comment_date, comment_content, user_ID) VALUES ('', '$comment_post_ID', '$comment_author', '$comment_author_email', '$comment_author_username', '$comment_date', '$comment_content', '$user_ID') ";
$comment_query = mysqli_query($conn, $comment_submit);
mysqli_close($conn);
header("Location: blogs.php");
die();
}
?>
You don't include/require the blogs.php script from the commentsubmit.php script, so the code in blogs.php would never be run after a POST that is made directly to commentsubmit.php unless you have some other request processing (i.e. a server-side rewrite or similar) that happens automatically on the server before the request ultimately reaches the portion of code shown in commentsubmit.php above.
<?php
$con = mysql_connect("localhost","root","password");
$con=mysql_select_db("database_name");
error_reporting(0);
session_start();
if(isset($_POST["submit"])){
$comment_author = $_POST['full_name'];
$comment_author_email = $_POST['email'];
$comment_author_username = $_POST['username'];
$sql="select * from table_name where `full_name`='"$comment_author "',`email`='"$comment_author_email "',`username`='"$comment_author_username "'";
$qur=mysql_query($sql);
$row= mysql_fetch_array($qur);
$num= mysql_num_rows($qur);
}
if($num>0){
$_SESSION["full_name"]=$full_name;
$_SESSION["email"]=$comment_author_email;
$_SESSION["username"]=$comment_author_username;
}
else{
echo"Username and Password are wrong";
}
?>
Related
I have a form handler (I believe that is the correct terminology) called insert.php, this is used to post form data to a MySQL database on localhost. I have different tables each containing a single record and would like to choose which table the data goes to. I could duplicate the insert.php file for each table but that seems messy. How do I choose which table the data goes to via post?
current insert.php:
<?php
require_once 'login.php';
$con=mysqli_connect($hh,$un,$pw,$db);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo 'Connected successfully';
$sql = "UPDATE PiBQ_Temp SET reqdTemp = '$_POST[setTemp]' WHERE tempKey = 1";
mysqli_query($con,$sql);
echo "1 record added";
header ('location: index.php');
mysql_close($con)
?>
What I think is needed for the $sql = variable:
$sql = "UPDATE '$_POST[myTable]' SET '$_POST[myField]' = '$_POST[myValue]' WHERE tableKey = 1"
My html is this:
<form action="insert.php" method="post">
<input type="text" name="myField" value="<?= $myValue ?>"/>
<input type="submit" value="Submit" />
what html should I be using to feed my revised insert.php file above, if that is correct? Thanks.
try this format
$sql = "UPDATE `".$_POST['myTable']."` SET `".$_POST['myField']."` = '".$_POST['myValue']."' WHERE `tableKey` = 1";
or
$mysqli = new mysqli("host", "user", "password", "db");
$stmt = $mysqli->prepare("UPDATE `".$mysqli->real_escape_string(str_replace(" ", "", strtolower($_POST['myTable'])))."` SET `".$mysqli->real_escape_string(str_replace(" ", "", strtolower($_POST['myField'])))."` = ? WHERE `tableKey` = 1");
$stmt->bind_param("s",$_POST['myValue']);
$stmt->execute();
You should use prepared statement instead
There's some wider practices that could be improve, but based on your current code/structure, I would use something like this:
<?php
require_once 'login.php';
try {
$con = new mysqli("host", "user", "password", "db");
} catch (mysqli_sql_exception $e) {
echo "Failed to connect to MySQL: ".$e;
}
$table = (isset($_POST['myTable'])) ? $_POST['myTable'] : null;
$reqdTemp = (isset($_POST['setTemp'])) ? $_POST['setTemp'] : null;
$tempKey = (isset($_POST['setKey'])) ? $_POST['setKey'] : null;
switch($table) {
case "thisTable":
$qry = "UPDATE `thisTable` SET thisField = ? WHERE thisKey = ?";
break;
case "thatTable":
$qry = "UPDATE `thatTable` SET thisField = ? WHERE thisKey = ?";
break;
case "anotherTable":
$qry = "UPDATE `anotherTable` SET thisField = ? WHERE thisKey = ?";
break;
default:
// do something?
break;
}
$stmt = $conn->prepare($qry);
$stmt->bind_param("si", $reqdTemp, $tempKey);
$stmt->execute();
if(!$stmt->execute()) {
echo $stmt->error;
}
else {
echo "1 record added";
}
header ('location: index.php');
mysql_close($con)
?>
Two things to note: The switch statement allows you to provide a different query based on the table name, but it assumes that the same structure is in place (i.e. update String Where Integer).
I've also assumed the thisKey is posted too, as 'setKey'.
Secondly, prepared statements.
This is more of a hint, rather than a whole solution, and you probably need to tidy it up and make it work for you outside of my assumptions
This question already has answers here:
What is the difference between single-quoted and double-quoted strings in PHP?
(7 answers)
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 5 years ago.
During a test to see if my database would receive a username through a form field , the code would not work unless I echo'd out error messages. Why is this? My goal is to send the username through the form field , and retrieve the list of usernames on the same page below the form field.
My html for submitting usernames ,
<section id="banner">
<div class="content">
<header>
<h2>Add Usernames Here</h2>
<form method="post">
<br><input type="text" name="user_name"><br>
<input type="submit" value="Submit">
</form>
</header>
</div>
For displaying usernames:
<section id="five" class="wrapper style2 special fade">
<div class="container">
<header>
<h2>Added Usernames</h2>
<?php require 'post.php'; ?>
</header>
</div>
</section>
And my post.php code
<?php
//connection
$url = parse_url(getenv("CLEARDB_DATABASE_URL"));
$server = $url["host"];
$username = $url["user"];
$password = $url["pass"];
$db = substr($url["path"], 1);
$conn = new mysqli($server, $username, $password, $db);
//test connection
if(!$conn)
{
echo 'not connected';
}
if(!mysqli_select_db($conn,'heroku_cd6b3866e127c21'))
{
echo 'database not selected';
}
//insert username
$user_name = $_POST['user_name'];
$sql = "INSERT INTO store (user_name) VALUES ('$user_name')";
//test query
if(!mysqli_query($conn,$sql))
{
echo 'not inserted';
}
else {
echo 'inserted';
}
//echo all usernames
mysqli_select_db($db,$conn);
$sql2 = "SELECT * FROM store";
$mydata = mysqli_query('$sql2,$conn');
while($record = mysqli_fetch_array($mydata)){
echo "<br>";
echo $record['user_name'];
}
?>
This code works until I remove the if statements , checking for the connection.
This is simple example, only one page named index.php:
<form action="index.php" method="post">
<br><input type="text" name="user_name">
<br><input type="submit" value="Submit">
</form>
<?php
$username = $_POST["user_name"];
$link = mysqli_connect("127.0.0.1", "root", "", "db12");
mysqli_query($link, "INSERT INTO users (username) values ('$username')");
echo $username;
$query = "SELECT username FROM users";
$result = mysqli_query($link, $query);
/* fetch associative array */
while ($row = mysqli_fetch_array($result)) {
echo $row['username'] . "<br>";
}
/* close connection */
mysqli_close($link);
?>
In production app always write separate page for insert, and always use prepare http://php.net/manual/en/mysqli.prepare.php
You aren't running the query anywhere else except in those if statements.
Try adding $mysqli->query($sql) underneath your declaration of $sql
You still need to call these functions:
mysqli_select_db($conn,'heroku_cd6b3866e127c21')
and
mysqli_query($conn,$sql)
Even if they are wrapped in an if statement or not you still need to select the db and send it a query. But I wouldn't want to do it like this, I would look into PDO.
http://php.net/manual/en/book.pdo.php
These methods are known for having SQLi vulnerabilities.
Edit
Also this line has an error:
$mydata = mysqli_query('$sql2,$conn');
I assume it should be:
$mydata = mysqli_query($conn,$sql2);
what is the best way to direct the user to another page given the IF statement is true. i want the page to direct the user to another page using PHP, when the IF statement is run, i tired this but it doesn't work??
if ( mysqli_num_rows ( $result ) > 0 )
{
header('Location: exist.php');
die();
}
Below is the full source code for the page.
<?php
// starts a session and checks if the user is logged in
error_reporting(E_ALL & ~E_NOTICE);
session_start();
if (isset($_SESSION['id'])) {
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
} else {
header('Location: index.php');
die();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<p><span>Room No: </span><?php $room = $_SESSION['g'];
echo $room; // echo's room ?>
</p>
<p><span>Computer No: </span><?php
$select3 = $_POST['bike'];
echo $select3;
?>
</p>
<p><span>Date: </span><?php $date = $_POST['datepicker'];
echo $date; // echo's date
?>
</p>
<p><span>Start Session: </span>
<?php
if(isset($_POST['select1'])) {
$select1 = $_POST['select1'];
echo $select1;
echo "";
}
else{
echo "not set";
}
?>
</p>
<p><span>End Session: </span>
<?php
if(isset($_POST['select2'])) {
$select2 = $_POST['select2'];
echo $select2;
echo "";
}
else{
echo "not set";
}
?>
</p>
</div>
<div id="success">
<?php
$servername = "localhost";
$name = "root";
$password = "root";
$dbname = "my computer";
// Create connection
$conn = mysqli_connect($servername, $name, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$query = "SELECT * FROM `booked` WHERE
`date` = '{$date}' AND
`computer_id` = '{$select3}' AND
`start_time` = '{$select1}' AND
`end_time` = '{$select2}' AND
`room` = '{$room}'
";
$result = mysqli_query($conn, $query);
if ( mysqli_num_rows ( $result ) > 0 )
{
header('Location: exist.php');
die();
}
else
{
$sql = "INSERT INTO booked (date, computer_id, name, start_time, end_time, room)
VALUES ('$date', '$select3', '$username', '$select1', '$select2', '$room')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
</div>
<form action="user.php">
<input type="submit" value="book another" class="bookanother" />
</form>
</div>
</body>
</html>
If the header is sent already, for example you have echo something before then the header will not work, because the header cannot be set after data flow has started, (since php would have already set the default headers for you). So, in this case if that is so, I do the redirect using javascript.
PHP Docs:
Remember that header() must be called before any actual output is
sent, either by normal HTML tags, blank lines in a file, or from PHP.
It is a very common error to read code with include, or require,
functions, or another file access function, and have spaces or empty
lines that are output before header() is called. The same problem
exists when using a single PHP/HTML file.
WORK-AROUND: This is a function I have written long back and include in controllers.
/**
* Safely redirect by first trying header method but if headers were
* already sent then use a <script> javascript method to redirect
*
* #param string
* #return null
*/
public function safeRedirect($new_url) {
if (!headers_sent()) {
header("Location: $new_url");
} else {
echo "<script>window.location.href = '$new_url';</script>";
}
exit();
}
add the function and simply call:
safeRedirect('index.php');
Login.php
session_start();
<?php
$username = "root";
$password = "tiger";
$hostname = "localhost";
//connection to the database
$dbhandle = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
/* #var $selected type */
$selected = mysqli_select_db($dbhandle,"sample")
or die("Could not select sample");
$name=(\filter_input(\INPUT_POST,'name'));
$phone=(\filter_input(\INPUT_POST,'phone'));
$email=(\filter_input(\INPUT_POST,'email'));
//$custno=(\filter_input(\INPUT_POST,'custno'));
if(!empty(\filter_input(\INPUT_POST,'continue')))
{
echo "<script type='text/javascript'>\n";
'check()';
echo "</script>";
$sql="insert into customersignin(name,phone,email)values('$name','$phone','$email')";
$result=mysqli_query($dbhandle,$sql) or die(\mysqli_error($dbhandle));
}
else
{
$sql1="insert into customersignin(custno)values(NULL)";
$result1=mysqli_query($dbhandle,$sql1) or die(\mysqli_error($dbhandle));
}
$sql2="select custno from customersignin";
$result2=mysqli_query($dbhandle,$sql2) or die (mysqli_error($dbhandle));
$row= mysqli_fetch_array($result2);
if(mysqli_num_rows($result2)>0)
{
echo "$_SESSION['custno']";
unset($_SESSION['custno'];
header('Location:customersvsoup.php');
}
mysqli_close($dbhandle);
$_SESSION[name]=(\filter_input(INPUT_POST,'name'));
customer.php
<body>
<?php session_start(); ?>
<input type="text" style="position: absolute;top:200px;" value="<?php echo $_SESSION["custno"]?>">
</body>
In the php file the customer log in is done,the custno is the auto generate field,i have 2 buttons called continue and skip,for both the auto generate works fine,after any of the button action is done,i need to display the custno in the text box of the next page using session.But the problem is the text box is empty when i run this code.But the session['name'] is working..Please help.
Your session_start(); should come at the beginning of the file in login.php. I see you using $_SESSION[custno] before it's called. That's why your textbox is empty.
Also it should be:
$_SESSION['custno']
$_SESSION['name']note the single quotes
Regarding your logical problem (in the comments) try:
$_SESSION['name'] = (filter_input(INPUT_POST, 'name'));
if (!empty(filter_input(INPUT_POST, 'continue')))
{
echo "<script type='text/javascript'>\n";
'check()';
echo "</script>";
$sql = "insert into customersignin(name,phone,email)values('$name','$phone','$email')";
$result = mysqli_query($dbhandle, $sql) or die(mysqli_error($dbhandle));
$sql2 = "select max(custno) as last_custno from customersignin";
$result2 = mysqli_query($dbhandle, $sql2) or die(mysqli_error($dbhandle));
if (mysqli_num_rows($result2) > 0)
{
$row = mysqli_fetch_assoc($result2);
$_SESSION['custno'] = $row['last_custno'];
header('Location:customersvsoup.php');
}
}
else
{
$sql1 = "insert into customersignin(custno)values(NULL)";
$result1 = mysqli_query($dbhandle, $sql1) or die(mysqli_error($dbhandle));
//since this bit of code is repeating,
//you could even use a function to shorten it
$sql2 = "select max(custno) as last_custno from customersignin";
$result2 = mysqli_query($dbhandle, $sql2) or die(mysqli_error($dbhandle));
if (mysqli_num_rows($result2) > 0)
{
$row = mysqli_fetch_assoc($result2);
$_SESSION['custno'] = $row['last_custno'];
header('Location:customersvsoup.php');
}
}
And please put the session_start(); inside after <?php. All php code should be within the PHP tags.
you have error in insert query:
$sql="insertintocustomersignin(name,phone,email)values('$name','$phone','$email')";
should be :
$sql="insert into customersignin(name,phone,email) values ('$name','$phone','$email')";
you should use quotes in array index :
$_SESSION[custno], $_SESSION[name] should be $_SESSION['custno'], $_SESSION['name']
// query
$sql = "INSERT INTO tool (title,details) VALUES (:title,:details) ";
$q = $conn->prepare($sql);
$q->execute(array(':details'=>$details,
':title'=>$title));
Been having trouble with this all day, I've finally got it down to this. If I use the above code, it will just add a new post to the database. This is supposed to be used for editing a post, so obviously I need to edit existing information:
// query
$post = htmlspecialchars($_GET['story']);
$sql = "UPDATE tool SET (title,details) VALUES (:title,:details) WHERE id = $post";
$q = $conn->prepare($sql);
$q->execute(array(':details'=>$details,
':title'=>$title));
'id' is a column in the database. I need it to update the title, and details, for that specific post. I'm just not sure what syntax I'm supposed to be using here.
Thanks for any answers!
===== Second question:
Now I'm back to my old error. Whenever I edit a post, it will lose the title and details, only once. The first time I edit the post, I lose all information, but the rest of the times it will work just fine. Any idea why? Heres the code:
Form from the edit page(may or may not be important, I don't know):
$name = $_SESSION['Username'];
if (in_array($name, $allowedposters)) {
$results = mysql_query("SELECT * FROM tool WHERE id = $post");
while($row = mysql_fetch_array($results)){
$title= $row['title'];
$details= $row['details'];
$date= $row['date'];
$author= $row['author'];
$id= $row['id'];
echo "<a href=story.php?id=";
echo $post;
echo ">Cancel edit</a> <br><br><b>";
echo $title;
echo "</b> <br><br>";
echo '
<form action="edit-new.php?story=';
echo $id;
echo '" method="post" enctype="multipart/form-data">
<textarea rows="1" cols="60" name="title" wrap="physical" maxlength="100">';
echo $title;
echo '</textarea><br>';
?>
<textarea rows="30" cols="60" name="details" wrap="physical" maxlength="10000">
<?php
echo $details;
echo '</textarea><br>';
echo '<label for="file">Upload featured image:</label><br>
<input type="file" name="file" id="file" />';
echo'<br><input type="submit" />';
}
} else {
echo "Not enough permissions.";
}
?>
Here is the SQL, inserting into DB:
<?php
$post = htmlspecialchars($_GET['story']);
$title = mysql_real_escape_string($_POST['title']);
$details = mysql_real_escape_string($_POST['details']);
echo "B<br>";
echo $_POST['title'];
echo '<br>';
echo $_POST['details'];
echo $post;
echo "<br><br>";
// configuration
$dbtype = "mysql";
$dbhost = "localhost";
$dbname = "zzzz";
$dbuser = "zzzzz";
$dbpass = "zzzzzz";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
// query
$sql = "UPDATE tool SET title=:title, details=:details WHERE id = :postid";
$q = $conn->prepare($sql);
$q->execute(array(
':details'=>$details,
':title'=>$title,
':postid' => $post
));
?>
Fix your sql UPDATE syntax
$sql = "UPDATE tool SET title=:title, details=:details WHERE id = :postid";
$q = $conn->prepare($sql);
$q->execute(array(
':details'=>$details,
':title'=>$title,
':postid' => $post
));