Hey I'm a PHP newbie setting up a "fetch, post to db, allow delete" project here and I've fetched the data, printed the DB rows and now I'm adding functionality to delete each row by '$id' but I'm running into this error.
I highlighted line 81 with astricks as well as two comment blocks above and below so you can find it easily.
Thanks for helping me learn.
<?php
// ***** MagicQuoteFix ***** //
if (get_magic_quotes_gpc())
{
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
$_POST = array_map('stripslashes_deep', $_POST);
$_GET = array_map('stripslashes_deep', $_GET);
$_COOKIE = array_map('stripslashes_deep', $_COOKIE);
$_REQUEST = array_map('stripslashes_deep', $_REQUEST);
}
// ***** Begin Connection Info ***** //
$connection = mysqli_connect('localhost', 'ijdbuser', 'ijdbpw');
if (!$connection)
{
$error = 'Unable to connect to the database server.';
include 'error.html.php';
exit();
}
if (!mysqli_set_charset($connection, 'utf8'))
{
$output = 'Unable to set database connection encoding.';
include 'output.html.php';
exit();
}
if (!mysqli_select_db($connection, 'ijdb'))
{
$error = 'Unable to locate the joke database.';
include 'error.html.php';
exit();
}
// ***** Display DB ***** //
$result = mysqli_query($connection, 'SELECT id, joketext FROM joke');
if (!$result)
{
$error = 'Error fetching jokes: ' . mysqli_error($connection);
include 'error.html.php';
exit();
}
while ($row = mysqli_fetch_array($result))
{
$jokes[] = array('id' => $row['id'], 'text' => $row['joketext']);
}
if (isset($_GET['addjoke'])) {}
else
{
include 'jokes.html.php';
}
//
// ***** Begin Add/Remove DB Options ***** //
if (isset($_GET['addjoke']))
{
include 'form.html.php';
exit();
}
if (isset($_GET['deletejoke']))
{
// LINE 81 //
******81.****** $id = mysql_real_escape_string($connection, $_POST['id']);
// LINE 81 //
$sql = "DELETE FROM joke WHERE id='$id'";
if (!mysqli_query($connection, $sql))
{
$error = 'Error deleting joke: ' . mysqli_error($connection);
include 'error.html.php';
exit();
}
//header('Location: .');
exit();
}
if (isset($_POST['joketext']))
{
$joketext = mysql_real_escape_string($connection, $_POST['joketext']);
$sql = 'INSERT INTO joke SET
joketext="' . $_POST['joketext'] . '",
jokedate=CURDATE()';
if (!mysqli_query($connection, $sql))
{
$error = 'Error adding submitted joke: ' . mysqli_error($connection);
include 'error.html.php';
exit();
}
header('Location: .');
exit();
}
?>
Your problem is with this line (the one that has the error)
$id = mysql_real_escape_string($connection, $_POST['id']);
instead it should be
$id = mysqli_real_escape_string($connection, $_POST['id']);
You are mostly handling things as mysqli_ functions (which is the better way), however in this case you are a using mysql_ connection for your escape. Don't use this, it is deprecated, and soon will no longer work because it is vulnerable to sql injection The syntax is different for each. You have the order set up correctly, but have a typo (since everything else is using mysqli. Also Do not use magic quotes! Dangerous and deprecated
Note, there are better ways of handling queries, and you wouldn't need to escape it at all if you use prepared statements (and also not need to worry about whether your variable needs quoting or not). These are just as secure (some would say more so, so you don't need to remember to escape all your variables), and have the advantage of being much faster for larger queries.
For instance, see below. Here's an example using your delete statement:
First connect to the database using an object oriented style like so:
$connection = new mysqli("localhost", "user", "password", "database");
(note it's a good idea to store your database variables in a separate script, and then call it as a require_once include)
Then, handle your query like this
$sql = $connection->prepare("DELETE FROM joke WHERE id=?");
$sql->bind_param("i", $id);
$sql->execute();
$sql->close();
Note that the "i" is specifying that this is an integer (as most ids are), however if this variable were a string, you would call specify this as "s"
for more information on mysqli prepared statements, take a look here: mysqli prepared statements
You are using mysqli to query to your database therefore you need to use mysqli_real_escape_string() instead of mysql_real_escape_string() and also remove the first argument that you have passed to the function which is $connection. This is a very common mistake every developer makes.
Therefore you can replace line 81 by
$id = mysqli_real_escape_string($_POST['id']);
similar situation:
please see:www.westwoodpavillion/ecommerce/admin_area/login.php (source code)
include("includes/db.php");
if(isset($_POST['login'])){
$email = mysqli_real_escape_string($con, $_POST['email']);
$pass = mysqli_real_escape_string($con, $_POST['password']);
it works for me....eloisa..Thank YOu very much.
change:
if (!ini_get("safe_mode")) $success = mail($to, $subject, $message, $headers, $params);
to:
if (!ini_get("safe_mode")) $success = #mail($to, $subject, $message, $headers, $params);
works like magic.. just change your mail($to... and the rest to the
specified above)
Related
I have written the following function in PHP that has a mysqli_query in it that runs without any errors or exceptions. However, the INSERT INTO statement or $insert variable doesn't seem to be working as expected and I can't figure it out. I realize that posting only a portion of the code might make it difficult to ascertain why it is not working, but I am really looking for confirmation that there are no errors in this function.
Do I need to utilize mysqli_real_escape_string for every url provided? I tried altering $website to $_website to account for this, but it returned nothing.
Just really trying to figure out if there's anything I'm doing wrong here that's prevent the SQL query to work. It returns no error which is making it hard to debug. Thanks in advance!
$jp = mysqli_connect("localhost", "myuser", "password", "mydatabase");
if (!$jp) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
function create_distributor( $new_user_id ) {
$errors = new WP_Error();
$error=false;
$errorMsg='';
$logo=true;
$name=addslashes(htmlentities($_REQUEST['name']));
$contact=addslashes(htmlentities($_REQUEST['contact_info']));
$user_info = get_userdata( $new_user_id );
$website = $_POST['website'];
if (stripos($website, "http://") !== 0) //doesn't start with http:// ? , then add it
$website = "http://" . $website;
// $_website = mysqli_real_escape_string($jp, $website); // THIS DOESNT RETURN ANYTHING
$subdir = $user_info->user_nicename; // use nicename because user_login is obfuscated as unverified
$distribpath = 'http://ghq.com/dhdq/'.$subdir;
$ga_code = 'UA-15331916-1'; //default GA code
$logo = 'http://ghq.com/wp-content/themes/CAG/img/ghlogo.jpg'; //default png logo
if(!isset($_REQUEST['name']) || $_REQUEST['name']=='')
{
$error=true;
$errors->add('Distributor Name is required', __('<strong>ERROR</strong>:Distrubutor\'s name was not provided.'));
}
if($error)
{
return($errorMsg);
}
$insert="INSERT INTO distributor (id, name, contact, logo, path, subdir, website, ga_code) VALUES ('".$new_user_id."','".$name."','".$contact."','".$logo."','".$distribpath."','".$subdir."','".$website."','".$ga_code."')";
// var_dump($insert);
// The var_dump print out above is the following SQL Command which if copied and pasted
in phpmyadmin works fine: string(252) "INSERT INTO distributor (id, name, contact,
logo, path, subdir, website, ga_code) VALUES ('1748','test24','','http://ghq.com/wp-content/themes/CAG/img/ghlogo.jpg',
'http://ghq.com/dhdq/test24','test24','','UA-15331916-1')"
mysqli_query($jp, $insert);
if ( false===$insert ) {
printf("error: %s\n", mysqli_error($jp));
}
else {
echo 'done.';
}
if($error)
{
return $errors;
}
else
{
return($id);
}
}
The problem I can see straight off is you are checking your sql variable instead of the query result.
mysqli_query($jp, $insert);
if ( false===$insert ) {
printf("error: %s\n", mysqli_error($jp));
}
else {
echo 'done.';
}
Try changing it to:
$result = mysqli_query($jp, $insert);
if (!$result) {
printf("error: %s\n", mysqli_error($jp));
}else {
echo 'done.';
}
Also whats $jp? it doesn't look like you have assigned it anything. Make sure this is the variable that has your mysqli_connect on it. With your question regarding mysqli_real_escape_string, you should really be utilizing mysqli prepared statements as well. All user input should be sanitized.
Can someone point the fault in this code? I'm unable to update data to the database. We are sending a text message to the server, and this file here decodes and sets it in the database. But this case over here is not working for some reason. I checked and tried to troubleshoot, but couldn't find a problem.
case 23:
// Gather Variables
$Message = preg_replace("/\s+/","%20", $Message);
$UnixTime = time();
$cycle = explode(":", $Message);
$machine_press = $cycle[0];
$machine_pct_full = $machine_press/20;
$machine_cycles_return = $cycle[1];
$machine_cycles_total = $cycle[2];
// Build SQL Statement to update static values in the machine table
$sql = "UPDATE `machines` SET `machine_last_run`=".$UnixTime.",`machine_press`=".$machine_press.",`machine_pct_full`=".$machine_pct_full.",`machine_cycles_return`=".$machine_cycles_return.",`machine_cycles_total`=".$machine_cycles_total." WHERE `machine_serial`='$MachSerial'";
// Performs the $sql query on the server to update the values
if ($conn->query($sql) === TRUE) {
// echo 'Entry saved successfully<br>';
} else {
echo 'Error: '. $conn->error;
}
$sql = "INSERT INTO `cycles` (`cycle_sequence`,`cycle_timestamp`,`cycle_did`,`cycle_serial`,`cycle_03_INT`,`cycle_14_INT`,`cycle_15_INT`,`cycle_18_INT`)";
$sql = $sql . "VALUES ($SeqNum,$UnixTime,'$siteDID','$MachSerial',$machine_press,$machine_cycles_total,$machine_cycles_return,$machine_pct_full)";
// Performs the $sql query on the server to insert the values
if ($conn->query($sql) === TRUE) {
// echo 'Entry saved successfully<br>';
} else {
echo 'Error: '. $conn->error;
}
break;
More information is required to help you out with your issue.
First, to display errors, edit the index.php file in your Codeigniter
project, update where it says
define('ENVIRONMENT', 'production');
to
define('ENVIRONMENT', 'development');
Then you'll see exactly what the problem is. That way you can provide the information needed to help you.
I just saw that you are inserting strings when not wrapping them in apostrophe '. So you queries should be:
$sql = "UPDATE `machines` SET `machine_last_run`='".$UnixTime."',`machine_press`='".$machine_press."',`machine_pct_full`='".$machine_pct_full."',`machine_cycles_return`='".$machine_cycles_return."',`machine_cycles_total`='".$machine_cycles_total."' WHERE `machine_serial`='$MachSerial'";
and
$sql = "INSERT INTO `cycles` (`cycle_sequence`,`cycle_timestamp`,`cycle_did`,`cycle_serial`,`cycle_03_INT`,`cycle_14_INT`,`cycle_15_INT`,`cycle_18_INT`)";
$sql = $sql . " VALUES ('$SeqNum','$UnixTime','$siteDID','$MachSerial','$machine_press','$machine_cycles_total','$machine_cycles_return','$machine_pct_full')";
For any type of unknown problems I can recommend turning on PHP and SQL errors and use a tool called postman that i use to test my apis. You can mimic requests with any method, headers and parameters and send an "sms" just like your provider or whatever does to your API. You can then see the errors your application throws.
EDIT
I tested your script using a fixed version with ' and db.
$Message = "value1:value2:value3";
$MachSerial = "someSerial";
$SeqNum = "someSeqNo";
$siteDID = "someDID";
$pdo = new PDO('mysql:host=someHost;dbname=someDb', 'someUser', 'somePass');
// Gather Variables
$Message = preg_replace("/\s+/","%20", $Message);
$UnixTime = time();
$cycle = explode(":", $Message);
$machine_press = $cycle[0];
$machine_pct_full = (int)$machine_press/20; // <----- Note the casting to int. Else a warning is thrown.
$machine_cycles_return = $cycle[1];
$machine_cycles_total = $cycle[2];
// Build SQL Statement to update static values in the machine table
$sql = "UPDATE `machines` SET `machine_last_run`='$UnixTime',`machine_press`='$machine_press',`machine_pct_full`='$machine_pct_full',`machine_cycles_return`='$machine_cycles_return',`machine_cycles_total`='$machine_cycles_total' WHERE `machine_serial`='$MachSerial'";
try {
$pdo->query($sql);
} catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}
$sql = "INSERT INTO `cycles` (`cycle_sequence`,`cycle_timestamp`,`cycle_did`,`cycle_serial`,`cycle_03_INT`,`cycle_14_INT`,`cycle_15_INT`,`cycle_18_INT`)";
$sql = $sql . "VALUES ('$SeqNum','$UnixTime','$siteDID','$MachSerial','$machine_press','$machine_cycles_total','$machine_cycles_return','$machine_pct_full')";
try {
$pdo->query($sql);
} catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}
It totally works. Got every cycle inserted and machines updated. Before i fixed it by adding wrapping ' i got plenty of errors.
Alright so this is the solution:
i replaced the line:
$Message = preg_replace("/\s+/","%20", $Message);
with:
$Message = preg_replace("/\s+/","", $Message);
This removes all blank spaces in my text message and makes it a single string before breaking and assigning it to different tables in the database.
I understand this wasnt really a problem with the script and no one around would have known the actual problem before answering. and thats why i am posting the solution just to update the team involved here.
I hope that someone sharp on PHP can help me with problem, that i really don't understand.
I have 2 scripts. 1: test.php 2:functions.php.
I created a little test where i called a functions in functions.php frim test.php and it work fine. I got a return and it was as expected. I also have a third script register.php where i have a query to a database and that work fine.
So I wanted the query to work as a function written in functions.php
Problem: It seems that it won't make the database query! But there is createt a connection
If I move the exactly same query to test.php, it works! Is there some kind of speciel reason for this? I quit new to php, but knows a little about Java, C, JavaScript, Python.
I have checked that my include / require is all in order.
1: test.php:
<?php
require 'includes/functions.php';
$name = 'testuser';
$_ok = 0;
$_ok = check_username ($name);
printf ( 'Navn i database?: ' . $_ok . '<br>' );
?>
2: functions.php:
<?php
require 'includes/db_connect.php';
// Check connection
if (! $mysqli) {
die ( 'mysqli_init_failed' );
}
if (mysqli_connect_errno ()) {
die ( 'Failed to connect to the Database, Sorry..! errorcode: ' .
mysqli_connect_errno() . ' <br>' . 'Error Type: ' . mysqli_connect_error () );
}
if ($debug_mode_c) {
print ('Connection Established: ' . mysqli_get_host_info ( $mysqli ) . '<br>') ;
print ('session_id: ' . session_id ()) . '<br>';
}
// Set HTML-Header to utf-8.
header ( 'Content Type: text/html; charset=UTF-8' );
// Functions
function check_username($_ok) {
$name = 'testuser';
$prep_stmt = "SELECT username FROM customs WHERE username=? LIMIT 1 ";
$stmt = mysqli_prepare($mysqli, $prep_stmt);
mysqli_stmt_bind_param($stmt, 's', $name);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $name_db);
mysqli_stmt_fetch($stmt);
if ($name == $name_db) {
echo "hello";
mysqli_close ($stmt);
$_ok = 0;
} else {
$name = '';
$_ok = 2;
}
mysqli_free_result($stmt);
mysqli_close($stmt);
return $_ok;
}
Maybe found the reason for no query.
Apparently the include script containing establish connection, is not loaded as the function is called in functions.php.
When the query code is in test.php, that include functions.php, all code is read, also the connection for the database.
But even if include 'db_connect' is inside function, it won't work !?! :-(
There is nothing like noquery() function in PHP. please just check it in the include file of the database connection. you will find a user defined function in your include file of the database connection.
I have a file called database.php which contains the following:
<?php
// Database connectivity stuff
$host = "localhost"; // Hostname for the database. Usually localhost
$username = "root"; // Username used to connect to the database
$password = "root"; // Password for the username used to connect to the database
$database = "blog"; // The database used
// Connect to the database using mysqli_connect
$connection = mysqli_connect($host, $username, $password, $database);
// Check the connection for errors
if (mysqli_connect_errno($connection)) {
// Stop the whole page from loading if errors occur
die("<br />Could not connect to the database. Please check the settings and try again.") . mysqli_connect_error() . mysqli_connect_errno();
}
?>
I have a new file called functions.php which contains the following:
<?php
// Functions file for the system
function add_post($user_id, $body) {
$post = "INSERT INTO posts (user_id, body, stamp) VALUES ($user_id, $body, now())";
$insert_post = "mysqli_query($connection, $post)";
}
?>
And an insert post php page (newPost.php) which contains the following:
<?php
// Define the user id and get the post from the form
$user_id = 1; // User ID hard coded for testing purposes
$body = substr($_POST['body'],0,200);
// Insert the post in the database using the add_post() function
if (isset($user_id, $body) && ($_SERVER['REQUEST_METHOD'] == 'POST')) {
// Insert the post in the database if conditions were met
add_post($user_id, $body);
}
// If the conditions were not met, display an error
else {
die("The post was not added. Something went wrong. Please try again later");
}
?>
When I try to post some text I get the following error:
Notice: Undefined variable: connection in /Applications/MAMP/htdocs/blog/includes/functions.php on line 7
What am I doing wrong here? isn't $connection supposed to be passed as i used require(); in my newPost.php file?
This is totally wrong:
$insert_post = "mysqli_query($connection, $post)";
^--- ^--
You're not executing your query. You're defining a string which happens to contain some text that LOOKS like a query call. Remove the quotes...
It's a variable scope issue. $connection is not available to add_post() unless you pass it as a parameter:
function add_post($user_id, $body, $connection) {
$post = "INSERT INTO posts (user_id, body, stamp) VALUES ($user_id, $body, now())";
$insert_post = mysqli_query($connection, $post);
}
You can also use the global keyword but that is generally considered a bad practice and should be avoided.
The above answers should get it to work for you, however consider using mysqli prepared statements instead of mysqli_query. Prepared statements are safer and protect you from sql injection through user input.
I'm opening myself to honest critizism and sugggestions.
The issue is with the function $_POST[void] being valid after a redirect. Quotes.add.php is a form that directs to quotes.done.php, submitted to mysql and redirected back to quotes.add.php with an echo $msg and reset to be filled out again.
Is header(); the best method in this case?
quotes.done.php
else{
include 'data.php';
$query = "INSERT INTO quotes (`id`, `quotes`, `artist`, `date`) VALUES ('null', '$_POST[text]', '$_POST[artist]', 'null')";
$result = mysql_query($query) or die (mysql_error());
$_POST['void'] = "$_POST[artist] Was Added Successfully to database";
unset ($_POST['artist']);
//var_dump($_POST['void']);
//exit;
header ("location: quotes.add.php");
exit;
}
quotes.add.php
if (isset($_POST['void'])) {
$msg = $_POST['void'];
}else{
$msg = "Please insert artist";
}
If you do a redirect i think you have to use $_SESSION.
I'd do:
session_start();
$_SESSION['msg'] = "$_POST[artist] Was Added Successfully to database";
header ("location: quotes.add.php");
exit;
and then
session_start();
if (isset($_SESSION['msg'])) {
$msg = $_SESSION['msg'];
unset($_SESSION['msg'];
}else{
$msg = "Please insert artist";
}
This is the clean, proper, and secure way to do it:
quotes.done.php
<?php
else{
include 'data.php';
// escape the input, to avoid SQL injection
$text = mysql_real_escape_string($_POST['text']);
$artist = mysql_real_escape_string($_POST['artist']);
$query = "INSERT INTO quotes (`id`, `quotes`, `artist`, `date`) VALUES ('null', '{$text}', '{$artist}', 'null')";
$result = mysql_query($query);
// always set your variables to a default value
$success = false;
// did the query execute successfully?
if($result){
$success = true;
}
header('Location: quotes.add.php?result=addedquote&artist='.urlencode($_POST['artist']).'&success='.urlencode($success));
exit;
}
?>
quotes.add.php
<?php
$msg = '';
if(isset($_GET['result']) && $_GET['result'] == 'addedquote') {
$artist = htmlentities(urldecode($_GET['artist']), ENT_QUOTES, 'UTF-8', false);
$success = (bool) urldecode($_GET['success']);
if($success){
$msg = "$artist Was Added Successfully to database";
} else{
$msg = "Failed to Add $artist to database";
}
} else{
$msg = "Please insert artist";
}
?>
A couple of things for you to note here:
If you are not using a wrapper for running your db queries with prepared parameterized statements, you should use at least mysql_real_escape_string() to remove the nasty stuff in order to prevent SQL injection.
As noted by others header() will do a GET request, hence why you are not getting the $_POST[void] on the page you are redirecting. That's why you will use variables on your url to transfer them to the redirected page, and then fetch them with $_GET.
$_POST[somename] and $_POST['somename'] are two different things. They will work, because PHP will try to see if there is a constant named somename, if there isn't one, you are lucky, but if there is one, then all sky falls down.
If you want to keep the $_POST variables, don't redirect. A redirect causes the client's browser to re-request the page with only $_GET params.
Save the record to the database. Get the new record ID, redirect to a page and pass in the ID. Then use the ID to fetch and display the record.
Redirecting will not POST a value to the page. You could use session or GET.
$message = urlencode("$_POST[artist] Was Added Successfully to database");
header ("location: quotes.add.php?message=" . $message);
On your quotes.add.php page
echo $_GET['message'];