Undefined connection variable in PHP - php

I've got a php script as follows:
function addPost(BlogPost $item, $tags) {
$connection = mysql_connect('localhost', '***', '***') or die(mysql_error());
mysql_select_db('jschaible1') or die(mysql_error());
$queryString = "insert into BlogPost values ( null, '" . $item->Title . "', '" . $item->Body . "', " . "now());";
$result = mysql_query($queryString) or die(mysql_error());
$dbResult = mysql_query('select * from blogpost where Title = "' . $item->Title . '";') or die(mysql_error());
while ($row = mysql_fetch_array($dbResult)) {
$tableID = $row['BlogPostID'];
}
foreach($tags as $t) {
$queryString = "insert ignore into Tag values('" . strtolower($t) . "');";
mysql_query($queryString) or die(mysql_error());
$queryString = "insert into blogposttag values (" . $tableID . ", '" . strtolower($t) . "');";
mysql_query($queryString) or die(mysql_error());
}
echo $connection;
mysql_close($connection) or die(mysql_error());
}
The function is being called like this:
<?php
session_start();
$errors = '';
if (!isset($_SESSION['dadfg6d5f6df54']))
header('Location:admin.php');
else {
include('Classes.php');
include('mySql.php');
include('utils.php');
if(isset($_POST['Submit'])) {
if ($_POST['Title'] == '') {
$errors = 'Post must have a title!';
}
else if ($_POST['PostBody'] == '') {
$errors = 'Post must be something!';
}
else if (strlen($_POST['PostBody']) < 10) {
$errors = "Write something substantial, c'mon!";
}
else if ($_POST['Tags'] == '') {
$errors = "At least one tag must be entered";
}
else {
$newPost = new BlogPost(NULL, sanitize($_POST['Title']), sanitize($_POST['PostBody']), NULL);
$newPost->Title = addEmoticons($newPost->Title);
$newPost->Body = addEmoticons($newPost->Body);
$tags = str_replace(',', '', $_POST['Tags']);
$tags = str_replace(';', '', $tags);
$tags = explode(' ', $tags);
error_reporting(E_ALL); ini_set('display_errors', 1);
addPost($newPost, $tags) or die();
$errors = 'Post added successfully';
}
}
}
?>
When it gets to mysql_close(), the page just stops executing and I get a blank page. This is really frustrating me, I don't understand at all why it's happening, especially seeing as how the echo on the PREVIOUS line puts out "resource id#6". I get no error message, just a blank page! Please help!

Your function has no return value. It therefore returns NULL which evaluates as a "falsy" value. Since you follow it with an or die() call, the false evaluation triggers the or die() and terminates your script.
// Don't do this:
addPost($newPost, $tags) or die();
// Do this:
addPost($newPost, $tags);
In the end of your function, you could return TRUE, but it is entirely unnecessary unless you wish to return a value based on the success or failure of your post addition. The way you have it, the die() is just causing undue harm. Since all the potential failing points in your function are already going to terminate the script on error, there is no great purpose to returning TRUE. Just remove the die() after the function call.

Related

Problems with mysql and mysqli

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1
given in C:\xampp\htdocs\swift\core\functions\general.php on line 49
Notice: Undefined variable: conn in
C:\xampp\htdocs\swift\core\functions\users.php on line 85
Warning: mysqli_query() expects parameter 1 to be mysqli, null given
in C:\xampp\htdocs\swift\core\functions\users.php on line 85
Fatal error: Uncaught Error: Call to undefined function
mysqli_result() in C:\xampp\htdocs\swift\core\functions\users.php:86
Stack trace: #0 C:\xampp\htdocs\swift\loginact.php(14): f_exists('')
#1 {main} thrown in C:\xampp\htdocs\swift\core\functions\users.php on line 86
I keep on getting those errors but i cant find a way, i already tried everything.. Hopefully someone can help me as I am new to php.
Ive been doing this for almost like a day now and i cannot figure out the answer.
This is the General.php.
<?php
$connect_error = 'Sorry, there was some connectivity issue!';
$conn = mysqli_connect('localhost','root','');
$db = mysqli_select_db($conn, 'swift');
function activation($to, $subject, $body) {
mail($to, $subject, $body, 'From: swift#srikanthnatarajan.com');
}
function recovery_user_pass($to, $subject, $body) {
mail($to, $subject, $body, 'From: swift#srikanthnatarajan.com');
}
function f_protect_page() {
if(f_logged_in() === false) {
header('Location: flogin.php');
exit();
}
}
function user_protect_page() {
if(f_logged_in() === false) {
header('Location: fprotect.php');
exit();
}
}
function use_protect_page() {
if(f_logged_in() === true) {
header('Location: fprotect.php');
exit();
}
}
function f_logged_in_redirect() {
if(f_logged_in() === true) {
header('Location: index.php');
exit();
}
}
function array_sanitize($item) {
$item = htmlentities(strip_tags(mysqli_real_escape_string($item)));
}
function sanitize($data) {
return htmlentities(strip_tags(mysqli_real_escape_string($data)));
}
function output_errors($errors) {
return '<ul><li>' . implode('</li><li>', $errors) . '</li></ul>';
}
?>
this is the USERS.PHP can someone please check this.
<?php
$connect_error = 'Sorry, there was some connectivity issue!';
$conn = mysqli_connect('localhost','root','');
$db = mysqli_select_db($conn, 'swift');
function f_recover($mode, $f_mailid) {
$mode = sanitize($mode);
$f_mailid = sanitize($f_mailid);
$f_data = f_data(f_id_from_email($f_mailid),'f_id','f_fname','f_uname');
if ($mode == 'f_uname') {
recovery_user_pass($f_mailid, 'Recovery: Your username', "Hello " . $f_data['f_fname'] . ",\n\nYour username is: " . $f_data['f_uname'] . "\n\n-Swift Airlines");
}
else if($mode == 'f_password') {
$generated_password = substr(md5(rand(999, 999999)), 0, 8);
f_change_password($f_data['f_id'], $generated_password);
update_f($f_data['f_id'], array('f_passrec' => '1'));
recovery_user_pass($f_mailid, 'Recovery: Your password', "Hello " . $f_data['f_fname'] . ",\n\nYour new password is: " . $generated_password . "\n\n-TOFSIS");
}
}
function f_activate($f_mailid, $f_mailcode) {
$f_mailid = mysqli_real_escape_string($_POST['f_mailid']);
$f_mailcode = mysqli_real_escape_string($_POST['f_mailcode']);
if(mysqli_result(mysqli_query("SELECT COUNT(`f_id`) FROM `flight_users` WHERE `f_mailid` = '$f_mailid' AND `f_mailcode` = '$f_mailcode' AND `f_active` = 0"), 0) == 1) {
mysqli_query("UPDATE `flight_users` SET `f_active` = 1 WHERE `f_mailid` = '$f_mailid' ");
return true;
}
else {
return false;
}
}
function update_f($f_id, $update_data) {
$update = array();
array_walk($update_data, 'array_sanitize');
foreach ($update_data as $field => $data) {
$update[] = '`' . $field . '` = \'' . $data . '\'';
}
mysqli_query("UPDATE `flight_users` SET " . implode(', ',$update) . "WHERE `f_id` = $f_id") or die(mysqli_error($conn));
}
function f_change_password($f_id, $f_password) {
$f_id = (int)$f_id;
$f_password = md5($f_password);
mysqli_query("UPDATE `flight_users` SET `f_password` = '$f_password', `f_passrec` = 0 WHERE `f_id` = $f_id");
}
function register_f($register_data) {
array_walk($register_data, 'array_sanitize');
$register_data['f_fname'] = ucwords(strtolower($register_data['f_fname']));
$register_data['f_lname'] = ucwords(strtolower($register_data['f_lname']));
$register_data['f_password'] = md5($register_data['f_password']);
$register_data['f_uname'] = strtolower($register_data['f_uname']);
$fields = '`' . implode('`, `', array_keys($register_data)) . '`';
$data = '\'' . implode('\', \'', $register_data) . '\'';
mysqli_query("INSERT INTO `flight_users` ($fields, `f_regdate`) VALUES ($data, NOW())");
activation($register_data['f_mailid'], 'Swift Airlines: Activate your account', "Hello " . $register_data['f_fname'] . ", \n\nYou need to activate your account in order to use the features of Swift Airlines. Please click the link below: \n\nhttp://srikanthnatarajan.com/swift/activate.php?f_mailid=" . $register_data['f_mailid'] . "&f_mailcode=" . $register_data['f_mailcode'] . " \n\n-Swift Airlines");
}
function f_data($f_id){
$data = array();
$f_id = (int)$f_id;
$func_num_args = func_num_args();
$func_get_args = func_get_args();
if($func_num_args > 1) {
unset($func_get_args[0]);
$fields = '`'. implode('`, `', $func_get_args) . '`';
$data = mysqli_fetch_assoc(mysqli_query("SELECT $fields FROM `flight_users` WHERE `f_id` = $f_id"));
return $data;
}
}
function f_logged_in() {
return (isset($_SESSION['f_id'])) ? true : false;
}
function f_exists($f_uname) {
$f_uname = sanitize($f_uname);
$query = mysqli_query($conn, "SELECT COUNT(`f_id`) FROM `flight_users` WHERE `f_uname`= '$f_uname'");
return (mysqli_result($conn, $query, 0) == 1) ? true : false;
}
function f_email_exists($f_mailid) {
$f_mailid = sanitize($f_mailid);
$query = mysqli_query($conn, "SELECT COUNT(`f_id`) FROM `flight_users` WHERE `f_mailid`= '$f_mailid'");
return (mysqli_result($conn, $query, 0) == 1) ? true : false;
}
function f_regid_exists($f_regid) {
$f_regid = sanitize($f_regid);
$query = mysqli_query($conn, "SELECT COUNT(`f_id`) FROM `flight_users` WHERE `f_regid`= '$f_regid'");
return (mysqli_result($conn, $query, 0) == 1) ? true : false;
}
function f_active($f_uname) {
$f_uname = sanitize($f_uname);
$query = mysqli_query($conn, "SELECT COUNT(`f_id`) FROM `flight_users` WHERE `f_uname`= '$f_uname' AND `f_active` = 1");
return (mysqli_result($conn, $query, 0) == 1) ? true : false;
}
function f_id_from_username($f_uname) {
$f_uname = sanitize($f_uname);
$query = mysqli_query($conn, "SELECT `f_id` FROM `flight_users` WHERE `f_uname` = '$f_uname'");
return mysqli_result($conn, $query, 0, 'f_id');
}
function f_id_from_email($f_mailid) {
$f_mailid = sanitize($f_mailid);
$query = mysqli_query($conn, "SELECT `f_id` FROM `flight_users` WHERE `f_mailid` = '$f_mailid'");
return mysqli_result($conn, $query, 0, 'f_id');
}
function f_login($f_uname, $f_password) {
$f_id = f_id_from_username($f_uname);
$f_uname = sanitize($f_uname);
$f_password = md5($f_password);
$query = mysqli_query($conn, "SELECT COUNT(`f_id`) FROM `flight_users` WHERE `f_uname`= '$f_uname' AND `f_password` = '$f_password'");
return (mysqli_result($conn, $query, 0) == 1) ? $f_id : false;
}
?>
and this is the Loginact.php------------------
<?php
$title = 'Swift Airlines | Login Error';
include $_SERVER["DOCUMENT_ROOT"].'/swift/core/init.php';
if(empty($_POST) === false) {
$f_uname = $_POST['f_uname'];
$f_password = $_POST['f_password'];
if(empty($f_uname) === true || empty($f_password) === true){
$errors[] = 'You need to enter both, the username and the password!';
}
else if (f_exists($f_uname)===false) {
$errors[] = 'No such user exists! Please register!';
}
else if(f_active($f_uname)===false) {
$errors[] = 'Please activate your account!';
}
else {
if(strlen($f_password)>32) {
$errors[] = 'Password too long!';
}
$f_login = f_login($f_uname, $f_password);
if($f_login===false) {
$errors[] = 'Username and Password do not match!';
}
else {
$_SESSION['f_id'] = $f_login;
header('Location: http://localhost/swift/index.php');
exit();
}
}
}
else {
$errors[] = 'No Log In credentials received!';
}
include $_SERVER["DOCUMENT_ROOT"].'/swift/includes/overall/header.php';
if(empty($errors) === false) {
?>
<br/><h4>We tried to log you in, but : </h4><br/>
<?php
echo output_errors($errors);
}
include $_SERVER["DOCUMENT_ROOT"].'/swift/includes/overall/footer.php';
?>
I keep on getting those errors but i cant find a way, i already tried everything.. Hopefully someone can help me as I am new to php.
Ive been doing this for almost like a day now and i cannot figure out the answer.
i know php is kind of hard yea and ive been looking for the answer for almost a day now. Im just new to programming and im doing my best to study hard about these kind of things hopefully someone can help me.
And i hope i can learn more about php and other programming language here.. ill keep looking for the answer even if im asking right now.. big thanks though.
I doubt you tried everything!
It looks as if you are trying to migrate from mysql_ functions to mysqli_.
From the manual for mysqli_fetch_array:
$query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result = mysqli_query($link, $query);
/* numeric array */
$row = mysqli_fetch_array($result, MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);
$link is your mysqli connection. In your code it is $conn.
Within your functions you have a scope issue. $conn is in the global scope, so is not set within the function's scope.
Break it down, start with something like your f_id_from_email function, and follow and try to translate the manual's examples.
The error messages are actually quite helpful if read. But you are likely overwhelmed, as you are faced with many.
Call to undefined function mysqli_result()
That's because there is no mysqli_result function.
1- general.php line 49: look at mysqli_real_escape_string, in procedural code, you must specify 2 arguments, the link (or connection) and the string.
function array_sanitize($conn,$item) {
$item = htmlentities(strip_tags(mysqli_real_escape_string($conn,$item)));
}
function sanitize($conn,$data) {
return htmlentities(strip_tags(mysqli_real_escape_string($conn,$data)));
}
2- users.php, both on line 85, the $conn does not exist in the scope of the function. Pass $conn as an argument to the function and call it with ($conn,$f_uname).
function f_exists($conn,$f_uname) {
$f_uname = sanitize($f_uname);
$query = mysqli_query($conn, "SELECT COUNT(`f_id`) FROM `flight_users` WHERE `f_uname`= '$f_uname'");
return (mysqli_result($conn, $query, 0) == 1) ? true : false;
}
3- your question at line 86, it is the same as my #2 point.

php script just stops even with set_time_limit(0)

I have looked at like 10 other posts with people who seem to have the same problem as me in, most suggest putting set_time_limit(0);. But even with that no matter what script I run, always after around 9-10 minutes it just stops.
I have tried so many combinations of the below 3 variables, setting them to -1, 0, 9999999; just always stops. It was not so long ago, I had the exact same script below run over night. And just one day I have this problem with any script.
I’m 100% sure it’s stopping before its finished, and it’s not stopping due to error. Because any of my scripts now stop at the same app run time.
Extremely frustrated, any help will be much appreciated.
In php.ini:
max_input_time = -1
max_execution_time = 0
set_time_limit = 0
Another scripts: (also stops after 10 minutes)
<?php
set_time_limit(0);
ignore_user_abort(true);
function categoryinsert($english, $name, $keywords, $language)
{
if(!$english)
{
echo "no english recieved! in categoryinsert<br />";
return 0;
}
else if(!$name)
{
echo "no name recieved! in categoryinsert<br />";
return 0;
}
else if(!$language)
{
echo "no language recieved! in categoryinsert<br />";
return 0;
}
$DBConnect = mysqli_connect("localhost", "USER***", "************");
mysqli_set_charset($DBConnect, "utf8");
mysqli_select_db($DBConnect, "db***");
$qwry = "INSERT INTO `categories` (english, name, keywords, language) values ('$english','$name','$keywords','$language');";
$QueryResult = mysqli_query($DBConnect, $qwry);
//Or die("<p>Unable to execute the query.[".$qwry."]<p>"
//. "<p>Error code " . mysqli_errno($DBConnect)
//. ": " . mysqli_error($DBConnect)) . "</p>";
mysqli_close($DBConnect);
}
function checkfor($english, $lang)
{
$DBConnect = mysqli_connect("localhost", "USER***", "************");
mysqli_set_charset($DBConnect, "utf8");
mysqli_select_db($DBConnect, "db***");
$qwry = "SELECT * FROM `categories` where english = '$english' and language = '$lang';";
$QueryResult = mysqli_query($DBConnect, $qwry);
$Row = mysqli_fetch_row($QueryResult);
mysqli_close($DBConnect);
if($Row) return true;
else return false;
}
function categoryupdate($keywords, $language, $english)
{
if(!$english)
{
echo "no english recieved! in categoryupdate<br />";
return 0;
}
else if(!$keywords)
{
echo "no keywords recieved! in categoryupdate<br />";
return 0;
}
else if(!$language)
{
echo "no language recieved! in categoryupdate<br />";
return 0;
}
$DBConnect = mysqli_connect("localhost", "USER***", "************");
mysqli_set_charset($DBConnect, "utf8");
mysqli_select_db($DBConnect, "db***");
$qwry = "UPDATE `categories` set keywords = '$keywords' where language = '$language' and language = '$language';";
$QueryResult = mysqli_query($DBConnect, $qwry)
Or die("<p>Unable to execute the query.[".$qwry."]<p>"
. "<p>Error code " . mysqli_errno($DBConnect)
. ": " . mysqli_error($DBConnect)) . "</p>";
mysqli_close($DBConnect);
}
function translatekeywords($keywords, $tolang)
{
if(!$keywords)
{
echo "no keywords recieved! in translatekeywords<br />";
return 0;
}
else if(!$tolang)
{
echo "no tolang recieved! in translatekeywords<br />";
return 0;
}
$parts = explode(", ", $keywords);
$count = 0;
$out = "";
while($parts[$count])
{
if(($count != 0) and ($result)) $out = $out . ", ";
$result = translate($parts[$count], 'eng', $tolang);
if($result) $out = $out . $result;
$count++;
}
return $out;
}
include '../functions.php';
$DBConnect = mysqli_connect("localhost", "USER***", "************");
mysqli_set_charset($DBConnect, "utf8");
mysqli_select_db($DBConnect, "db***");
$qwry = "SELECT english, keywords FROM `categories` where language = 'eng' order by name ASC;";
$QueryResult = mysqli_query($DBConnect, $qwry)
Or die("<p>Unable to execute the query.[".$qwry."]<p>"
. "<p>Error code " . mysqli_errno($DBConnect)
. ": " . mysqli_error($DBConnect)) . "</p>";
$count = 0;
$Row = mysqli_fetch_row($QueryResult);
do
{
$categories[$count] = $Row;
echo $count.') ['.$categories[$count][0].']['.$categories[$count][1].']<br />';
$Row = mysqli_fetch_row($QueryResult);
$count++;
}while($Row);
$qwry = "SELECT ISO3 FROM `languages` order by name ASC;";
$QueryResult = mysqli_query($DBConnect, $qwry)
Or die("<p>Unable to execute the query.[".$qwry."]<p>"
. "<p>Error code " . mysqli_errno($DBConnect)
. ": " . mysqli_error($DBConnect)) . "</p>";
$count = 0;
$Row = mysqli_fetch_row($QueryResult);
do
{
$languages[$count] = $Row[0];
$Row = mysqli_fetch_row($QueryResult);
echo '['.$languages[$count].']<br />';
$count++;
}while($Row);
$lcount = 0;
do
{
if($languages[$lcount] != 'eng')
{
$ccount = 0;
do
{
if(!checkfor($categories[$ccount][0], $languages[$lcount]))
{
$name = translate($categories[$ccount][0], 'eng', $languages[$lcount]);
if($categories[$ccount][1]) $keywords = translatekeywords($categories[$ccount][1],$languages[$lcount]);
categoryinsert($categories[$ccount][0], $name, $keywords, $languages[$lcount]);
}
$ccount++;
}while($categories[$ccount]);
}
$lcount++;
}while($languages[$lcount]);
mysqli_close($DBConnect);
echo "FINISHED! [$lcount] languages proccessed";
?>
The script:
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head>
<body>
<?php
set_time_limit(0);
ignore_user_abort(true);
include 'functions.php';
function insertsentence($sentence, $lang, $id, $user)
{
if(($lang == 'epo') and (strlen($sentence) < 255) )
{
$DBConnect = mysqli_connect("localhost", "xxxxx_userx", "xxxxxxx!");
mysqli_set_charset($DBConnect, "utf8");
mysqli_select_db($DBConnect, "xxxxx_main");
$insertqwry = "INSERT INTO `sentences` (sentence, user, id, language) VALUES ('".withslashes($sentence)."', '".withslashes($user)."', '".withslashes($id)."', '".withslashes($lang)."');";
$QueryResult = mysqli_query($DBConnect, $insertqwry) ;
//Or die("<p>Unable to execute the query.[".$insertqwry."]<p>"
//. "<p>Error code " . mysqli_errno($DBConnect)
//. ": " . mysqli_error($DBConnect)) . "</p>";
mysqli_close($DBConnect);
return 1;
}
}
$myFile = "sentences_detailed.csv";
$fh = fopen($myFile, 'r');
$s = fread($fh, 3);
if ($s != pack('CCC',0xef, 0xbb, 0xbf)) {
// bom not found, rewind file
fseek($fh, 0, SEEK_SET);
}
$count = 0;
ob_start();
do
{
$line = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', withslashes(trim(fgets($fh))));
$parts = explode(" ", $line);
$id = $parts[0];
$lang = $parts[1];
$sentence = withslashes($parts[2]);
$user = withslashes($parts[3]);
$note = "";
if ((!$line) or ($line == "") or ($line == "!"))
{
echo ($count-1)." entries were processed<br />";
echo "done<br />";
exit();
}
if ($sentence != "!" )
{
if (insertsentence($sentence, $lang, $id, $user))
echo "!";
}
ob_flush();
flush();
$count++;
echo ".";
}while($line);
fclose($fh);
mysqli_close($DBConnect);
echo ($count-1)." entries were processed<br />";
?>
</body>
</html>
EDIT: No matter what script I run, or how simple it always stops after about 10 minutes. So I doubt it’s anything to do with the code in my script. So I'll add that my web server I’m running scripts on, is on Bluehost.
The answer is its a limitation bluehost has set to my account. Heres the response he gave me:
...
The Dedicated IP (+$3.33 per month) will increase the limits on the account.
The following it the limits on how the server will kill processes with and without the Dedicated IP on the account:
With a Dedicated IP Without Dedicated IP
Apache/Web (HTML/PHP/Downloads) 12 hours 10 minutes
...
Consider using flush function of PHP, with this you can execute your loop continuously - I know this is not the best and final solution but this might helpful to you :)
See this first example
Some ideas.
First your code has these calls to a function called withslashes() which I assume is a custom function designed to add slashes (aka: escape) values to quotes & other characters But you are using MySQLi calls, right? Then why not avoid reinventing the wheel and just use mysqli_real_escape_string() which is part of the MySQLi extensions?
Also, I added mysqli_free_result() which “Frees the memory associated with a result.” Which can’t hurt even if the result of your query is just an acknowledgement that the query ran.
And I added a sleep() value of ` second to at least throttle the process a bit to give your server room to breath.
The whole goal is to use built-in PHP functions to avoid using more RAM than necessary when running MySQL queries & pausing the script by 1 second to give it breathing room.
Here is a refactored version of insertsentence() using the first set of ideas to improve performance:
function insertsentence($sentence, $lang, $id, $user) {
if (($lang == 'epo') and (strlen($sentence) < 255)) {
$DBConnect = mysqli_connect("localhost", "xxxxx_userx", "xxxxxxx!");
mysqli_set_charset($DBConnect, "utf8");
mysqli_select_db($DBConnect, "xxxxx_main");
$insertqwry = "INSERT INTO `sentences` (sentence, user, id, language)"
. " VALUES ('$sentence', '$user', '$id', '$lang');"
;
// Escape the query.
$insertqwry = mysqli_real_escape_string($DBConnect, $insertqwry);
$QueryResult = mysqli_query($DBConnect, $insertqwry) ;
// Free the result set.
mysqli_free_result($QueryResult);
mysqli_close($DBConnect);
// Sleep for 1 second.
sleep(1);
return TRUE;
}
}
But why not use mysqli_stmt_bind_param() to make full use of the prepared statements capability of MySQLi? Then you no longer need to use mysqli_real_escape_string() because prepared statements basically handle all of that.
With that in mind, here is another refactored version of insertsentence() which uses mysqli_stmt_bind_param():
function insertsentence($sentence, $lang, $id, $user) {
if (($lang == 'epo') and (strlen($sentence) < 255)) {
$DBConnect = mysqli_connect("localhost", "xxxxx_userx", "xxxxxxx!");
mysqli_set_charset($DBConnect, "utf8");
mysqli_select_db($DBConnect, "xxxxx_main");
$insertqwry = "INSERT INTO `sentences` (sentence, user, id, language)"
. " VALUES (?, ?, ?, ?);"
;
// Bind the values to the statement.
mysqli_stmt_bind_param($insertqwry, 'ssis', $sentence, $user, $id, $lang);
$QueryResult = mysqli_query($DBConnect, $insertqwry) ;
// Free the result set.
mysqli_free_result($QueryResult);
mysqli_close($DBConnect);
// Sleep for 1 second.
sleep(1);
return TRUE;
}
}
Note the 'ssds' in mysqli_stmt_bind_param(). Each letter determines the types of your 4 values. So in this case it is string (sentence), string (user), integer (id), string (language) which is my best guesses based on the data you’re giving me.
Sounds like your script is limited by the server. I think you can change this in php.ini.

Echo Nothing when Query is Empty

I am trying to check if the user input $entry is empty, and if it is, to echo nothing. I don't want it to do anything. There are no results, it shouldn't display anything. However, I keep getting an empty query error.
Here is my php:
$link = fConnectToDatabase();
//Retrieve parameters from querystring
$entry = fCleanString($link, $_GET['entry'], 15);
if (!empty($entry)) {
$sql = "select price, name, image
from geekproducts
where name like '%$entry%' or ' $entry '
order by name";
}
$result = mysqli_query($link, $sql)
or die('SQL syntax error: ' . mysqli_error($link));
if (! ($result)){
echo "";
}
How do I get my page to display nothing when the result is null?
EDIT The problem seems to be solely with
$result = mysqli_query($link, $sql)
or die('SQL syntax error: ' . mysqli_error($link));
Getting rid of the or die statement returns a big paragraph on syntax errors. Any ideas?
How about
if (isset($_GET['entry']) {
$entry = fCleanString($link, $_GET['entry'], 15);
$sql = "select price, name, image
from geekproducts
where name like '%$entry%' or ' $entry '
order by name";
$result = mysqli_query($link, $sql)
or die('SQL syntax error: ' . mysqli_error($link));
} else {
echo 'nothing ;)';
}
you can do it like this:
if(mysql_num_rows($result)==0)echo '';
I think what you're trying to do is suppressing the error
$link = fConnectToDatabase();
//Retrieve parameters from querystring
$entry = fCleanString($link, $_GET['entry'], 15);
if (!empty($entry)) {
$sql = "select price, name, image
from geekproducts
where name like '%$entry%' or ' $entry '
order by name";
}
$result = #mysqli_query($link, $sql)
Adding # before the function suppresses errors

data structure in php and mysql

Hello I have error on line 10 could tell me what is my mistake. Is it a boolean problem? I tried various solutions but I still get the same error:
<?php
class classData {
function __construct() {
mysql_select_db("dbVentas", mysql_connect("localhost", "root", ""));
}
function voidInsert($code, $name) {
if (validateCodigo($code) == true) {
mysql_query("insert into tbZone (code,zone) values ('" . $code . "','" . $name . "')")
or die("ERROR!!!... ");
}
}
function validateCodigo($code) {
$ok = true;
$isql = mysql_query("select * from tbZone where code='" . $code . "'");
$cCod = 0;
while ($oRow = mysql_fetch_array($isql)) {
extract($oRow);
$cCod++;
}
if ($cCod > 0) {
$ok = false;
}
return $ok;
}
}
?>
I call this php file DataClass.php
Since you're calling another class method, you should use
$this->validateCodigo($code) instead of validateCodigo($code)

Transparent mysql_error logging: How can I read mysql_error() twice?

I want to do a transparent mysql_error logging in my php app. I've done the following yet:
function mysql_query_log_error($query) {
$debug_trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
$caller = $debug_trace[1];
$file = substr($caller[file], strrpos($caller[file], '/')+1);
$line = $caller[line];
$error = mysql_error();
$error_query = "INSERT INTO Common.ERRsql SET "
."errQuery = '".mysql_real_escape_string($query)."', "
."errText = '".mysql_real_escape_string($error)."', "
."errDate = NOW(), "
."errFile = '".mysql_real_escape_string($file)."', "
."errLine = '".mysql_real_escape_string($line)."' ";
mysql_query($error_query);
}
function mysql_query_log($query) {
$result = mysql_query($query) or mysql_query_log_error($query);
return $result;
}
But when I read mysql_error() in the mysql_query_log_error() function, the original caller can't access the mysql_error() (because it returns an empty string, so it's "read out").
How can I do it in a transparent way, I mean, the mysql_error() will remain intact?
You assign the original error to a variable, then pass that variable into the function. There's no need trying to duplicate the error, when you can get it once and store it in a variable.
This should accomplish what you're trying to do :
function mysql_query_log_error($query, $error) {
$debug_trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
$caller = $debug_trace[1];
$file = substr($caller[file], strrpos($caller[file], '/')+1);
$line = $caller[line];
$error_query = "INSERT INTO Common.ERRsql SET "
."errQuery = '".mysql_real_escape_string($query)."', "
."errText = '".mysql_real_escape_string($error)."', "
."errDate = NOW(), "
."errFile = '".mysql_real_escape_string($file)."', "
."errLine = '".mysql_real_escape_string($line)."' ";
mysql_query($error_query);
}
function mysql_query_log($query) {
$result = mysql_query($query) or mysql_query_log_error($query, mysql_error());
return $result;
}
In your mysql_query_log function, you will directly store the error in a variable.

Categories