MYSQL and PHP database update wont update database - php

I am having an issue trying update the database with a form.
So, my issue is when I click on update nothing happens. The database doesn't update.
Another issue is when i use POST in my form and SQL query. It doesn't pull the information through to the edit page, it is blank.
I'm sorry if this hard to read etc. but this is my first time posting. Also, I know there is security flaws in my GET/POST queries I'm just trying to get the thing to work before I start using the prepared statements or whatever they are called.
FYI, if I echo the query and define a if/else statement, I can see it doesn't work but I just don't know why. I have spent 3 days on this and change the code so many times using examples I have found on the internet.
Index.php
<?php
$servername = "localhost";
$username = "***";
$password = "****";
$dbname = "****";
$link = new mysqli("$servername", "$username", "$password", "$dbname");
if ($link->connect_error) {
die("Connection failed: " . $link->connect_error);
}
echo "Connected successfully";
mysqli_select_db($link,"jamesrph_myphp");
$sql = "SELECT * FROM article";
$result = mysqli_query($link,$sql);
$id = 'id';
$title = 'title';
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css"/>
<title>PHP </title>
</head>
<body>
<h1> My title </h1>
<table>
<tr>
<?php
while($row=mysqli_fetch_array($result)){
?>
<td><?php echo $row["title"]; ?> </td>
<td>Read More</td>
<td>Edit</td>
</tr>
<?php
}
?>
</table>
</body>
</html>
edit.php
<?php
$link = mysqli_connect("localhost","******","******", "*****");
$query = "SELECT * FROM article WHERE id=".mysqli_real_escape_string($link, $_GET['id'])." LIMIT 1";
$result = mysqli_query($link,$query);
$row = mysqli_fetch_array($result);
$title = $row['title'];
$content = $row['content'];
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<p> Edit Article </p>
<form method="get" action="processarticle.php">
<input type="hidden" name="id" value="<?php echo $row["id"]; ?>" />
<input id="titlearea" type="text" name="title" value="<?php echo $row["title"]; ?>"/>
<textarea id="contentarea" name="content" rows="10" cols="40"><?php echo $row["content"];?></textarea>
<input type="submit" name="submit" id="update_article"/>
</form>
</body>
</html>
processarticle.php
<<?php
//Database Connection
include 'connection.php';
//Get ID from Database
if(isset($_GET['edit_id'])){
$sql = "SELECT * FROM article WHERE id =" .$_GET['edit_id'];
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_array($result);
}
//Update Information
if(isset($_POST['btn-update'])){
$title = $_POST['title'];
$content = $_POST['content'];
$id = $_POST['id'];
$update = "UPDATE article SET title=?, content=? WHERE id=?";
$up = mysqli_query($link, $update);
if($stmt = $mysqli->prepare($update)){
$stmt->bind_param("ssi" ,$title ,$content ,$id);
$stmt->excute();
}
header("location: disp.php");
}
?>

Ok your edit.php form has a GET method, yet you are using POST variables in you processarticle.php and you have a GET variable in there.
Lets just say a form can only do one thing either GET or POST
The URL you specified in your form then will access either GET or POST variables based on form method
So if you want to update your article based off your form first lets look at the id = this should be $POST['id'] the hidden field in your form, not that hidden though
$update = "UPDATE article SET title='$title', content='$content' WHERE id=". $_POST['id'];
The more I look at this the more this is going to turn in to a 3 part mini series
Ok on your processarticle.php for starters I would use a prepared statement for the update http://php.net/manual/en/mysqli.prepare.php
process.php
//Update Information
if(isset($_POST['Update_Article'])){
$title = $_POST['title'];
$content = $_POST['content'];
$id = $_POST['id'];
$SQL = "UPDATE
article
SET title=?, content=?
WHERE id=?";
if ($stmt = $mysqli->prepare($SQL)) {
$stmt->bind_param("sss", $title ,$content ,$id );
$stmt->execute();
}
}
Start here http://www.w3schools.com/php/default.asp and go from crawling to walking
Honest to god work through that from top to bottom then go here
https://symfony.com/ and hope in a F1 Car
Then try http://www.w3schools.com/bootstrap/default.asp because you are going to want your page to look cool

Use form method post or change all $_POST in $_GET in processarticle.php.
And try changing $_GET['edit_id'] into $_GET['id'] in processarticle.php.

Related

My website search query is not working

On my website I have a file articles.php and on it I have a search field. When I enter the information it redirects me to my search.php which is correct and in the URL I can see it is outputting my result but it's not showing me my results on the search.php body.
The Localhost URL is outputting after I searched "Can you game on Windows visa"
http://localhost/qaa/search.php?search=Can+you+game+on+widows+vista&submit-search=
There is nothing on this page, just an empty box search.php
Connection
<?php
$server = "localhost";
$username = "root";
$password = "";
$db = "Qaa";
$conn = mysqli_connect($server, $username, $password, $db);
?>
articles.php "Where my search bar is located"
<?php
include 'connect.php';
?>
<h1>Front Page</h1>
<h2>All articles:</h2>
<link rel="stylesheet" type="text/css" href="css/article.css">
<div class="article-container">
<form action="search.php">
<input type="text" name="search" placeholder="Search">
<button type="submit" name="submit-search">Get answers</button>
</form>
<?php
$sql = "SELECT * FROM article";
$result = mysqli_query($conn, $sql);
$queryResults = mysqli_num_rows($result);
if ($queryResults > 0){
while ($row = mysqli_fetch_assoc($result)){
echo "<div class='article-box'>
<h3>".$row['a_title']."</h3>
<p>".$row['a_text']."</p>
<hp>".$row['a_date']."</p>
<p>".$row['a_author']."</p>
</div>";
}
}
?>
Search.php "Where the search information should appear after click on 'Get answers button'"
<?php
include 'connect.php';
?>
<link rel="stylesheet" type="text/css" href="css/article.css">
<h1>Search Page</h1>
<div class="article-container">
<?php
if (isset($_POST['submit-search'])){
$search = mysqli_real_escape_string($conn, $_POST['search']);
$sql = "SELECT * FROM article WHERE a_title LIKE '%$search%' OR a_text
LIKE '%$search%' OR a_author LIKE '%$search%' OR a_date LIKE '%$search%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
echo "There are ".$queryResult." results!";
if($queryResult > 0){
while ($row = mysqli_fetch_assoc($result)){
echo "<div class='article-box'>
<h3>".$row['a_title']."</h3>
<p>".$row['a_text']."</p>
<hp>".$row['a_date']."</p>
<p>".$row['a_author']."</p>
</div>";
}
}else{
echo "There are no results matching your search! Contact our support so
we can add this or if you have a result, add it, as a result, using the
GIVE ANSWER button!";
}
}
?>
</div>
You are using $_POST['search'] Which is wrong. Because your search string is submitted in get method. So you must use:-
$_GET['search']
Please try this.

how to search sql database using php

For the past couple days, I have been trying to learn how to search an mysql database. So far I have the code below. for some reason it isn't searching and giving me results back. my database is named score and the table is all scores. Someone please help me with this.
It should be searching my database but it's coming up with no results. I have made sure everything is correct.
This file is searching.php
<?php
if (isset($_POST['search'])) {
$id = $_POST['id'];
$connect = mysqli_connect("localhost", "root", "root", "score");
$query = "SELECT `name` FROM `all_scores` WHERE `id` = $id LIMIT 1";
$result = mysqli_query($connect, $query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$name = $row['name'];
}
} else {
echo "Undifined ID";
$gameid = "";
}
mysqli_free_result($result);
mysqli_close($connect);
} else {
$gameid = "";
}
this is search.php
<!DOCTYPE html>
<html>
<head>
<title> PHP FIND DATA </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="searching.php" method="post">
Id:<input type="text" name="id"><br><br>
<input type="submit" name="search" value="Find">
</form>
</body>
</html>
To get the form values inside the php file you need to use $_POST. Here's an example using PDO. You're only retrieving one row so you don't need the while loop.
searching.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$q = $conn->prepare("SELECT `name` FROM `all_scores` WHERE `id` = :id LIMIT 1");
$q->bindValue(':id', $_POST['id'], PDO::PARAM_STR, 50);
$q->execute();
if ($q->rowCount() > 0) {
$check = $q->fetch(PDO::FETCH_ASSOC);
$row_id = $check['id'];
// do something
}
Html:
<form action="searching.php" method="post">
Id:<input type="text" name="id"><br><br>
<input type="submit" name="search" value="Find">
</form>
Take some time look at several other examples

session variables are not inserting in database in php and mysql form

It is not inserting the session variables like name, id ,email, number like which is stored in $a,$b,$c,$d in pseller.php
This is my login page where i am checking username and password
login.php
<?php
error_reporting(E_ALL); // to see if there is error in code
include "connect_to_mysql.php";
if(isset($_POST['log']))
{
$user= $_POST['user'];
$pass= md5($_POST['pass']);
$sql=mysql_query( "select * from reg where username= '$user' AND password='$pass' AND category='product seller' LIMIT 1 ") or die( mysql_error());
$data=mysql_num_rows($sql);
if ($data == 1) {
$_SESSION['name']=$name;
$_SESSION['id']=$id;
$_SESSION['phone_no']=$number;
$_SESSION['email_id']=$email;
header("location:pseller.php");
}
else {
header("location:login.php?error");
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> Log In </title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
</head>
<body>
<div id="mainWrapper">
<div id="pageContent"><br /><br /><br />
<div align="right" style="margin-right:24px; color:#FF0000">
<br /><br />
<form id="form" name="form" method="post" action="login.php">
<h2 style="padding-right:200px;">User Name:</h2>
<input name="user" type="text" id="user" size="40" style="height:30px;" required placeholder="Enter Email"/>
<br /><br />
<h2 style="padding-right:210px;">Password:</h2>
<input name="pass" type="password" id="pass" size="40" style="height:30px;" required/>
<br />
<br />
<br />
<img style="padding-right:190px;" src="generate.php"><br /><br />
<input type="text" name="secure" size="10" required placeholder="Enter The Value" style="padding-right:210px; height:30px;">
<br />
<br />
<br />
<input type="submit" name="log" id="log" value="Log In" style="padding-right:40px;" />
</form>
<p> </p>
</div>
<br />
<br />
<br />
</div>
</div>
</body>
</html>
This is pseller page where I am trying to store session values in variables then inserting in database. but session variables are not inserting data in database and showing the value of v_id v_number as 0.
pseller.php
<?php
// Parse the form data and add inventory item to the system
include_once('connect_to_mysql.php');
session_start();
if (isset($_POST['p_name'])) {
$target_dir = "pics/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file) ;
$img_name = $_FILES["fileToUpload"]["name"];
$a=$_SESSION['name'];
$b=$_SESSION['id'];
$c=$_SESSION['phone_no'];
$d=$_SESSION['email_id'];
$product_name = mysql_real_escape_string( $_POST['p_name']);
$price = mysql_real_escape_string($_POST['price']);
$category = mysql_real_escape_string($_POST['category']);
$subcategory = mysql_real_escape_string($_POST['subcategory']);
$category2 = mysql_real_escape_string($_POST['category2']);
$details = mysql_real_escape_string($_POST['details']);
// See if that product name is an identical match to another product in the system
// Add this product into the database now
$sql = mysql_query("INSERT INTO product (p_name, price, details, category, sub_category, category2, img_name, v_id, v_name, v_number, v_email, date) VALUES('$product_name','$price','$details','$category','$subcategory','$category2','$img_name','$b','$a','$c','$d',now())") or die (mysql_error());
}
?>
Please help me to come out from here.
Ok so judging from the question and discussion in the comments, you're lacking proper handling of the user data in login.php.
There are also a couple of other points that are a bit off in your code:
You should not the mysql library as it's deprecated. You should either use mysqli, which is a rather easy switch if you're already used to mysql, or use PDO
Your code is vulnerable to SQL injection. You should use prepared statements when using user input in SQL queries. More info here for example
MD5 is not a very secure option for passwords. You can read more here
Below is a simple example of the PHP part for login.php I threw together based on what information I could gather from your question. It isn't complete for your specific database structure and needs, but should help you forward with your problem:
<?php
// Define database connection using mysqli
$mysqli = new mysqli("localhost", "username", "password", "dbname");
if(isset($_POST['log']))
{
$user= $_POST['user'];
$pass= md5($_POST['pass']); // Should be replaced by secure alternatives
// Define the SQL query string
$sql = "SELECT id, name, phone_no, email FROM reg WHERE email = ? AND password = ? LIMIT 1";
$stmt = $mysqli->prepare($sql); // Prepare the query string
$stmt->bind_param("ss", $user, $pass); // Define prepared statement parameters
// Execute the prepared stament
if ($stmt->execute())
{
$result = $stmt->get_result(); // Get the result
$data = $result->num_rows; // Get number of rows
if ($data == 1)
{
$userdata = $result->fetch_array(MYSQLI_ASSOC); // Get an associative array from the result
$_SESSION['name'] = $userdata['name'];
$_SESSION['id'] = $userdata['id'];
$_SESSION['phone_no'] = $userdata['phone_no'];
$_SESSION['email_id'] = $userdata['email'];
header("location:pseller.php");
}
}
else
{
header("location:login.php?error");
}
}
?>
$_SESSION['id']=$id;
$_SESSION['phone_no']=$number;
only get updated if select with username and password has rowcount 1
Those become variables $b and $c in pseller.php
So if $user and $pass do not get you a row on select from db, you get junk in SESSION.
mysql_num_rows returns number of rows. You are doing LIMIT 3. So if you are 0, 2, or 3, session is in trouble. Why, because your if statement says =1.
Also, you are using a deprecated mysql_* function library and acting directly upon user-supplied values that can render sql injection attacks. Use mysqli or pdo, and see this.
Include session_start(); in yourlogin.php
$sql=mysql_query("select * from reg where username= '$user'
AND password='$pass' AND category='product seller'") or die( mysql_error());
Inside the above query, Please make the changes.
Avoid making column names with spaces category='product seller'
Now echo the values under the SELECT * FROM query and the $a, $b, $c, $d to know if you REALLY are taking the values through to the next page. I am pretty much sure that you were not and also #Drew suggested, shift to msqli/PDO.
EDIT:
In your second page pseller.php try to echo and see what you're getting.
echo $_SESSION['name'];
echo $_SESSION['id'];
echo $_SESSION['phone_no'];
echo $_SESSION['email_id'];
No luck? Okay let's just try it this way and see what happens;
$sql=mysql_query("select * from reg where username= '$user' AND password='$pass'") or die( mysql_error());
if ($sql) {
while($row=mysql_fetch_array($sql))
{
echo $row['name'];
echo $row['id'];
echo $row['phone_no'];
echo $row['email_id'];
}
// header("location:pseller.php");
}
Now put the correct username and password (present in the database) and if you can see the echoed values, use sessions to store and use them later on also uncomment the header(); line and you are good to go.

Linking to user profile through PHP

On my website I've displayed a list of registered users on a members page using echo in PHP. I'd now like to link the names of these users to their profile pages. Is there a way to do this?
My current code:
<html>
<title>Find User Info</title>
<body>
<form method="POST">
<p>Type Username: </p><input type="text" name="username"placeholder="Enter Username...">
<br>
<input type="submit" name="submit" value="Search User">
</form>
<?php
session_start();
error_reporting(0);
$connection = mysql_connect("localhost", "root", "***"); // Establishing Connection with Server
$db = mysql_select_db("****", $connection); // Selecting Database from Server
$query = mysql_query("SELECT * FROM accs ORDER BY loginstatus"); //selecting all from table users where username is name that your is loged in
while($row = mysql_fetch_assoc($query))
{
echo $row['name'];
}
if(isset($_POST['submit'])){
$username = $_POST['username'];
$_SESSION['searchuser'] = $username; //setting session username to one from table, this is useful if you login, that restart your browser and than you go in url where is your profile.php... Anyway this is useful :D
header( 'Location: user.php' ) ;
}
?>
</body>
</html>
The template link is like: mywebsite.com/search/user.php
echo ''.$row['name'].'';
is this what you are looking for ?
All you'll have to do is echo out an <a> element with the appropriate parameters for the link.
In your loop where you echo out the name of the user. you can include the <a> element definitions and only have the name as the text of the link:
while($row = mysql_fetch_assoc($query)) {
$user_name = $row['name'];
$profile_link = "http://your-cool-site/users/" . $row['id'];
echo "<a href='" . $profile_link . "' >" . $user_name . "</a>";
}
This code assumes that the link to your user page is something like:
http://your-cool-site/users/USER_ID

having issues with php_self

I am trying to implement a page where a user enters a comment and it gets displayed right in the same page. The problem i am having is that every time you go to the page there are no comments in the page(there are actually comments).
This is my sceneario i am having:
I go to the page and there are no comments, i enter a comment 'hello' and it gets displayed right away.
I go to a different page and then i come back to the comments page and there are no comments.(the comment "hello" should be already displayed)
I enter a comment "hi" and both comments "hello" and "hi" get displayed
I cant resolve this issue..
This is my code, its pretty long
<?php
session_start(); //starts or continues the session
require_once('functions.php'); //needed for some function calls
error_reporting(E_ALL ^ E_NOTICE);
?>
<!DOCTYPE html>
<html lang = "en">
<head>
<script type = "text/javascript" src = "functions.js"></script>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<?php
GetUserLayout($_SESSION['userId'], $_SESSION['superUser']);
?>
<div id = "shareyouridea_form" class = "post">
<h1> Share your post</h1>
<!-- used for the form -->
<form id = "idea_form" method = "post"
action = "<?php echo $PHP_SELF;?>"
onkeypress = "return DisableEnterKey(event);">
<table>
<caption>
<strong>
<br /> Share post form:
</strong>
</caption>
<tr class = "spacearound"> <!-- input for bright idea -->
<td>  Post: </td>
<td>
<textarea form = "idea_form" name = "b_idea" rows = "12"
cols = "85" title = "Please describe your product idea"
id = "bright_idea" maxlength = "1000"
onkeypress =
"return InputLimiter(event, 'lettersSpacePunctuation');">
</textarea>
</td>
</tr>
</table>
<p>
   
<input type = "reset" value = "Reset" />
  
<input type = "submit" value = "Share Idea!"
title = "complete form first to submit"
id = "submit_button"
name = "add_comment"
onmousedown = "IsIdeaFormCompleted();" />
</p>
</form> <!-- end idea_form -->
</div>
</div> <!-- end of ShareYourIdea_middle -->
<script>
DisplayFooter();
</script>
<?php
if(isset($_POST['add_comment'])){ // if add comment was pressed
// get variables
$name = $_SESSION['firstName'];
$empId = $_SESSION['userId'];
$idea = $_POST['b_idea'];
// CONNECTING TO OUR DATABASE
$db = mysqli_connect(dbHost, dbUser, dbPassword, dbName);
if (mysqli_connect_errno()) { //if connection to the database failed
echo("<p id = 'greatideadescription'>
Connection to database failed: " .
mysqli_connect_error($db) . "</p>");
exit("goodbye");
} //by now we have connection to the database
// WE WRITE OUR QUERY TO INSERT POST INFO TO DATABASE
$query = "INSERT INTO posts(postId,empl_Id,post,postDate)
VALUES('','$empId','$idea',NOW())";
$result = mysqli_query($db, $query);
}
?>
<?php
// WE DO A QUERY TO SHOW ALL COMMENTS IN THE PAGE
$query = "SELECT firstName,lastName, post,
date_format((date_add(postDate,interval -7 hour)),'%a, %M, %d, %Y at %I:%i%p' ) as mydatefield
FROM users INNER JOIN posts ON userId = empl_Id
ORDER BY postDate DESC";
$result = mysqli_query($db,$query);
if (!$result) { //if the query failed
echo("<p id = 'greatideadescription'>
Error, the query could not be executed: " .
mysqli_error($db) . "</p>");
mysqli_close($db);}
if (mysqli_num_rows($result) == 0) { //if no rows returned
echo("<div id = 'blogs'>
<div id ='name'>
No posts detected
</div>
</div>
<div class='fb-like' data-href='http://jacobspayroll.zxq.net/index/blog.php' data-send='true' data-width='450' data-show-faces='true'></div>
");
mysqli_close($db); //close the database
exit("</table></div></form></div></div>
<script>DisplayFooter();</script></body></html>");
} //by now we know that we have some products purchases returned
$numRows = mysqli_num_rows($result); //gets number of rows
$numFields = mysqli_num_fields($result); //gets number of fields
//prints the data in the table
while($row = mysqli_fetch_assoc($result)){
$posted = $row['post'];
$message = wordwrap($posted,5);
echo
'<div id ="blogs">
<table id = "blog_id">
</br>
<div id = "name">
<strong>'.$row['firstName'] . ' ' .$row['lastName'].
'</strong>
: ' .$message .
'<br/>
</div>
<div id ="date">'.
$row['mydatefield'] . '
</div>
<div id ="delete_comment">
Delete this comment
</div>
<p>
</table>
</div>';
}
mysqli_close($db);
?>
</body>
</html>
You have the wrong Usage of PHP_SELF
//You must use Server and execution environment information `$_SERVER[]`
$_SERVER['PHP_SELF'];
// For your form action like this
action = "<?php echo $_SERVER['PHP_SELF'];?>"
as Kail mentioned you got it wrong but you might want to use $_SERVER['SCRIPT_NAME'] instead of $_SERVER['PHP_SELF'] then you might want to add some script to get GET parameters if you use them for your script(s). If you use PHP_SELF you might have a user link to script.php/%22%3E%3Cscript%3Ealert('xss')%3C/script%3E%3Cfoo might look like action="script.php/"><script>alert('xss')</script> or could be a redirect to collect cookies and the alike in other words XSS attack.
$_SERVER['PHP_SELF'] vs $_SERVER['SCRIPT_NAME'] vs $_SERVER['REQUEST_URI']
XSS Woes
What's the difference between $_SERVER['PHP_SELF'] and $_SERVER['SCRIPT_NAME']?

Categories