I'm at a complete loss here. I've written a relatively simple PHP script which updates a database record based on user input from a HTML form. The script contains an 'if' statement which executes based a hidden input. I know that the statement executes because the SQL query executes without a problem. The problem I'm having is that there there is another if statement within which should execute if the query object is set, but apparently it doesn't because the $message variable within is not assigned a value. I know that the query object is set because when I echo it it shows up as '1'. Below is the code block in question:
<?php
if(isset($_POST['submitted']) == 1) {
$name = mysqli_real_escape_string($dbc, $_POST['name']);
$q = "UPDATE ".$_POST['table']." SET name = '".$name."' WHERE id = ".$_POST['id'];
$r = mysqli_query($dbc, $q);
echo $r;
print_r($_POST);
echo mysqli_error($dbc);
if ($r) {
$message = '<p>Operation executed successfuly</p>';
} else {
$message = '<p>Operation did not execute because: '.mysqli_error($dbc);
$message .= '<p>'.$q.'</p>';
}
}
?>
The echoes and print_r() below the query are for debugging purposes. The code that should echo $message is above the aforementioned code block (in my script) and looks like this:
<?php if(isset($message)) {echo $message;} ?>
Also, I tried using isset() for the $r variable and also changed the condition to $r !== false but that did not make a difference. When I just echo out $message without the isset() i get the obvious " Undefined variable: message in C:\xampp\htdocs\IMS\modify.php on line 47" error. My apologies if I'm missing something glaringly obvious. I did search beforehand but all the answers were too different from my situation and my knowledge of PHP is too small for me to be able to connect dots that are that far away, if you know what I mean.
EDIT: alright, I might as well put in the entire script. It's a bit all over the place, my apologies. The $id and $table variables do show as undefined after the submit button is pressed, could that have something to do with it?
<?php
error_reporting(E_ALL);
include('config/setup.php');
$id = $_GET['id'];
$table = $_GET['table'];
if ($table == "users") {
header('Location: index.php');
exit;
}
?>
<html>
<head>
<title>Update</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="back">
Back
</div>
<div class="panel">
<?php
if(!isset($_POST['submitted'])) {
$q = "SELECT name FROM $table WHERE id = $id";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_assoc($r);
if($table == "categories"){
$type = "category";
} else if ($table == "products") {
$type = "product";
}
echo "<p>You are changing the properties of this ".$type.": ".$row['name']."</p>";
}
?>
<?php if(isset($message)) {echo $message;} ?>
<form action="modify.php" method="POST">
<label for="name">New name</label>
<input type="text" class="form-control" id="name" name="name">
<button type="submit">Submit</button>
<input type="hidden" name="submitted" value="1">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="hidden" name="table" value="<?php echo $table; ?>">
</form>
<?php
if(isset($_POST['submitted'])) {
$name = mysqli_real_escape_string($dbc, $_POST['name']);
$q = "UPDATE ".$_POST['table']." SET name = '".$name."' WHERE id = ".$_POST['id'];
$r = mysqli_query($dbc, $q);
echo $r;
print_r($_POST);
echo mysqli_error($dbc);
if ($r !== false) {
$message = '<p>Operation executed successfuly</p>';
} else {
$message = '<p>Operation did not execute because: '.mysqli_error($dbc);
$message .= '<p>'.$q.'</p>';
}
}
?>
</div>
</body>
EDIT2: Alright, I came up with a "fix" that kind of solves the problem, namely, I moved the if condition up before the echo of $message and changed the condition to isset($_POST['submitted']. This will have to do, I suppose. I guess I should read up more about the order of operations when processing submitted data and parsing PHP files in general, because I am quite confused as to why this "fix" even works...
This (conditional) statement is a false positive:
if(isset($_POST['submitted']) == 1)
What you need to do is either break them up into two separate statements:
if(isset($_POST['submitted']) && $_POST['submitted']== 1)
or just remove the ==1.
Your code is also open to a serious SQL injection. Updating a table and setting columns from user input is not safe at all.
At best, use a prepared statement.
https://en.wikipedia.org/wiki/Prepared_statement
However, please note that you cannot bind a table and/or a column should you want to convert that to a prepared statement method.
Therefore the following will fail (when using a PDO prepared statement as an example):
$q = "UPDATE :table SET :name = :name WHERE id = :id;
or
$q = "UPDATE ? SET name = :name WHERE id = :id;
Read the following about this method, where that cannot be used:
Can I parameterize the table name in a prepared statement?
Can PHP PDO Statements accept the table or column name as parameter?
Related
I have been looking for 3 weeks on the Internet for an answer to this question and cannot find anything that even comes close or in handy. I have a Database Table that i need to have checked. If a Users_ID is present in that table, I would like my code to display an update.php link in my form action="" tag and if the Users_ID is not present in that db table, then i would like to have an Insertdb.php page to be linked in the form instead of an update.php page. Here is what I have:
PHP Code:
<?php
session_start();
error_reporting(E_ALL);
include_once("dbconnect.php");
$users_id = $_SESSION['user_id'];
$sql = "SELECT * FROM dbtable WHERE uid=$users_id";
if($results = $con->query($sql)) {
while($display = $results->fetch_array(MYSQLI_ASSOC)) {
$uid = $display['uid'];
if($display['uid']==""){
$pagelink = "insertintodb.php";
}else{
$pagelink = "updatedb.php";
}
}
$results->close();
}
?>
And my HTML section looks like this:
HTML Code:
<form action="<?php echo $pagelink; ?>" method="POST">
<input type="text" value="" placeholder="Insert Value" name="something" />
<input type="submit" value="Submit Data" name="submit_data_to_db" />
</form>
How would I go about doing this? My current method Posted above is what I'm currently using, however its displaying only <form action="" method="POST"> when i check it against the pages view-source. Please help me anyway you can. Any and all help would be greatly appreciated. Thank you
you usually use num_rows method:
<?php
session_start();
error_reporting(E_ALL);
include_once("dbconnect.php");
$users_id = $_SESSION['user_id'];
$sql = "SELECT * FROM dbtable WHERE uid=$users_id";
if($results = $con->query($sql)) {
if($results->num_rows() > 0){
$pagelink = "insertintodb.php";
}else{
$pagelink = "updatedb.php";
}
}
$results->close();
}
?>
I see you use $con but I see nowhere you have declared it.
Can you confirm that actually exists? It is possible your script is halting its execution at that point.
Also a few things I would implement in there:
1. When you use variables that come from external sources (like your forms), or even other variables really, always care for SQL injection;
2. Your if & else can be reduced to just an if (when you find an ID). To all others case, you wish a default behaviour that is your else. So something like this:
$pageLink = "insertintodb.php";
if (!empty($display['uid'])) {
$pageLink = "updatedb.php"
}
I am new to PHP/MYSQLI and I am having trouble creating a simple search to search my database. The columns in my database are: 'ID' , 'Name' , 'Age'. The name of my database is 'users' and the table name is 'employees'.
Here is the code:
<?php require('Connections/Localhost.php'); ?>
<?php
if (isset($_POST['Search'])) {
$search = $_POST['element'];
$sql = mysqli_query("SELECT * FROM employees WHERE Name = '$search' ");
if($sql->num_rows > 0 ) {
while($rows = $sql->fetch_assoc()) {
$id = $rows['ID'];
$name = $rows['Name'];
$age = $rows['Age'];
echo "ID: $id <br> Name: $name <br> Age: $age <br>";
}
}
else {
echo "No Result Found!";
}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form method="post">
<input type="text" name="element" placeholder="Enter A Name"/>
<input type="button" name="Search" value="Search" />
</form>
</body>
</html>
It just returns a blank page and nothing else. I want the user to enter a name in the text area of the form and on clicking the Search button all the data corresponding to that name from the database should be displayed on the webpage. Please correct me where I made the mistake.
You need to change button type to submit.
Your form is not posting.
Change
<input type="button" name="Search" value="Search" />
To:
<input type="submit" name="Search" value="Search" />
Also, mysqli_query() needs database connection resource.
You have given only sql query.
$sql = mysqli_query($databaseConnection, "SELECT * FROM employees WHERE Name = '$search' ");
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode =
MYSQLI_STORE_RESULT ] )
Reference
As per request of OP here I will explain the general concept of a Prepared statement in mysqli feel free to edit this if you feel I did not elaborated on a topic.
The first thing you need to do is prepare the query(preparing the
query is sending an empty query to the database). But instead of
defining the parameter you will put a question mark.
After that you need to bind the parameters to the question marks In the exact order as in the query! The first thing you'll do is defining the type of the parameter string is s integer is i and blob
is b. After that you'll need to define the variables with the data.
And the third and final thing you'll need to do is executing the query. I always use it in an if statement because it will return a
true or false and like this you can check if the query failed or not and handle the error. In this case you will not need an else because the page will die if the query returns false.
/*1.*/
$stmt = $databaseConnection->prepare("SELECT * FROM `employees` WHERE `name` = ?");
/*2.*/
$stmt->bind_param("s",$search);
/*3.*/
if(!$stmt->execute())
{
die("There went something wrong: " . $stmt->error);
}
Edit: here is the question explaining more about how to prevent SQL-injections.
I am trying to make this program where I can delete a thread if I am logged in. Now I already have the button linked and everything, I have it doing multiple tasks when pressed, but it seems to not run the SQL query I want it to. Now I have a variable called $forumid which is set in the URL and retrieved using $_GET['forumid'];
I know this is setting properly, because I have done echo $forumid; and its been correct. But there is one line of code that doesn't run for some reason, and that is:
$db->query("DELETE FROM threads WHERE id='$forumid'");
Now when I remove the WHERE clause, it works, but it wipes out the entire table. So I now know that the problem is the WHERE clause, I just can't find out why it is the issue. I am fairly new to PHP so please forgive my ignorance. But if anyone is able to see the issue, please tell me. Thank you.
[EDIT: COMPLETE CODE]
<?php
require 'connect.php';
session_start();
$forumid = $_GET['forumid'];
$title;
$body;
$by;
$loggedAsAuthor;
?>
<html>
<head>
<title>Legend Factions - View Forum</title>
<link href="stylesheet.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="header">
Home
Forum
Vote
Donate
Members
</div>
<div id="content">
<div id="divider">
<?php
if ($result = $db->query("SELECT * FROM threads")) {
while ($row = $result->fetch_assoc()) {
if ($row['id'] == $forumid) {
$title = $row['title'];
$body = $row['words'];
$by = $row['by'];
if ($_SESSION['sess_username'] == $by || $_SESSION['sess_username'] == "admin") {
$loggedAsAuthor = true;
}
}
}
}
echo '<h2>', $title, '</h2><br/><label>By: ', $by;
if (isset($loggedAsAuthor)) {
echo '<form action="viewForum.php" method="post">
<br/><input type="submit" name="delete" value="Delete Thread"/>
</form>';
}
$delete = $_POST['delete'];
if (isset($delete)) {
$db->query("DELETE FROM threads WHERE id=$forumid ");
//header("Location: forum.php");
}
?>
<hr/>
<?php
echo $body;
?>
</div>
</div>
</body>
</html>`
You need to modify your sql query as like :
$db->query("DELETE FROM threads WHERE id= $forumid "); // removed single quotes
Hope it works for you now.
You can try this way, Hope it will help
$qry = "DELETE FROM threads WHERE id= $forumid ";
$db->query($qry);
Your query seems to be correct.
If $_GET['forumid'] is a string, do :
$db->query("DELETE FROM threads WHERE id=".$db->quote($_GET['forumid']));
If $_GET['forumid'] is numeric, do :
$db->query("DELETE FROM threads WHERE id=".(int)$_GET['forumid']);
In any case, string syntax should work, because string will be cast to integer by mysql.
To debug, do :
echo "DELETE FROM threads WHERE id=".$db->quote($_GET['forumid']) ;
And give us the result, or directly paste it into phpMyAdmin to see the error.
You should also add this line at the top of your script to see all errors :
error_reporting(E_ALL) ;
ini_set('display_errors', true) ;
if(isset($_GET['forumid']) && !empty($_GET['forumid'])){
$qry = "DELETE FROM threads WHERE id= '" . mysql_real_escape_string ($_GET['forumid']) . "'";
}
or use active record
$this->db->where('id', $forumid );
$this->db->delete('threads ');
Either integer or string syntax in MySQL should work if the threads id is an integer. What I see that could be happening is:
1) $forumid does not have the value you think it has?
To check it, var_dump the variable right before the delete query:
var_dump($forumid); die;
2) The table id column is not named "id"?
Check the database schema, to check if the column has the name you think it should have. In mysql CLI:
desc threads;
i have this code which permits me to do a request in order to make a query!
Now the form which is processed has this code:
<form action="edit_images.php" method="post">
<input type="hidden" value="<? echo $gal_id1 ?>" name="img_id1" />
<input type="submit" value="Edit All Images" />
</form>
While the query is like this :
$img_id=$_REQUEST['img_id1'];
$sql="SELECT * FROM tbl_images WHERE Img_gal_id='$img_id'";
But it seems like it won't take the value...
I mean, it doesn't recognize the $img_id, which i have printed before and takes the exact value.
Let me show you the query i use in order to retrieve it:
$sql = "SELECT gal_id,gal_title,gal_image FROM tbl_galleries where gal_id='" . $_REQUEST['gid'] ."';";
$query = mysql_query($sql) or $myErrorsP = mysql_error();
if(isset($myErrors) && $myErrorsP!=''){
} else {
$row = mysql_fetch_row($query);
mysql_free_result($query);
$gal_id = $row[0];
$gal_id1 = $row[0];
$gal_title = $row[1];
$gal_image = $row[2];
}
You are missing a ; on the end of your echo that isn't outputting the value as expected. Additionally, you are using short tags, which could be causing problems. You might want to swtich to using <?php as an opening over <? on it's own.
<input type="hidden" value="<?php echo $gal_id1; ?>" name="img_id1" />
Lastly, you are using zero protection against injection attacks. Please, research prepared statements in PDO and update your code. The first injection attack you don't have will thank you for it.
Edit: When you run into a problem like this, it is often good practice to echo out the $sql just before you execute it.
you could do this in the future with:
$sql = "SELECT gal_id,gal_title,gal_image FROM tbl_galleries where gal_id='" . $_REQUEST['gid'] ."';";
echo $sql."<br>\n";
$query = mysql_query($sql) or $myErrorsP = mysql_error();
which would have probably given you an excellent indication of what the problem was.
I am reading a tutorial on how to insert and update data into a MySQL table using PHP, the code is listed below. My problem is when i click update but I have not modified any data, rowCount() returns 0 and breaks the code.
My question is, If I am simply updating the database with the same values that are in the database, why does rowCount() return zero? My thoughts were that even though it was the same data it would be inserted anyway and return a count of the updated rows? I am guessing that it check the data before it try's the update? Can anyone shed some light on this for me and suggest a workaround? I have been starring at the code for hours and have been unable to come up with anything, thanks.
<?php
require_once('../includes/connection.inc.php');
// initialize flags
$OK = false;
$done = false;
// create database connection
$conn = dbConnect('write', 'pdo');
if (isset($_GET['article_id']) && !$_POST) {
// prepare sql query
$sql = 'SELECT article_id, title, article FROM blog WHERE article_id = ?';
$stmt = $conn->prepare($sql);
// bind the results
$stmt->bindColumn(1, $article_id);
$stmt->bindColumn(2, $title);
$stmt->bindColumn(3, $article);
// execute query by passing array of variables
$OK = $stmt->execute(array($_GET['article_id']));
$stmt->fetch();
}
// if form has been submitted, update record
if (isset($_POST['update'])) {
//prepare update query
$sql = 'UPDATE blog SET title = ?, article = ? WHERE article_id = ?';
$stmt = $conn->prepare($sql);
// execute query by passing array of variables
$stmt->execute(array($_POST['title'], $_POST['article'], $_POST['article_id']));
$done = $stmt->rowCount();
}
// redirect page on sucess or if $_GET['article_id'] not defined
if ($done || !isset($_GET['article_id'])) {
header('Location: http://localhost/PHP_Solutions/admin/blog_list_pdo.php');
exit();
}
// store error message if query fails
if (isset($stmt) && !$OK && !$done) {
$error = $stmt->errorInfo();
if (isset($error[2])) {
$error = $error[2];
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Update Blog Entry</title>
<link href="../styles/admin.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>Update Blog Entry</h1>
<p>List all entries </p>
<?php if (isset($error[2])) {
echo "<p class='warning'>Error: $error[2]</p>";
echo '<pre>';
print_r($_POST);
print_r($error);
echo '</pre>';
}
if ($article_id == 0) { ?>
<p class="warning">Invalid request: record does not exist.</p>
<?php } else { ?>
<form id="form1" method="post" action="">
<input name="article_id" type="hidden" value="<?php echo $article_id; ?>">
<p>
<label for="title">Title:</label>
<input name="title" type="text" class="widebox" id="title" value="<?php echo htmlentities($title, ENT_COMPAT, 'utf-8'); ?>">
</p>
<p>
<label for="article">Article:</label>
<textarea name="article" cols="60" rows="8" class="widebox" id="article"><?php echo htmlentities($article, ENT_COMPAT, 'utf-8'); ?></textarea>
</p>
<p>
<input type="submit" name="update" value="Update Entry" id="update">
</p>
</form>
<?php } ?>
</body>
</html>
My question is, If I am simply updating the database with the same values that are in the database, why does rowCount() return zero?
rowCount is counting the affected rows by a query. As you haven't changed anything, there are zero affected rows.
PDOStatement->rowCount — Returns the number of rows affected by the last SQL statement
It has nothing to do with PHP - it's just how MySQL works.
MySQL documentations says:
For UPDATE statements, the affected-rows value by default is the number of rows actually changed. If you specify the CLIENT_FOUND_ROWS flag to mysql_real_connect() when connecting to mysqld, the affected-rows value is the number of rows “found”; that is, matched by the WHERE clause.
When you're using the UPDATE statement, and you submit the same values that are in database, it will always return zero, because it doesn't affected any row.
A way to resolve this problem is:
$done = $stmt !== false ? true : false;
What i did?
I did that:
if($stmt !== false){
$done = true;
} else{
$done = false;
}
Because if rowCount() is zero, but $stmt has executed without errors, $stmt was executed, but didn't change anything.
It's how MySQL works and has nothing intrinsically to do with the PDO extension; performing a regular mysql query would produce the same results. There is a workaround I found using the mysql functions, although I'm not sure if you can do anything similar with a PDO object.
$q = 'UPDATE etc...';
$r = mysql_query($q, $con);
$info = mysql_info(); // Returns info about last query.
list($matches, $changed, $warnings) = sscanf($matched, "Rows matched: %d Changed: %d Warnings: %d");
if ($matches > 0) {} // etc
Hope this helps a little.