I tried to use mysqli in for my forum database. this is the code I used:
<meta charset="utf-8">
<?php
include("config.php");
$limits = "6";
$forum_id = "2";
$db = new mysqli($INFO['sql_host'], $INFO['sql_user'], $INFO['sql_pass'], $INFO['sql_database']);
$topics = $db->query("
SELECT
`topics`.`start_date`,
`topics`.`title`,
`topics`.`starter_name`,
`topics`.`posts`,
`topics`.`title_seo`,
`topics`.`tid`,
`posts`.`post`
FROM
`" . $INFO['sql_tbl_prefix'] . "topics` as `topic`,
`" . $INFO['sql_tbl_prefix'] . "posts` as `post`
WHERE
`topics`.`approved` = 1 AND
`topics`.`forum_id`= " . $forum_id . " AND
`posts`.`topic_id` = `topic`.`tid` AND
`posts`.`new_topic` = 1
ORDER BY
`topics`.`start_date`
DESC LIMIT 5");
echo '<ul id="news">';
while ($topic = $topics->fetch_object()) {
$url = $INFO['board_url'] . '/index.php?/topic/' . $topic->tid . '-' . $topic->title_seo . '/';
$topic->post = strip_tags(str_replace(array('[', ']'), array('<', '>'), $topic->post));
$topic->start_date = date("Y.m.d H:i", $topic->start_date);
echo '
<div class="news">
<div class="newsp"><div class="pteksts">' . $topic->title . '</div></div>
<center><img src="img/news.png"></center>
<div class="teksts" style="padding-bottom: 5px;">' . $topic->post . '</div>
</div>
';
}
echo '</ul>';
?>
and errors i received:
Fatal error: Call to a member function fetch_object() on a non-object in /home/public_html/scripts/news.php on line 35
You give aliases for your tables as topic and post, but then you use the aliases topics and posts. You need to change the table qualifiers to use the same spelling as your table alias.
Wrong, because alias topic is not the same as table qualifier topics:
SELECT
`topics`.`start_date`, . . .
FROM
`" . $INFO['sql_tbl_prefix'] . "topics` as `topic`,
. . .
Right, after changing the table qualifier to match the alias name:
SELECT
`topic`.`start_date`, . . .
FROM
`" . $INFO['sql_tbl_prefix'] . "topics` as `topic`,
. . .
Right as well, but alias is unnecessary if it's the same as the base table name:
SELECT
`topics`.`start_date`, . . .
FROM
`" . $INFO['sql_tbl_prefix'] . "topics` as `topics`,
. . .
But more to the point, you should always check the return value from $db->query(), because it returns false if there's an error. You can't call any method on a false because that's not an object.
If that happens, report the error but do not try to fetch from the result. It won't work.
$topics = $db->query(...);
if ($topics === false) {
die($db->error);
}
// now we can be sure it's safe to call methods on $topics
while ($topic = $topics->fetch_object()) {
. . .
Re your comment that the output is blank:
I just tested this script and it mostly works, so I can't guess what's going wrong. I suggest you read your http server's error log, which is where many PHP notices and errors are output.
I do see the following notice:
Notice: A non well formed numeric value encountered in /Users/billkarwin/workspace/SQL/22159646.php on line 51
The line is this:
$topic->start_date = date("Y.m.d H:i", $topic->start_date);
The problem is that PHP's date() function takes an integer timestamp, not a date string.
You might want to format the date in SQL, using MySQL DATE_FORMAT() function instead.
Related
I already searched for my answer, but all of the solutions do not fit to my problem. I want to build a forum, where first of, all questions are requested from my MySQL database. Then I want to find out the date of the latest entry for each question, so I created this:
while ($array = mysqli_fetch_assoc($res_page)) {
$get_latest_date = "select * from forum"
. " where id = "
. $array["id"]
. ' order by date DESC'
. ' limit 1';
$latest_date = mysqli_query($con, $get_latest_date);
$date = mysqli_fetch_row($latest_date);
echo '<div class="forum_preview">'
. '<a href=#" class="forum_preview_question">'
. $array["question_short"]
. '</a>'
. '<p class="forum_preview_date">'
. $date["date"]
. '</p>'
. '<p class="forum_preview_comments">'
. $number_of_questions
. '</p>'
. '</div>';
}
My problem is, that showing the latest date is not working, because I cannot get the result out of my mysqli_query.
Can anybody show me where my mistake is or does anybody have another idea?
I think what you are looking for is mysqli_fetch_assoc, mysqli_fetch_row returns an array, mysqli_fetch_assoc returns an associative array so you can get data by keys.
$latest_date = mysqli_query($con, $get_latest_date);
$date = mysqli_fetch_assoc($latest_date);
echo $date["date"];
I have included the php code run on the server side that is failing with the following error:
Parse error: syntax error, unexpected T_ELSE in
/home3/atljj/public_html/Osler/include/vo2_membersite.php on line 2849
No clue why it is stopping on the ELSE statement ???
Short story... I want to write a program to create and maintain a 1 record MYSQL control file.
I am writing the code in steps and so far have:
Written HTML code to via a form, submit to the server a request to create the table with the proper fields.
The server was then re-written to write the first record into the table via the INSERT statement.
All is well to this point... I have 1 record in the MySQL file and next I only need to update it.
The server was changed to test for a record already existing and if so bypass the INSERT code and run the UPDATE code instead... But I do not see where the problem is, other than I am attempting to use MYSQLi code now.
Is my table checking done wrong, I'm searching for record 1 and if not found use INSERT ELSE use the UPDATE...
function UpdateCase(&$formvars)
{
$con = mysqli_connect($this->db_host,$this->username,$this->pwd,$this->database);
if (mysqli_connect_errno())
{
$this->HandleDBError("Failed to connect to MySQL");
return false;
}
$c_match = $this->RandomIt();
$c_username = "admin";
$qry = "Select * from $this->case_c_table WHERE c_id = 1";
if(!$result = mysqli_query($con,$qry));
{ /* first entry not found add to table*/
$c_flag="M";
$addit = 'INSERT INTO $this->case_c_table (
c_match,
c_flag,
c_username,
c_element,
c_patname,
c_patgndr,
c_patage,
c_patethncty,
c_patdate,
c_cc,
c_td,
c_lmpdate
)
values
(
"' . $c_match . '",
"' . $c_flag . '",
"' . $c_username . '",
"' . $this->SanitizeForSQL($formvars['c_element']) . '",
"' . $this->SanitizeForSQL($formvars['c_patname']) . '",
"' . $this->SanitizeForSQL($formvars['c_patgndr']) . '",
"' . $this->SanitizeForSQL($formvars['c_patage']) . '",
"' . $this->SanitizeForSQL($formvars['c_patethncty']) . '",
"' . $this->SanitizeForSQL($formvars['c_patdate']) . '",
"' . $this->SanitizeForSQL($formvars['c_cc']) . '",
"' . $this->SanitizeForSQL($formvars['c_td']) . '",
"' . $this->SanitizeForSQL($formvars['c_lmpdate']) . '"
)';
mysqli_query($con,$addit);
}
else
{
$qry="Update $this->case_c_table Set
c_element=". $this->SanitizeForSQL($formvars['c_element']).",
c_patname=". $this->SanitizeForSQL($formvars['c_patname']).",
c_patgndr=". $this->SanitizeForSQL($formvars['c_patgndr']).",
c_patage=" . $this->SanitizeForSQL($formvars['c_patage']).",
c_patethncty=". $this->SanitizeForSQL($formvars['c_patethncty']).",
c_patdate=". $this->SanitizeForSQL($formvars['c_patdate']).",
c_cc=". $this->SanitizeForSQL($formvars['c_cc']).",
c_td=". $this->SanitizeForSQL($formvars['c_td']).",
c_lmpdate=". $this->SanitizeForSQL($formvars['c_lmpdate'])."
WHERE c_id=1";
mysqli_query($con,$qry);
}
}
Hi I'm trying to call several functions that I have defined in php within mysql_query. The sql query executes successfully however all the columns which should contain values from functions are left empty in the database. The sql query looks like this:
$sqldescription = description($e->href);
$sqlimage = image($e->href,$e->innertext);
$sqlstatus = status($e->href);
$sqlgenre = genre($e->href);
$sqlauthor = author($e->href);
$sqlrelease = release($e->href);
$sql = "INSERT INTO manga (`manga_title`, `manga_description`, `manga_thumnail`, `manga_latest_chap`, `manga_status`, `manga_genre`, `manga_author`, `manga_released_date`, `manga_added_date`, `manga_link`) VALUES
('" . $e->innertext . "', '" . $sqldescription . "', '$sqlimage', '0', '$sqlstatus', '$sqlgenre', '$sqlauthor', '$sqlrelease', '" . date("Y-m-d") . "', '" . $e->href . "')";
mysql_query($sql,$con);
most of the functions are pretty similar and here is what one of them looks like:
function description($url){
$descriptionhtml = new simple_html_dom();
$descriptionhtml->load_file($url);
foreach ($descriptionhtml->find('p.summary') as $d)
echo $d;
}
I would appreciate any help :)
I am having a small issue with some coding of mine. For some reason my entries aren't dropping in my DB. Any suggestions would be greatly appreciated! Here is my code...
<?php
$dbhost="localhost";
$dbname="DBNAME";
$dbuser="USER";
$dbpasswd="PASSWORD"; // connect to the db
$dbcxn = mysqli_connect($dbhost, $dbuser, $dbpasswd);
if (!$dbcxn) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysqli_select_db($dbcxn, $dbname);
if (!$db_selected) {
die ('Can\'t use dbreviews : ' . mysql_error());
}
$query = "INSERT INTO entries ( submitterFirstName, submitterLastName, submitterPhone, submitterEmail, referredFirstName, referredLastName, referredPhone, referredEmail, referredReason)
VALUES ('$submitterFirstName', '$submitterLastName', '$submitterPhone', '$submitterEmail', '$referredFirstName', '$referredLastName', '$referredPhone', '$referredEmail', '$referredProject')";
$result=mysqli_query($dbcxn, $query);
?>
The first thing you want to check is echo the query back to yourself and read it over.
Second, check the table structure. Make sure the column names are all spelled correctly and that all fields exist in your table (I've accidently forgotten to add a column before).
Third, you may or may not receive error messages depending on your configuration. But, you can manually check.
if (!$result) {
echo mysqli_error($dbcxn);
}
First thing first should be code formatting, it will help you read the code and consequently find your errors easier.
$query = "
INSERT INTO
entries
(
submitterFirstName,
submitterLastName,
submitterPhone,
submitterEmail,
referredFirstName,
" .
"referredLastName,
referredPhone,
referredEmail,
referredReason
)
" .
" VALUES
(
'$submitterFirstName',
'$submitterLastName',
'$submitterPhone',
' $submitterEmail',
'$referredFirstName'," .
"'$referredLastName',
'$referredPhone',
'$referredEmail',
'$referredProject'
);
"
The above is your query string split onto several lines, there are some errors which should be evident straight away? Once formatted I would do echo $query and view the output of $query.
Also try seeing if you can do an insert without using php (using mysql workbench, php admin etc) then compare it with the string value you have set as $query.
// less errors, please note that inside "" you can include php $vars without needing to escape.
$query = "
INSERT INTO
entries
(
submitterFirstName,
submitterLastName,
submitterPhone,
submitterEmail,
referredFirstName,
referredLastName,
referredPhone,
referredEmail,
referredReason
)
VALUES
(
'$submitterFirstName',
'$submitterLastName',
'$submitterPhone',
'$submitterEmail',
'$referredFirstName',
'$referredLastName',
'$referredPhone',
'$referredEmail',
'$referredProject'
);
";
Change your query variable to:
$query = "INSERT INTO entries " .
"( submitterFirstName, submitterLastName, submitterPhone, submitterEmail, referredFirstName, " .
" referredLastName, referredPhone, referredEmail, referredReason )" .
" VALUES ('" .
$submitterFirstName . "', '" .
$submitterLastName . "', '" .
$submitterPhone . "', '" .
$submitterEmail . "', '" .
$referredFirstName . "', '" .
$referredLastName . "', '" .
$referredPhone . "', '" .
$referredEmail . "', '" .
$referredProject . "')";
and it should be working.
Suggesting to use mysqli prepare
There is nothing wrong with my code, but I just cant help but wonder, should I wrap the $key with mysql_real_escape_string? This is just part of my Database function which is mainly used to pull data out of the database with table name and $where as arguments to the function. $where is to be an associative array with keys being column name, and values being the data.
This is what processes the $where array. Before this I have $sql = 'select * from ' . $table;
if(!empty($where)){
$where_count = count($where);
$sql .= ' WHERE ';
foreach($where as $key => $value){
$split_key = explode(' ', $key);
if(count($split_key) > 1){
$sql .= $key[0] . ' ' . $key[1] . ' "' . mysql_real_escape_string($value) . '" ';
} else {
$sql .= $key . ' = "' . mysql_real_escape_string($value) . '" ';
}
}
}
Filter ANY INPUT from the user that is going to be placed in your query. No doubt!
So if the keys are supplied by the user, YES and if they are generated in a safe manner, NO.
Take a look at SQL Injection to understand why filtering must be done.
I am not sure what is being asked here, but I can see one error:
$sql .= $key[0] . ' ' . $key[1] . ' "' . mysql_real_escape_string($value) . '" ';
should be
$sql .= $split_key[0] . ' ' . $split_key[1] . ' "' . mysql_real_escape_string($value) . '" ';
If you really want to quote field names, use backticks.
See http://dev.mysql.com/doc/refman/5.6/en/identifiers.html
The following statement creates a table named a`b that contains a
column named c"d:
CREATE TABLE `a``b` (`c"d` INT);