Php / MySQL Insert record query error? - php

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.

Related

HTTP Error 500 when trying to execucute INSERT INTO sql query

I'm fairly new to php and SQL and just can't figure out the problem. Note that this is a school project, therefore the vulnerability to SQL Injections and saving the blank passwords are nothing to worry about.
After the User filled out the Login-form, he's redirected to this page:
[Some html]
<?php
if(isset($_POST['submit']))
{
ConnectSQL();
}
//Retrieve POSTed Login information
$Username = htmlspecialchars($_POST['RegUsername']);
$Email = htmlspecialchars($_POST['RegEmail']);
$Password = htmlspecialchars($_POST['RegPassword']);
function ConnectSQL() {
// SQL Server Extension Sample Code:
// (ConnectionInfo, obviously it's there in the real file)
$conn = sqlsrv_connect($serverName, $connectionInfo);
// PHP Data Objects(PDO) Sample Code:
try {
$conn = new PDO('sqlsrv:server = tcp:xxx.database.windows.net,1433; Database = userdb', 'arechon', '{NotTheRealPassword}');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Successfully connected to SQL Server and DB";
Register();
}
catch (PDOException $e) {
print('Error connecting to SQL Server.');
die(print_r($e));
}
}
function Register($Username, $Email, $Password) {
$regquery = "INSERT INTO dbo.Users (Username, Email, Password) VALUES ('UsernameTest', 'EmailTest', 'PasswordTest')";
$conn->query($regquery);
echo '<script type="text/javascript">window.open("http://xxx.azurewebsites.net/Login.html", "_self");</script>';
The Code always seems to stop at $conn->query($regquery); and doesn't return any error messages. Sometimes it just stops, when I slightly modify the Code (e.g. replacing $conn->query($regquery); with $conn->exec($regquery); or using " instead of ') I get a HTTP500 error.
I found some similiar questions here on stackoverflow as well as on other plattforms, but none of the provided answers could solve this error. Note that I use SQL and NOT MySQL (though it wouldn't be a lot of work to change that if you think that could solve my problem).

PHP mysqli insert return error invalid request

I've been having a bit of trouble with my PHP code.
I'm trying to insert a new row in table gebruikers.
I'm using a JSON API to post the data from my C# Android app to the server.
running the code returns an invalid request error.
PHP:
function registerUser($api_data)
{
// connection
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$database = "test";
$mysqli = new mysqli($servername, $username, $password, $database);
//check connection
if(mysqli_connect_errno())
{
API_Response(true, 'connection error');
}
$register_data = json_decode($api_data);
$leerlingnummer = intval($register_data->leerlingnummer); //passed as string, int in database
$wachtwoord = $register_data->wachtwoord; //string
$email = $register_data->email; //string
$result = $mysqli->query("INSERT INTO `gebruikers` (`Leerlingnummer`, `Wachtwoord`, `Email`) VALUES ({$leerlingnummer}, {$wachtwoord}, {$email})");
if ($result == false)
{
API_Response(true, "{$mysqli->error}");
}
else
{
API_Response(false, 'SUCCESS');
}
$mysqli->close();
}
database is looking as follows:
database layout
I've never felt this stupid before, but the error came from the fact that I was still referencing to an older .php file. I was so focussed on the PHP script that I didn't notice this error in my app before.
the quotes advised by Sean and fuso were needed later on though so thanks for that.
Problem solved, sorry for wasting some of your time :/
You should quote your data in the insert query.
... VALUES ('{$email}','{$other}')

Trying to insert data into a database using PHP / Mysqli

I'm trying to execute an Insert query to write data into a Database. I'm using Mysqli and PHP.
The code looks OK for me. However, every time I go to the webpage to check if the form works, the query gets executed an a new row is created in the DB (empty).
I'm pretty sure there is something wrong with the last if statement. Could you advise?
BTW, the snippet is only for the PHP to execute the sql query, since the form is working just fine.
Thanks!
$servername = "localhost";
$username = "root";
$password = "mysqlpassword";
$dbname = "bowieDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$album = $_POST['album'];
$relyear = $_POST['relyear'];
$label = $_POST['label'];
$chart = $_POST['chart'];
$track1 = $_POST['track1'];
$track2 = $_POST['track2'];
$track3 = $_POST['track3'];
$track4 = $_POST['track4'];
$track5 = $_POST['track5'];
$sql = "INSERT INTO Albums (album, relyear, label, chart, track1, track2, track3, track4, track5)
VALUES ('$album', '$relyear', '$label', '$chart', '$track1', '$track2', '$track3', '$track4', '$track5')";
$result = mysqli_query($conn, $sql);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
You are mixing Procedural and Object Orientated SQL interactions.
This is Procedural:
$result = mysqli_query($conn, $sql);
This is Object Orientated:
$conn->query($sql)
You can not use both with the same connection details, you should do one or the other throughout your code. The best one to use is Object Orientated approach, so rework the Procedural code to:
$result = $conn->query($sql);
if ($result) {
...
So actually you can simply remove the line starting $result = ... and let the IF statement query you already have handle itself.
Other notes:
Use MySQL error feedback such as checking if(!empty($conn->error)){print $conn->error;} after SQL statements. See example code below...
Use the following PHP error feedback too, set at the very top of your PHP page:
...
error_reporting(E_ALL);
ini_set('display_errors',0);
ini_set('log_errors',1);
you need to read up and be aware of SQL injection that can destory your database should someone POST data that also happens to be MySQL commands such as DROP.
Code for Comment:
if ($_SERVER['REQUEST_METHOD'] == "POST") {
//run SQL query you already have coded and assume
// that the form has been filled in.
$result = $conn->query($sql);
if ($result) {
//all ok
}
if(!empty($conn->error)) {
print "SQL Error: ".$conn->error;
}
}
use
1. if(isset($_POST['Submit'])){//your code here }
and
2. if($result){...
if you are using procedural method

My if / else statement doesnt work for my custom php login script

Somehow my conditional simply doesnt work. Once I click the button on my login form which is set to "post" and has the action defined as the below login script I only get directed to the script but not redirected as defined in my conditional statement. What is wrong with my code?
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$database = "project";
$connection = mysqli_connect($servername, $username, $password, $database) or exit(header("location:maintenance.php"));
function login_check() {
global $connection;
$name = $_POST['name'];
$password = $_POST['password'];
$prepared = mysqli_stmt_init($connection);
$request = mysqli_stmt_prepare($prepared, "SELECT id FROM members WHERE name = ? AND password = ?");
mysqli_stmt_bind_param($prepared, "ss", $name, $password);
$result= mysqli_stmt_bind_result($request);
$rows_counter = mysqli_num_rows($result);
mysqli_stmt_close($prepared);
if ($rows_counter > 0) {
$_SESSION['member'] = $name;
header("location:../../success.php");
}
else {
header("location:../../relogin.php");
}
}
Here is my input and approach to your code.
First of all before writing a solution and tell to much, it is always a good practice to make step by step code troubleshooting.
Before going and building a complete login system and put if statement or make prepare statement with inputs etc.
Make your solution in small working chops and put the puzzle together.
You question was focused on if statement and most of the help and answer was also focused on if statement which is nice, but the problem was not there.
I removed the if statement and a lot and just focused to see if I get some thing returned, I did not.
You $result= mysqli_stmt_bind_result($request); missed arguments, when that fixed, the next line missed also something else. I already there quit debugging.
I have rewrite your code and it works, what I did I have redefined the naming of variable so they are crystal clear to understand what is name, call it username, database username call it dbUser or dbUsername etc.
And if you want to check your code returning some thing or not, use var_dump($someVariable).
Last thing, before making a post form, you could create a dummy username and password in your database and inject that directly in your code like, just to see if every thing is working, and then move to your form:
$username = "user1";
$password = "1234";
The solution I did is just to demonstrate how to do it and not necessarily representation of the best logic, but it is up to you to find the correct logic and all depends on your strategy.
Here is my suggestion:
<?php
session_start();
$dbHost = "localhost";
$dbUser = "root";
$dbPass = "";
$dbName = "product";
$connection = new mysqli($dbHost, $dbUser, $dbPass, $dbName);
// Check connection
if ($connection->connect_error)
{
header("location:maintenance.php");
exit();
// or for debugging, activate following line
//die("Connection failed: " . $connection->connect_error);
}
$username = $_POST['username'];
$password = $_POST['password'];
//if username and password empty stop login
if (!$username || !$password)
{
//do something, die is only example
die ("Not all the fields were filled in");
} else
{
login_check($username, $password);
}
function login_check($username, $password)
{
global $connection;
//sql statements is corrected, change field name to username
$sql = "SELECT * FROM `members` WHERE `username` = ? AND `password` = ?";
$stmt = $connection->prepare($sql);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$output = $stmt->get_result();
$row = $output->fetch_array(MYSQLI_NUM);
$stmt->close();
//print what comes out in $row
//print_r($row);
//check if $row has data
if ($row)
{
echo "success do something";
$_SESSION['member'] = $username;
} else
{
echo "fail do something";
}
}
After defining the function login_check(), you should also call it (if the conditions are right):
function login_check() {
// your implementation as above
}
if (isset($_POST['name']) && isset($_POST['password'])) {
login_check(); // actually call the function
}
As a side note, it is good practice to also explicetely close the connection before redirecting.
Edit
as KhomeHoly comments, only call the function when necessary...
You need to call your functions if you define them. Not doing so is like building a room within a new house but forgetting the door. It's there, but nobody can use or access it.
So what you need to do is the following:
// your script as it is right now
if (isset($_POST['name']) && isset($_POST['password'])) {
login_check(); // actually call the function
}
With isset() you check if the certain $_POST parameters are set, but not validated. You should at least do a basic validation of the data to see if they are correct!
Something like this would work, depends on your requirements
if (isset($_POST['name']) && strlen($_POST['name') >= 4 && isset($_POST['password']) && strlen($_POST['password']) >= 4) {
login_check(); // actually call the function
}
The code above would check if those paramters are set and check if name and password are at least 4 characters long. (I wouldn't accept usernames lower than 4 chars personally, passwords should be at least 8 for me)
Now of course this misses an correct error reporting and all that stuff, but I think that should give you the basic idea based on your quesiton.
Always, always, always put exit() after header redirect call. Even in that case, it might solve your issue.
header("location:../../success.php");
exit();
Why?

My program is skipping a function in PHP

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!

Categories