I am trying to make a basic hit counter that I can use on all of my websites.
I have a prepared statement querying both my Go Daddy MySQL server as well as my MAMP MySQL server, and the the statement won't 'Prepare'. Here it is:
function hit_counter($url){
if($mysqli = new mysqli('localhost', 'root', '', 'DB')){
$crack = "SELECT hc-id, hc-url, hc-unique_hits, hc-total_hits, hc-last_viewed FROM hit_counter WHERE hc-url =?";
if($stmt = $mysqli->prepare(crack)){
$stmt->bind_param('s', $url);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id, $url, $unique_hits, $total_hits, $last_viewed);
$stmt->fetch();
echo "the statement was prepared successfully";
$total_hits = $total_hits+1;
$last_viewed = date('l jS \of F Y h:i:s A');
echo $unique_hits;
if($unique === true){
$unique_hits = $unique_hits+1;
}
$update = 'UPDATE hit_counter set hc-unique_hits=? hc-total_hits=? hc-last_viewed=? WHERE hc-url=?';
if($stmt= $mysqli->prepare($update)){
$stmt->bind_param('iiss', $unique_hits, $total_hits, $last_viewed, $url);
$stmt->execute();
}else{echo "the update statement wasn't prepared.";}
}else{echo "The statement wasn't prepared.";}
}else{echo "the SQL connection wasn't made";}
}
I know that it is connecting to the database, but whenever I run the script, it echos the else statement for if($stmt = $mysqli->prepare(crack)){ "The Statement wasn't prepared".
Your columns contain hyphens which MySQL is interpreting it as hc MINUS unique_hits etc. thinking you want to do a mathematical problem.
You also have missing commas in your SETs
UPDATE hit_counter set `hc-unique_hits`=?, `hc-total_hits`=?, `hc-last_viewed`=? WHERE `hc-url`=?
It's best to stay away from using hyphens for column names. Use underscores instead.
Using
if(!$stmt->execute()){trigger_error("there was an error....".$mysqli->error, E_USER_WARNING);}
would have spotted that error.
Same thing for
$crack = "SELECT hc-id, hc-url, hc-unique_hits, hc-total_hits, hc-last_viewed FROM hit_counter WHERE hc-url =?";
use backticks around those containing hyphens.
$crack = "SELECT `hc-id`, `hc-url`, `hc-unique_hits`, `hc-total_hits`, `hc-last_viewed`
FROM hit_counter WHERE `hc-url` =?";
For more information on Identifier Qualifiers, consult:
http://dev.mysql.com/doc/refman/5.0/en/identifier-qualifiers.html
Also
if($stmt = $mysqli->prepare(crack)){
should be
if($stmt = $mysqli->prepare($crack)){
where you missed the $ for crack. Otherwise it's treated as a constant.
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);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Another developing tool that is at your disposal is var_dump().
Use var_dump($variable_to_check); to see what is passing through or not.
see the value if($stmt = $mysqli->prepare(crack)){ should be
$crack , spot the $ !!
Related
I have a MySQL statement that won't work for me. I've checked several parts of the code but it keeps returning null as the result. I've also tried replacing the WHERE enc_mail = AND enc_public_id=" to "WHERE 1" to check if it was a problem with the variables, but it is not. I did not get errors either.
$connect_db = mysqli_connect("myhost","my username","my password","my db");
$mail_id = crypto(mysqli_real_escape_string($connect_db,htmlspecialchars($_GET['em'])),'e');
$public_id = mysqli_real_escape_string($connect_db,htmlspecialchars($_GET['public']));
$active_true = true;
$check = $connect_db->prepare("SELECT active FROM enc_data WHERE enc_mail=? AND enc_pub_id=?");
$check->bind_param("ss", $mail_id, $public_id);
$active = $check->execute();
if($active[0]=="" ){
//It goes here once the code is run
}
You need to apply bind_result and then fetch
Also there is absolutely no reason to escape_string when using prepared statements as #GrumpyCrouton said
i would recommend you switch to PDO as it is more straightforward
I agree with #Akintunde that you should NOT use escaping and htmlspecialchars on query parameters. Escaping is redundant when you use query parameters. htmlspecialchars is just when you output content to HTML, not for input to SQL.
You don't necessarily have to use bind_result() for a mysqli query. You can get a result object from the prepared statement, and then use fetch methods on the result object to get successive rows.
Here's how I would write your code:
// makes mysqli throw exceptions if errors occur
mysqli_report(MYSQLI_REPORT_STRICT);
$connect_db = new mysqli("myhost", "my username", "my password", "my db");
$mail_id = $_GET['em'];
$public_id = $_GET['public'];
$active_true = true;
$sql = "SELECT active FROM enc_data WHERE enc_mail=? AND enc_pub_id=?";
$stmt = $connect_db->prepare($sql);
$stmt->bind_param("ss", $mail_id, $public_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
if($row["active"]=="" ){
//It goes here once the code is run
}
}
But in fact I would prefer to use PDO instead of mysqli, so I guess that's not really how I would write the OP's code. :-)
So I'm making my own blog scripts using MYSQL and PHP.
I had the whole 'writing the blog to a database' thing working perfectly, until I realised that if you tried to write a blog with speech marks, this would prevent the INSERT statement from working (obviously - the speechmarks were ending the SQL statement).
So I tried to use real_escape_string, and now the INSERT doesn't work even if you exclude quotes.
I tried using:
sqlstate
in order to find out the issue, and it returned "42000" - which, after googling for a little bit, refers to a syntax error, which doesn't make much sense as there is no syntax error before the use of real_escape_string.
Also, I'm now getting this error:
Call to a member function close() on a non-object in /postarticle.php on line 37
Which refers to the close() call in the ELSE statement.
Please may you help? Been going round in circles for a while. Here is my code:
<?php
$host = 'CENSORED';
$user = 'CENSORED';
$pass = 'CENSORED';
$db = 'CENSORED';
$connection = new mysqli($host,$user,$pass,$db);
$_SESSION["article"] = $_POST["article"];
$date_of_blog = getdate();
$article = ($_SESSION["article"]);
$sql1 = "SELECT * FROM `Blogs`";
$res1 = $connection->query($sql1);
$newrows = $res1->num_rows + 1;
$sql2 = "INSERT INTO Blogs(BlogID, Blog_Contents, D_O_B) VALUES ('$newrows','$article','$date_of_blog')";
$sql2 = $connection->real_escape_string($sql2);
$res2 = $connection->query($sql2);
if ($res2->num_rows == $newrows)
{
$res->close();
$connection->close();
header( 'Location: adminpanel.php' );
}
else
{
echo ($connection->sqlstate);
$connection->close();
$res->close();
}
exit();
?>
Also, on a side note, the getdate() call that I've got has never worked. In the database every blog post comes up as:
0000:00:00 00:00:00
EDIT:
Issue is now solved. Find the functional code below:
<?php
$host = 'CENSORED';
$user = 'CENSORED';
$pass = 'CENSORED';
$db = 'CENSORED';
$connection = new mysqli($host,$user,$pass,$db);
$_SESSION["article"] = $_POST["article"];
$article = ($_SESSION["article"]);
$article = $connection->real_escape_string($article);
$sql1 = "SELECT * FROM `Blogs`";
$res1 = $connection->query($sql1);
$newrows = $res1->num_rows + 1;
$sql2 = "INSERT INTO Blogs(BlogID, Blog_Contents, D_O_B) VALUES (\"$newrows\",\"$article\",CURDATE())";
$res2 = $connection->query($sql2);
if ($res2 != false)
{
header( 'Location: adminpanel.php' );
}
else
{
echo ($connection->sqlstate);
}
$connection->close();
$res->close();
exit();
?>
I'm very sorry if these questions are basic and annoy the professionals around here; I've tried to follow the guidelines and I've googled for a while etc. I just haven't found any solutions that match my issue(s).
Thankyou for your time.
There are a number issues with the code as originally posted. Chiefly, the cause of the two issues you initially identified is a misuse of mysqli::real_escape_string(). It needs to be called on each variable individually which appears in the code. So instead of calling it on the whole statement, it must be called multiple times for multiple variables like:
$article = $connection->real_escape_string($connection);
The failure of the query due to incorrect quoting (due to real_escape_string()) is the reason for the error message calling close().
As ascertained in the comments, you are using num_rows + 1 to validate that one new row has been inserted based on the previous number of rows returned. This is problematic for a few reasons. Mainly, it exposes a race condition wherein a row may be inserted from two sessions at once and one or both will fail because the expected value for $newrows doesn't match. Really BlogID should be an auto_increment column in your database. That eliminates the need for any logic around it whatsoever. You don't even need to include it in the INSERT because it will be automatically incremented.
That also completely eliminates the need for the first SELECT statement.
Substituting MySQL's native NOW() function for the date value, you can simplify the statement to:
INSERT INTO Blogs (Blog_Contents, D_O_B) VALUES ('$article', NOW())
To test success or failure of the insert, you just need to verify that its variable is not false.
Putting this together, your code can be reduced as:
if (!isset($_POST['article'])) {
// exit or handle an empty post somehow...
}
$connection = new mysqli($host,$user,$pass,$db);
$_SESSION["article"] = $_POST["article"];
// Escape $article for later use
$article = $connection->real_escape_string($_SESSION["article"]);
// Only an INSERT is needed. $article is already escaped
$sql = "INSERT INTO Blogs (Blog_Contents, D_O_B) VALUES ('$article', NOW())";
// Run the query
$res = $connection->query($sql);
// Test for failure by checking for a false value
if ($res) {
// The connection & resource closure can be omitted
// PHP will handle that automatically and implicitly.
header( 'Location: adminpanel.php' );
// Explictly exit as good practice after redirection
exit();
}
else {
// The INSERT failed. Check the error message
echo $connection->error;
}
This should bring your current code into working order. However, since you're learning this it is an excellent time to begin learning to use prepared statements via prepare()/bind_param()/execute() in MySQLi. This is a recommended best practice to prevent SQL injection, although using real_escape_string() works as long as you use it correctly and never forget.
See How can I prevent SQL injection in PHP for examples.
But it would look like:
// connection already established, etc...
// Prepare the statement using a ? placeholder for article
$stmt = $connection->prepare("INSERT INTO Blogs (Blog_Contents, D_O_B) VALUES (?, NOW())");
if ($stmt) {
// bind in the variable and execute
// Note that real_escape_string() is not needed when using
// the ? placeholder for article
$stmt->bind_param('s', $_SESSION['article']);
$stmt->execute();
// Redirect
header( 'Location: adminpanel.php' );
exit();
}
else {
echo $connection->error;
}
You need to apply the real_escape_string function to the variables not the entire SQL string.
$sql2 = "INSERT INTO Blogs(BlogID, Blog_Contents, D_O_B) VALUES ('".$connection->real_escape_string($newrows)."','".$connection->real_escape_string($article)."','".$connection->real_escape_string($date_of_blog)."')";
The purpose is to remove anything that might be misinterpreted as query functions by MySQL, but there are parts of the query that you obviously want to be interpreted as such.
I have a little login script.
function login($sql) {
try {
$fbhost = "localhost";
$fbname = "foodbank";
$fbusername = "root";
$fbpassword = "";
$DBH = new PDO("mysql:host=$fbhost;dbname=$fbname",$fbusername,$fbpassword);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$STH = $DBH->query($sql);
$STH->setFetchMode(PDO::FETCH_ASSOC);
session_start();
if ($row = $STH->fetch()) {
$_SESSION['username'] = "$row[username]";
header("Location:index.php");
}
} catch(PDOException $e) {
echo $e->getMessage();
}
}
EDITS:
index.php
$sql = "SELECT username from users where username = ". $_POST['username'] ." AND password = ". $_POST['password'] ."";
login($sql);
Changed above from insert to select query. Now I get new error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'pvtpyro' in 'where clause'
Based on your latest edit: You can't fetch results with PDO after executing an INSERT query. See here: http://www.php.net/manual/en/pdostatement.fetch.php#105682
Edit: I suppose, since the function's called "login", you want to have something like this as $sql: "SELECT password FROM users WHERE username = :username", and then iterate over the results with the while loop, and then log in the user if the password matches?
Edit2: Based on your edit to provide a SELECT query: DO NOT USE THIS QUERY. What you are doing is NOT SQL injection proof. Never ever use variables from user input (i.e. $_POST, $_GET et al) and put them unfiltered into an SQL query. Please look up the term "prepared statements" here at SO or Google.
As you can see, since you forgot to put single ticks (apostrophes) before and after the double quotes, MySQL thinks that your input refers to another column ("pvtpyro") instead of comparing the value in the column against a string. ALWAYS use the ":username", ":password" syntax (the one with prepended colons) or your queries will be unsafe and enormously dangerous to your application.
The constructor of PDO uses 2 variables which are not defined in the code you supplied - $fbhost and $fbname.
EDIT:
You're calling session_start() inside the while loop, which can cause errors. Take it out of the loop.
EDIT 2:
You should really debug the code. Either via putting die in different parts of the code, outputting some helpful information just before (which is the less preferred way) OR by using xdebug and an IDE, which will allow you to run line by line, and see the exact state of each variable and such.
If I undestand correctly, $data $STH->execute($data); should be an array, even if value is one. So, you may try replacing that query with $STH->execute(array($data));
edited:
Change your lines to this:
$data = array($_POST["username"], $_POST["password"]);
$sql = "INSERT INTO users (username, password) value (?, ?)";
$STH = $DBH->prepare($sql);
$STH->execute($data);
Seems to me that you're not connected to your database properly... I had this error earlier today and it was for that reason. Either that or you have an incorrect string
This is the code I'm using:
<?php
// Set the MySQL Configuration
$db_host = "";
$db_user = "";
$db_password = "";
$db_name = "";
$db_table = "";
// Start Connection
$db_connect = mysql_connect ($db_host, $db_user, $db_password);
// Select Database
$db_select = mysql_select_db ($db_name, $db_connect);
// Update Values in Database
$query = "UPDATE $db_table SET
age = age + 1,
land = '".$_POST['data3']."'
WHERE name = '".$_POST['data1']."'
";
// Execution MySQL query
$result = mysql_query($query) or die(mysql_error($db_connect));
//Close MySQL connection
mysql_close($db_connect);
//HTTP Response
echo " your age: age";
?>
I want to echo the value of the $age variable, but instead I always get the word "age." For example, the code should echo your age: 5 but instead it outputs your age: age
First, you'll need to run a SELECT query to retrieve the updated value of age. The query should look something like this:
"SELECT age FROM db_table_name WHERE name = ?"
Once you've obtained the result of that query, with say PDO::fetch (see my note below about PDO) and set it to the variable $age, you can output it with an echo statement:
echo "Your age: $age";
Also, please don't use mysql_* functions for new code. They are no longer maintained and the community has begun the deprecation process (see the red box). Instead, you should learn about prepared statements and use either PDO or MySQLi. If you can't decide which, this article will help you. If you care to learn, this is a good PDO tutorial.
The reason I'm not giving you the exact code for this is because it shouldn't be done with the mysql_* functions at all. Creating an SQL query with data directly from $_POST like this is extremely dangerous code to use and an incredibly bad idea all around. Never do this. You open yourself up to numerous SQL injection attacks. Even using mysql_real_escape_string is not enough. You should be using prepared statements.
UPDATE: Here is a simple example that's close to what you're asking, but using PDO and prepared statements. This is by no means a comprehensive example, since there are several ways to alter it that will still work (e.g. prepared statements allow you to execute multiple statements on the server in one statement), and I don't have a working server at the moment to test to make sure it's exactly what you need, but I hope it gets the point of across.
<?php
// Create the database connection
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 'username', 'password');
// Set PDO/MySQL to use real prepared statements instead of emulating them
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
// The UPDATE query we're going to use
$update_query = "UPDATE `db_table_name` SET age = age + 1, land = :land WHERE name = :name";
// Prepare the query
$stmt = $db->prepare($update_query);
// Bind variables to the named parameters in the query with their values from $_POST
$land = $_POST['data3'];
$name = $_POST['data1']
$stmt->bindParam(':land', $land);
$stmt->bindParam(':name', $name);
// Execute the statement on the server
$stmt->execute();
// The SELECT query we're going to use
$select_query = "SELECT age FROM `db_table_name` WHERE name = :name";
// Again, prepare the query
$stmt_select = $db->prepare($select_query);
// Bind the paramters (in this case only one) to the new statement
// $name is already set from before, so there is no need to set it again
$stmt_select->bindParam(":name", $name);
$stmt_select->execute();
/*
* With no arguments, PDO::fetchColumn() returns the first column
* in the current row of the result set. Otherwise, fetchColumn()
* takes a 0-indexed number of the column you wish to retrieve
* from the row.
*/
$age = $stmt_select->fetchColumn();
echo("Your age: $age");
?>
All of this information came directly from the PHP documentation on prepared statements and PDO::fetchColumn().
I know this particular query works, as I tested it with unprepared, procedural methods. Here it is:
$name = 'introduction';
$mysqli = new mysqli('localhost', 'user', 'pass', 'db') or die('There was a problem connecting to the database.');
$stmt = $mysqli->prepare("SELECT name, content FROM sections WHERE name = ?");
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->bind_result($content);
$stmt->fetch();
echo $content;
$stmt->close();
I realized that, since I have an id column as an index in the sections table, I needed to bind that as a result as well, given the above statement at php.net, (thanks again, Bill).
Here's the new code:
$name = 'introduction';
$mysqli = new mysqli('localhost', 'user', 'pass', 'db') or die('There was a problem connecting to the database.');
$stmt = $mysqli->prepare("SELECT name, content FROM sections WHERE name = ?");
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->bind_result($id, $name, $content);
$stmt->fetch();
echo $content;
$stmt->close();
Thanks again to all who can offer suggestions. (I'm curious: I find it hard to debug when using the OOP style of prepared statements in this way. Is there, for example, an easy way to simply see the query that was actually used?)
If I do the following, just as a quick-and-dirty example:
$name = 'introduction';
#mysql_connect('host', 'user', 'pass');
#mysql_select_db('db');
$query = "SELECT name,content FROM sections WHERE name = '$name'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_object($result)) {
$content = $row->content;
echo $content;
}
My data appears and all is well. If, however, I do the following:
$name = 'introduction';
$mysqli = new mysqli('localhost', 'user', 'pass', 'db') or die('There was a problem connecting to the database.');
$stmt = $mysqli->prepare("SELECT name, content FROM sections WHERE name = ?");
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->bind_result($name, $content);
$stmt->fetch();
echo $content;
$stmt->close();
Which I believe is correct (feel free to yell if not, of course), I get nothing. What's more, with that code, when I do an html validation (just in case), I get an internal server warning (500), which I take to be a problem with the sql code. Am I just nuts?
I don't see anything wrong with your preparation of the statement or use of parameters, but there is something wrong in your binding results:
http://php.net/manual/en/mysqli-stmt.bind-result.php says:
Note that all columns must be bound
after mysqli_stmt_execute() and prior
to calling mysqli_stmt_fetch().
(emphasis mine)
The above doc should be taken as all columns in your query, not all columns in your table.
Okay, I just tried this myself. If I omit the $name column, it gives this warning:
PHP Warning: mysqli_stmt::bind_result(): Number of bind variables doesn't
match number of fields in prepared statement in mysqli.php on line 9
PHP Stack trace:
PHP 1. {main}() /Users/bill/workspace/PHP/mysqli.php:0
PHP 2. mysqli_stmt->bind_result() /Users/bill/workspace/PHP/mysqli.php:9
But it does fetch the data.
If I bind both $name and $content to the results of the query, it works without error or warning.
So I'm forced to ask you: are you sure there's a row in the database that matches your condition? That is, where name = 'introduction'? Keep in mind that in SQL, string comparisons are case-sensitive by default.
One mistake I see people make frequently is that they connect to a different database in their PHP script than the database they use for ad hoc queries. So you need to be absolutely sure you're verifying that the data exists in the right database.
Shouldn't that be
$stmt->bind_result($name, $content);
As you select 2 columns