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.
Related
I am trying to run a cron job on a shared host. The cron job is working and the script is running and entering data to a table but the problem is when it reaches the point where it must save an image, it is not doing it. I need please to know why?
To tell you what I found out:
-I found out that for a script to run through a cron job, you must put the connection of the database in the same file and not include it
So here is my script with credentials being hidden:
$start_time = microtime(true);
define("DB_HOST", "*******");
define("DB_USER", "*******");
define("DB_PASS", "*******");
define("DB_NAME", "*******");
$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
//define('SITE_ROOT', $_SERVER['DOCUMENT_ROOT']);
//include "create_thumbnail.php";
// the news feeds table name is feeds_list
$query_count = "SELECT COUNT(*) FROM youtube_channels_feed_list WHERE active = 1";
$result_count = mysqli_query($connection, $query_count);
$count = mysqli_fetch_array($result_count);
$count_shift = array_shift($count);
if($count_shift > 0) {
$query_fetch = "SELECT * FROM youtube_channels_feed_list WHERE active = 1";
$result_fetch = mysqli_query($connection, $query_fetch);
while($row = mysqli_fetch_assoc($result_fetch)) {
$feed_id = $row["id"];
$feed_name = strtolower($row["feed_name"]);
$feed_url = $row["feed_url"];
$feed_region = $row["feed_region"];
$feed_length = $row["feed_length"];
$subject_id = $row["subject_id"];
$feed_source_url = $row["feed_source_url"];
$url = $feed_url;
$xml = simplexml_load_file($url);
if($xml === false){
//echo "Operation failed<br/><br/>";
} else {
$count = 0;
for($i = 0; $i < $feed_length; $i++) {
$count++;
//echo "<br/><b><i>".$feed_name.": ------</i></b><br/><br/>";
//echo "Feed Length is: ".$feed_length."<br/><br/>";
// because item 0 is about the site and not news
$title = $xml->entry[$i]->title;
$title = str_replace("'", "'", $title);
$title = str_replace('"', """, $title);
$link = $xml->entry[$i]->link->attributes()['href'];
$pubDate = $xml->entry[$i]->published;
$pubDate = strtotime($pubDate);
$insert_date = time();
$image_outer_link = $xml->entry[$i]->children( 'media', True )->group->children( 'media', True )->thumbnail->attributes()['url'];
//echo $image_outer_link . "<br/>";
// for ignore to work we must make the title field in table UNIQUE
$query1 = "INSERT IGNORE INTO youtube_videos_testing (title, link, pubDate, channel_feed_id, subject_id, insert_date) VALUES('$title', '$link', $pubDate, $feed_id, $subject_id, $insert_date)";
if($result = mysqli_query($connection, $query1)){
$the_last_inserted_id = mysqli_insert_id($connection);
echo "last inserted id: " . $the_last_inserted_id . "<br>";
$new_image_link1 = "video-" . $the_last_inserted_id . ".jpg";
$new_image_link_thumb = "youtube-video-thumb-" . $the_last_inserted_id . ".jpg";
$query2 = "UPDATE youtube_videos_testing SET image = '$new_image_link_thumb' WHERE id = " . $the_last_inserted_id;
//echo $query2. "<br>";
$result2 = mysqli_query($connection, $query2);
$affected_rows = mysqli_affected_rows($connection);
//echo "affected_rows = " . $affected_rows;
if($affected_rows > 0) {
$query3 = "UPDATE youtube_videos_testing SET updated = 1 WHERE id = " . $the_last_inserted_id;
//echo $query2. "<br>";
$result3 = mysqli_query($connection, $query3);
// HERE IS WHERE THE PROBLEM IS HAPPENING
$target_path = $_SERVER['DOCUMENT_ROOT'] . "/admin/uploads/youtube_videos_testing/" . $new_image_link1;
echo $target_path . "<br>";
// Open the file to get existing content
$data = file_get_contents($image_outer_link);
// Write the contents back to a new file
file_put_contents($target_path, $data);
}
}
}
//echo "Count: " . $count . "<br>";
}
}
} else {
//echo "database is empty";
}
// These lines should be placed at the end of the script to get the script running time
// End clock time in seconds
$end_time = microtime(true);
// Calculate script execution time
$execution_time = ($end_time - $start_time);
echo " Execution time of script = ".$execution_time." sec";
Chances are that the cron job runs either as a different user or with a different home directory than what you're expecting.
Another usual source of trouble is that with crontab scripts, the $_SERVER array is not populated because they're not being run by a web server at all. You don't have DOCUMENT_ROOT, and so on.
Since you seem able to write to the database, try saving in a text field in a debug table the result from the get_current_user() and getcwd() commands.
Alternatively, if the first command in your script is
chdir(__DIR__);
this will ensure that the script is running from the directory in which it originates.
If your script resides in your DOCUMENT_ROOT, then you can use __DIR__ instead of $_SERVER['DOCUMENT_ROOT']. Or you can add at the top
if (!isset($_SERVER)) {
$_SERVER = array();
}
$_SERVER['DOCUMENT_ROOT'] = __DIR__;
to quickly fix things.
Another solution, when available, is to have cron call your script as a Web page using lynx or curl:
curl -sk http://yourwebserver.com/path/to/script.php > /dev/null 2>&1
It is usually better to save the output to a log file to investigate possible errors (so, ">> /path/to/var/www/html/logs/debug.log" instead of "> /dev/null" -- notice the two >'s to append to a log rather than rewriting it each time).
I want to create a function that automatically makes a connection to the database and performs the given queries but I can't get it to work and it gives no errors.
I think I'm not outputting in the correct way my goal is to output a array that stores all the returned values from the queries.
Here is my code so far hope you can help:
public function db_query() {
$ini = parse_ini_file($_SERVER['DOCUMENT_ROOT'] . '/app.ini');
$mysqli = new mysqli($ini['db_location'], $ini['db_user'], $ini['db_password'], $ini['db_name']);
// create string of queries separated by ;
$query = "SELECT name FROM mailbox;";
$query .= "SELECT port FROM mailbox";
// execute query - $result is false if the first query failed
$result = mysqli_multi_query($mysqli, $query);
if ($result) {
do {
// grab the result of the next query
if (($result = mysqli_store_result($mysqli, 0)) === false && mysqli_error($mysqli) != '') {
echo "Query failed: " . mysqli_error($mysqli);
while ($row = $result->fetch_row()) {
echo $row[0];
}
}
} while (mysqli_more_results($mysqli) && mysqli_next_result($mysqli)); // while there are more results
} else {
echo "First query failed..." . mysqli_error($mysqli);
}
}
Note: I did not add the parameter for the query just for testing
purposes.
public function db_query($mysqli) {
$return = [];
$result = mysqli_query($mysqli, "SELECT name FROM mailbox");
while ($row = $result->fetch_row()) {
$return[] = $row[0];
}
$result = mysqli_query($mysqli, "SELECT port FROM mailbox");
while ($row = $result->fetch_row()) {
$return[] = $row[0];
}
return $return;
}
simple, clean, efficient, always works
I've got a number of variables that need to be looked up in a MySQL database, their values replaced with database entries, and then put together in a single string to display to the end user, code below.
I've created the below code, which while it technically works, looks really messy. Basically I'm having to look up each variable directly before it appears in the string (using the below)
$xxx = $conn->query($xxx);
This creates for really messy looking code, and also results in multiple database queries which no doubt will slow my site down. Is there a more efficient way to do this that I'm missing out on?
Any help would be greatly appreciated
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$airlinequery = "SELECT * FROM `airlines` WHERE `iatacode` = '$airline' LIMIT 0 , 30;";
$depairportquery = "SELECT * FROM `airportdata` WHERE `airportcode` = '$depdest' LIMIT 0 , 30;";
$arrairportquery = "SELECT * FROM `airportdata` WHERE `airportcode` = '$arrdest' LIMIT 0 , 30;";
$bookingclassquery = "SELECT $bookingclass FROM `bookingclass` WHERE `airline` = '$airline' LIMIT 0 , 30;";
$utctakeoffquery = "SELECT `timezonehours`,`timezoneminutes`,`timezone` FROM `airportdata` WHERE `airportcode`= '$depdest';";
$utcarriveoffquery = "SELECT `timezonehours`,`timezoneminutes`,`timezone` FROM `airportdata` WHERE `airportcode`= '$arrdest';";
if(!$result = $conn->query($airlinequery)){
die('There was an error running the query [' . $conn->error . ']');
}
$result = $conn->query($airlinequery);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$date=date_create($depdate);
echo date_format($date,"D d M"). " - ". $airline." ".$flightno;
}
}
$cabinresult = $conn->query($bookingclassquery);
if ($cabinresult->num_rows > 0) {
while($cabinrow = $cabinresult->fetch_assoc()) {
echo $cabinrow[$bookingclass];
}
}
$dresult = $conn->query($depairportquery);
if ($dresult->num_rows > 0) {
while($drow = $dresult->fetch_assoc()) {
$arr = explode(' ',trim($drow['airportname']));
if ($arr[0] == $drow['cityname']){
$drow['cityname'] = "";
}else{
$drow['cityname']= " ".$drow['cityname'];
}
echo "Depart: " .$drow['airportname'].",".$drow['cityname']." (".$drow['airportcode'].") at " . $deptime."<br>";
}
}
$aresult = $conn->query($arrairportquery);
if ($aresult->num_rows > 0) {
while($arow = $aresult->fetch_assoc()) {
$arr = explode(' ',trim($arow['airportname']));
if ($arr[0] == $arow['cityname']){
$arow['cityname'] = "";
}else{
$arow['cityname']= " ".$arow['cityname'];
}
echo "Arrive: " .$arow['airportname'].",".$arow['cityname']." (".$arow['airportcode'].") at " . $arrtime .$nextday."
";
$arrdate ="";
}
}
$conn->close();
This should be a comment, but its a bit long and will be hard to read....
SELECT *
Why are you selecting all the attributes from the table when you don't need them? You've not provided the table structures which would inform a number of choices about a solution here. If these issues had been addressed we might have been able to advise whether a UNION or VIEW would apposite.
while($row = $result->fetch_assoc()) {
$date=date_create($depdate);
echo date_format($date,"D d M"). " - ". $airline." ".$flightno;
}
What is $depdate? $airline? $flightno? Are these supposed to be values retrieved from $row? Your loop body never references $row. There are similar issues for all your queries.
I'm new to php n I'm trying to make a phone to timezone converter.
I'm getting the error undefined variable '$result' on line 49
How do I resolve it.
Also if you can find out any other mistakes I've made
Please chck for errors I'm making
Phone number:
<button type="submit" name="submit" action="submit">
Submit
</button>
</form>
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$ccode=$_POST["phone"];
// Create connection
$db = new mysqli($servername, $username, $password);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
$pattern = '/^\(?[\d]{1,4}\)?( |-)?/';
if(preg_match($pattern, $ccode, $matches))
{
$code = $matches[0];
} else $code = substr($ccode, 0, 4);
$q = "SELECT nicename FROM country.country WHERE phonecode=$code";
if($query = $db->query($q))
{
$record = $query->fetch_assoc();
} else echo "<br/>NO RECORD";
echo '<pre>';print_r($record);
if (empty($_POST["phone"]))
{
echo "<p>Please write a Phone Number!</p>";
}
$abb = "SELECT zone_id FROM zone INNER JOIN country on country.country_code = zone.country_code
WHERE country.country_name = " . $record['nicename'];
if($query = $db->query($abb))
{
$result = $query->fetch_assoc();
} else echo "<br/>NO RECORD";
echo '<pre>';print_r($result);
?>
</body>
Thanks for the help!
I believe this way it will works. I'm not sure about $code, if he contains the right information, you can check that by echo'ing the $code.
if(preg_match($pattern, $ccode, $matches))
{
$code = $matches[0];
} else { $code = substr($ccode, 0, 4); }
$q = "SELECT nicename FROM country WHERE phonecode=$code";
if($query = $db->query($q))
{
$record = $query->fetch_assoc();
echo '<pre>';
print_r($record);
} else { echo "<br/>NO RECORD"; }
$abb = "SELECT zone_id FROM zone INNER JOIN country on country.country_code = zone.country_code
WHERE country.country_name = '" . $record['nicename'] . "'";
if($query = $db->query($abb))
{
$result = $query->fetch_assoc();
echo '<pre>';
print_r($result);
//Here $result will exist!
} else { echo "<br/>NO RECORD"; }
// You had your $result here, and here, the result may not exist,
// depending if the query succeeded or not.
// Same counts for the query above.
There were 2 problems as far as I can tell.
1 was that you tried to print $record, while $record may not have existed, and the same counts for $result.
2 was the zone-query, if you check if a column/field equals a certain string, then make sure the string has quotes around itself. So country_name='something'. You didn't have these quotes around $record['nicename'], so whatever came out of $record['nicename'], he thought it was a column/field, but not a value to check upon.
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.