PHP: Function no query & return - php

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.

Related

Issue getting mysqli_query to execute

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.

mysql_real_escape_string() expects parameter 1 to be string, object given

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)

can anyone please tell me whats wrong with my session?

I'm trying to add an announcement with the need of the user [ id] who posted it and I was going to take it via session I don't know its not working I keep getting this error (Fatal error: Cannot redeclare check_login() (previously declared in C:\xamppp2\htdocs\session.php:17) )
and I'm trying to insert current time and date separately is (date(),now()) are the right functions? I'm trying to insert those too, could you guys possibly help? here's my code
I included the session on top of my page
<?PHP include('session.php');?>
and here's the rest of my php file
<?PHP
$link = mysql_connect('localhost','root','');
if (!$link) {
die('Could not connect :' . mysql_error());
}
$Selected= mysql_select_db("elearningg", $link);
if (!$Selected) {
die("Could not connect: " . mysql_error());
}
if(!empty($_POST))
{
$msg = '';
$error = '';
$title = $_POST['title'];
$desc = $_POST['desc'];
if(trim($title) == '')
{$error = 'Please enter event title';}
else if(trim($desc) == '')
{$error = 'Please enter description ';}
$IID =$_SESSION['userid'];
if($error=='') {
$qry6="INSERT INTO announcement (`Atitle`,`Adescription`,`Adate`,`Atime`,`IID`) VALUES
('$title','$desc',date(),now(),$IID)" ;
$result6=mysql_query($qry6);
$msg = " Announcement is added ";
}
}
mysql_close($link);
?>
and here's my actual session script..
if (!$link) {
die('Could not connect :' . mysql_error());
}
$Selected= mysql_select_db("elearningg", $link);
if (!$Selected) {
die("Could not connect: " . mysql_error());
}
ob_start();
session_start();
function check_login(){
if(!empty($_SESSION['userid'])){
return 1;
}else{
return 0;
}
}
?>
This isn't a session problem. You are as your error message says trying to redeclare check_login().
You can only declare a function once.
So depending on how your files are structured you need to make sure that that function is only declared once. Perhaps you use includes in your files. You either need to make sure it isn't redeclared so think about how you structure it so that doesn't happen or use require_once, this adds more overhead to your script though.
http://php.net/manual/en/function.require-once.php

Mysql call stops all forms of output php

Hello, I'm kind of new to php, so don't bash on me, but I just can't figure out what the problem is with this code. So basically I have several forms of output, but as soon as I do anything with mysql ( even just connect and disconnect! ), it won't allow me to do any kind of output. It also won't allow me to redirect.
I tried taking all the code out between the mysql connect and disconnect code and it didn't help to resolve anything, However, as soon as I comment out the mysql connection code, all my outputs and redirects work! I'm trying to build a simple login script that gets the email and password from a form elsewhere. I would love to get this resolved so I could figure out if the rest of it works. And I know that 'header' will not work after echo; the echo and the file writes will not be there as soon as I can make sure this is working. Any help would be appreciated! Thanks!
<?php
/*
Login.php searches for the email address given by loginPage.php in the data base.
If the email is found and the password given by loginPage.php matches that stored
in the data base, a session will begin and the client will be redirected to the
main page.
*** INCOMPLETE ***
*/
echo "HELLO!";
$email = $_POST["email"];
$password = $_POST["password"];
$errorLog = fopen("login.txt", "w");
fwrite($errorLog, "***Sesion started***");
$mysql_id = mysql_connect("localhost", "root", "12131");
if (!$mysql_id)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('informationStation', $mysql_id);
$results = mysql_query("SELECT password FROM Personals WHERE email = '" . $email . "';", $mysql_id);
if($results != null && $password == mysql_fetch_array($result))
{
$redirect = 'Location: http://127.0.1.1/main.php';
}
else
{
$redirect = 'Location: http://127.0.1.1/loginPage.php';
{
mysql_close($mysql_id);
fwrite($errorLog, "result: " . $results);
fwrite($errorLog, "redirect: " . $redirect);
fclose($errorLog);
header($redirect);
?>
Try this to get you started..
$results = mysql_query("SELECT password FROM Personals WHERE email = '" . $email . "'", $mysql_id) or die(mysql_error());
But you also need to read about sql injection.
And you should not store passwords in your database without salting and hashing them.
And you also need to use array syntax to access the data from your result...
$mysql = mysql_connect("localhost", "root", "12131") or die('Could not connect: ' . mysql_error());
mysql_select_db('informationStation', $mysql);
function loged($email, $password) {
$result = mysql_query("SELECT id FROM Personals WHERE email = '" . $email . "' AND password='" . $password . "'");
if(mysql_num_rows($result) != 1)
return false;
return true;
}
if(loged(mysql_real_escape_string($email), md5($password))) {
header('Location: http://127.0.1.1/mainPage.php');
exit;
}
header('Location: http://127.0.1.1/loginPage.php');
In this example you need to store users password using md5 encryption method (search for other more securely encryption methods).
Also we've escaped the email address against sql injection.
I've created a function which can be called every time you want to see if the user is loged in or not.
Note that this is not a complete login script. You will also need to make a login function where you'll have to start a new session for each user.

PHP script not redirecting via header

I am looking for some kind of bug in my code which is causing this PHP page to not redirect. I'm looking to see if someone might know the cause of this problem (it may have something to do with the cookies).
inc_vars.php:
<?php
//some of the variables have been omitted.
$pid = 'gbb';
$dbtable ='';
$dbname = '';
$dbuser = '';
$dbpass = '';
$connect = mysql_connect('localhost', $dbuser, $dbpass);
if(!$connect){
header('Location: omitted');
die();
}
mysql_select_db ($dbname, $connect);
$webroot = 'omitted';
$share_page = $webroot . '/share-the-training';
$gift = $webroot . '/free-video?setuser=1199';
$bonus_content = $webroot . '/awesome-bonus';
$share_php = $webroot . '/share.php';
?>
refresh_id.php:
<?php
include_once('inc_vars.php');
$results = mysql_query("SELECT id FROM " . $dbtable . " WHERE email='" . $_GET['email'] . "'");
if(!$results || mysql_num_rows($results)==0){
header('Location: ' . $share_page . '?errorcode=1');
die();
}
$res_arr = mysql_fetch_assoc ($results);
setcookie($pid . "_viral", (string)$res_arr['id'], time() + 3600 * 365);
move_on();
function move_on(){
header ('Location: ' . $share_php);
die();
}
?>
When the person visits refresh_id.php?email=their_email they should redirect to the $share_php page. This is not working.
However, if this scenario happens: refresh_id.php?email=an-email-that-is-not-in-database then the script redirects to $share_page absolutely fine.
I have tried this with and without the gbb_viral cookie in place. I'm not sure why this isn't working. All pages are live and on the internet right now in case you want to look for yourself.
omitted
An email that exists in the database is as follows: acctrafficcop#gmail.com (for those that want to test this)
UPDATE
Stupid mistake with scopes. I simply added global $share_php in the move_on() function and everything is working fine now. Thank you everyone for the heads up on SQL injection, I am switching over to prepared statements right now.
In your move_on function, the variable $share_php does not exist because of variable scope. Therefore your redirect looks like this: Location:. There is no URL in the Location header.
You can pass the variable into the function, or use the global keyword to make it available. Try this:
move_on('/redirect_url');
function move_on($url){
header ('Location: ' . $url);
die();
}
In fact, in refresh_id.php I don't see a variable called $share_php anywhere, so you are redirecting to an empty URL.
You also need to set a status header for the browser to honor the location header. Try adding
header('HTTP/1.1 303 See Other');
Using curl will help you debug. Also, your are setting yourself up for SQL Injection with your SQL query.
Edit: After reading the second answer, it is correct that you aren't passing in a location to your redirection function. This should be fixed as well.
$results = mysql_query("SELECT id FROM " . $dbtable . " WHERE email='" . $_GET['email'] . "'");
Never trust input from users like this. Instead, use a SQL bind. Here's how you would do it with the mysqli library: http://php.net/manual/en/mysqli-stmt.bind-param.php

Categories