My PHP script was written to send email and SMS when some new information is entered in the front end to members in database. However the email code and SMS code are working individually, but when put together the code is not getting executed.
The code in fact skipped. I tried making a deliberate error in the called function but it did not recognize it. Why?
<?php
error_reporting(E_ALL ^ E_NOTICE);
define('INCLUDE_CHECK', true);
require 'functions.php';
include ("generatesms.php");
include ("class.phpmailer.php");
include ("../sendsmsV3.5/sendsmsV3.5/CurlProcess.php");
include ("../sendsmsV3.5/sendsmsV3.5/Way2Sms.php");
include ("class.smtp.php");
// The above files can be included only if INCLUDE_CHECK is defined
$host = "localhost"; // Host name
$username = "root"; // Mysql username
$password = ""; // Mysql password
$db_name = "test"; // Database name
$tbl_name = "mails"; // Table name
// Connect to server and select database.
mysql_connect($host, $username, $password) or die("cannot connect");
mysql_select_db($db_name)or die("cannot select DB");
// Get values from form
$subject = $_POST['subject'];
$email = $_POST['email'];
$phone = $_POST['phone'];
//$dept = $_POST['dept'];
$content = $_POST['content'];
$month = $_POST['birthday-mm'];
$day = $_POST['birthday-dd'];
$year = $_POST['birthday-yyyy'];
$date_eve = "$year-$month-$day";
$dept = $_POST['branch'];
if (empty($dept)) {
echo("You didn't select any DEPEARTMENTS.");
} else {
$N = count($dept);
for($i=0; $i < $N; $i++) {
echo $dept[$i]; echo "<br>";
$dep = $dept[$i];
// Insert data into mysql
$sql = "INSERT INTO $tbl_name(subject, body, dept, phone, email, date_eve) VALUES ('$subject', '$content', '$dep', '$phone', '$email', '$date_eve')";
$result = mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if ($result) {
echo "Successful";
echo "<BR>";
newssender($dept, $content, $subject);
generatesms($dept,$date_eve,$subject);
echo "<a href='index.php'>Back to main page</a>";
} else {
echo "ERROR";
}
}
}
// close connection
mysql_close();
Firstly you have a big problem with all of your SQL. You shouldn't use mysql_* functions as they are deprecated and you're not sanitizing your inputs leaving you exposed to vulnerabilities. (http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php)
If you could pose your newssender() function code I can give you a detailed/specific answer but in the meantime I will give a general solution that goes through some debugging processes for other users.
if you have code like this:
myFunction1();
myFunction2();
and myFunction1() is run but myFunction2() is NOT, you can try commenting out // myFunction1() (which it sounds like you did) and at that point if myFunction2() runs then obviously the problem resides in myFunction1(). Here are the things to look for:
Fatal errors. Make sure you have errors and notices turned on to find syntax or other errors in your code
Look for any die or exit that may exist in your code. Those end the script and no more code is executed.
A quick way to test #2 is to do this:
myFunction1();
echo 'I made it here!';
If you don't see "I made it here!" on your screen then obviously the code didn't get that far, meaning the code ended before it returned from myFunction1()
I hope that helps!
Related
If I want to add content to the table using "INSERT INTO", I don't get an error message and the table is not filled. I'm new with PHP. explanations would be nice. The database runs on XAMPP.
I don't know what to try. I've already used another table, but it doesn't work. The user should have full access to the table. The names also match.
<?php
$username = $_POST["username"];
$passwort = $_POST["passwort"];
$mail = $_POST["mail"];
$passwort2 = $_POST["passwort2"];
$pass = sha1($passwort);
$db = mysqli_connect("localhost", "phptest1", "o84XM5wxo65QBjkF", "phptest1");
if($passwort == $passwort2) {
echo "Password is correct.";
$db = "INSERT INTO user (Username, Mail, Password) VALUES ('$username', '$mail', '$pass')";
} else if(!($passwort == $passwot2)) {
echo "Password is not correct";
} ?>
The variable $db actually contains information about the connection. You cannot insert a query into your database the way you are trying to
You can use $db (in your case) in order to check whether the connection has been correctly established or not and then if everything works correctly you can user mysqli_query() to inject the query into your database.
You can do it like so:
<?php
if(isset($_POST['submit'])){ //You have to check if your submit button is pressed
$username = $_POST["username"];
$passwort = $_POST["passwort"];
$mail = $_POST["mail"];
$passwort2 = $_POST["passwort2"];
$pass = sha1($passwort);
$db = mysqli_connect("localhost", "phptest1", "o84XM5wxo65QBjkF", "phptest1");
if(!$db){
die('Connection could not be established! Check provided information');
}
if($passwort == $passwort2) {
echo "Password is correct.Inserting query now";
$query = "INSERT INTO user (Username, Mail, Password) VALUES ('$username', '$mail', '$pass')";
$result = mysqli_query($db, $query); //keep $result for debugging purposes.
} else {
die("Password is not correct");
} //no need for else if as there are only 2 conditions.
if(!$result){ //check if query was successful.
die('Query Error');
}
echo "Query Updated successfully";
}
?>
This code is really simplistic and for testing purposes only.
I just wanted to show you the way you can send queries to your database. You better use other encryption techniques i.e. crypt() and of course functions like mysqli_real_escape_string() when retrieving data from users, in order to avoid potential injection attacks.
Check this post for more info about preventing injections.
Hope that helps.
Here's the PHP code:
<?php
$servername = "***";
$username = "*****";
$password = "*****";
$database = "*****";
try {
$conn = new PDO('mysql:host='.$servername.';dbname='.$database, $username, $password);
console.log('yes!');
}
catch(PDOException $e) {
print "Error!:" . $e->getMessage(). "<br/>";
die();
}
if (isset($_POST['submit']))
{
//$name = $_POST['name'];
//$day = $_POST['day'];
//$acctName = $_POST['acctName'];
//$acctType = $_POST['acctType'];
//$location = $_POST['location'];
//$prospect = $_POST['prospect'];
//$notes = $_POST['notes'];
$name = 'sally sue';
$day = 'monday';
$acctName = 'Account Uno';
$acctType = 'Cold Call';
$location = 'Location';
$prospect = 'Prospect';
$notes = 'These are notes! Notey notey notes';
$order = "INSERT INTO `schedule`(`id`, `name`, `day`, `acctName`, `acctType`, `location`, `prospect`, `notes`) VALUES ('$name', '$day', '$acctName', '$acctType', '$location', '$prospect', '$notes')";
$stmt = $conn->prepare($order);
$stmt->execute();
}
?>
Here's the deal. I have an HTML form that I use jQuery to grab the variables, and AJAX to post the form to this PHP file. I feel confident that everything is fine up to the point where it gets to the PHP file.
I commented out the POST variables and hard-coded my own to make it a little simpler. I'm not getting a 500 Internal Server Error. I've ran my code through a PHP syntax validator (and fixed a billion errors haha). Obviously I'm still doing something wrong, but I cannot find it for the life of me. I'm hoping that someone here has some insight?
EDIT: Also, the username, password, database, and table name are ALL correct. I've double checked them several times. The only thing I'm not sure of is the server name, which is 'localhost' since the DB is on the same server as this web page.
EDIT 2: I've changed the MySql insert statement back to the original, which had the back ticks. I copied it straight from phpMyAdmin console on the server which it resides. It was that way originally, but I changed it due to desperation. It still is not updating my database. Any further ideas?
Thanks in advance!
I have an assignment where I have to make a registration page in php.... I just want to keep things simple so making the form work is all I'm aiming for. I am aware of the vulnerability of sql injections/plaintext, but that's the last of my worries for now since it's a class assignment.
The script below works as far as inserting new users/passwords, but if there's an existing user, the page is blank and doesn't give a warning. I'm looking for help in giving the error "Sorry, this user already exists" shown on the screen (or something).
Thanks :D.
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', '////////');
define('DB_USER','/////////');
define('DB_PASSWORD','///////////');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
function NewUser() { $userName = $_POST['user']; $password = $_POST['pass']; $query = "INSERT INTO UserName (userName,pass) VALUES ('$userName','$password')"; $data = mysql_query ($query)or die(mysql_error()); if($data) { echo "YOUR REGISTRATION IS COMPLETED..."; } } function SignUp() { if(!empty($_POST['user'])) {
$query = mysql_query("SELECT * FROM UserName WHERE userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
if(!$row = mysql_fetch_array($query)))
{ newuser(); }
else { echo "SORRY...YOU ARE ALREADY REGISTERED USER..."; } } } if(isset($_POST['submit'])) { SignUp(); } ?>
First, Its really important check your php_error_log or Add error reporting into the TOP of your file.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
There is an extra closing parenthesis and you are calling an undefined function.
Assuming these are the errors, fix then with:
if(!$row = mysql_fetch_array($query)) {
NewUser();
}
else {
echo "SORRY...YOU ARE ALREADY REGISTERED USER...";
}
Also, consider using mysqli with prepared statements, or PDO with prepared statements, they're much safer.
Hope it helps you.
Thanks to #bcesars for the extra parenthesis fix. I thought there was something odd with the count.
After, I came up with a problem where the "This user already exists" error pops up ONLY if the user and pass matches the same one in the database. If I use a different password, the info is still inserted into the database.
Solution:
Remove
AND pass = '$_POST[pass]'
from
$query = mysql_query("SELECT * FROM UserName WHERE userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
So far it works. I'm still new into this whole database/php thing so thanks for bearing with me ♥
I have a simple user registration form and external connection script with some strange results.
The page register.php shows the form fine, however seems to display my entire connection string before the form?
It then throws up errors in relation to my connection variable '$dbcon' (I have commented the line at which this happens) Here is my register.php code:
<?php
session_start();
require "connect.php";
if (isset($_SESSION['username'])){
header("location: members.php");
}
if (isset($_POST['submit']))
{
$user = $_POST['user'];
$pass = $_POST['pass'];
$rpass = $_POST['rpass'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
if ($user == "" || $pass == "" || $rpass == "")
{
echo "Please fill all fields";
}
else
{
if ($pass != $rpass)
{
echo "Passwords do not match";
}
else
{
//This is where the errors are found
$query = mysqli_query($dbcon, "SELECT * FROM users WHERE username = '$user' ") or die ("Cannot query table");
$row = mysqli_num_rows($query);
if($row == 1)
{
echo "This username is already taken";
}
else
{
$add = mysqli_query($dbcon, "INSERT INTO users (id, firstname, lastname, username, password, admin) VALUES
(null, '$fname', '$lname', '$user', '$pass', '$admin') ") or die ("Cant insert data");
echo "Successfully added user!";
}
}
}
}
?>
And here is my connection file 'connect.php' (the $dbcon string is the one that prints out??)
$server = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'bodgett';
$dbcon = mysqli_connect($server, $user, $pass, $dbname)or die("Can not connect to Server.");
Specifically, the error is 'Notice: Undefined variable: dbcon in C:\webserver...\register2.php'
Can anyone suggest why is doesn't recognize this variable?
Probably a wrong filename (maybe file isn't called connect.php) OR wrong file extension? (html instead of .php)
I just copied all your code, and it works for me. Aswell I don't see php start and closing Tags.
I agree with #Xatenev. Also, you may want to consider using PDO for your database interactions, it's the most secure way. I found this very helpful: http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
Sorry if this seems irrelevant, just trying to help.
The connection file 'connect.php' is not enclosed within tags, hence not usable and explains why the text was simply printing out at the top of the page.
Check if mysqli extension is enabled
the code that generates $dbcon is inside a class or inside some function?
If yes, maybe you need to return or call it properly.
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.