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 :)
Related
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.
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);
}
}
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
I have a variable formvar that is incremented every time a user adds an additional field in an HTML form. This variable is posted to the PHP script for the purpose of looping through all of the added fields.
I am trying to combine two variables in the MySQL query to match what is in my HTML form. I would like the MySQL query to go upc0, upc1, etc until the for loop terminates.
for($i=0;$i<=$_POST[formvar];$i++)
{
mysql_select_db("bits", $con);
$sql="INSERT INTO report (UPC, Quantity, Comment)
VALUES ('$_POST[upc].$i','$_POST[quantity].$i','$_POST[comment].$i')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else echo "Records added successfully";
}
Sorry if this code is bad, I am new to web programming.
Thank you!
Ok, since each answer hinted at escaping (but did not give an example):
$sql = "INSERT INTO report (UPC, Quantity, Comment) VALUES
('" . mysql_real_escape_string($_POST["upc".$i]) . "','" .
mysql_real_escape_string($_POST["quantity" . $i]) . "','" .
mysql_real_escape_string($_POST["comment" . $i]) . "')";
That should protect you from SQL Injection, and is one proper method of creating sql queries. The best method would be to use parametrized queries (There's a ton of information out there on it, so I'd suggest a good Google search would be better than me trying to explain it here)...
First things first. In your HTML, create Input-Fields like this:
<input type="foo" name="upc[]">
<input type="foo" name="quantity[]">
<input type="foo" name="comment[]">
Then in your PHP-Script you do it like this:
<?php
# Choose DB
mysql_select_db("bits", $con);
# Iterates the Form-Data
$data_arr = array();
foreach($_POST['upc'] as $k=>$v) {
# Makes sure all needed data is available
if(isset($_POST['quantity'][$k], $_POST['comment'][$k])) {
$data_arr[] = array(
'upc' => $v,
'quantity' => $_POST['quantity'][$k],
'comment' => $_POST['comment'][$k]
);
}
}
# Build mysql insert string
foreach($data_arr as $k=>$v) {
# Escapes each field
$v = array_map('mysql_real_escape_string', $v);
# Maps array to value set
$data_arr[$k] = '('. implode(',', $v). ')';
}
$sql = 'INSERT INTO report (UPC, Quantity, Comment) VALUES '. implode(', ', $data_arr);
# Perform mysql query
mysql_query($sql, $con) or die('Error: ' . mysql_error());
echo 'Records added successfully';
Wrote it on my iPad, i'm on an airplane... so untestet. Good luck. ;o)
Not sure if I understand the question well but this is what I think :
$sql="INSERT INTO report (UPC, Quantity, Comment) VALUES
('" . $_POST["upc".$i] . "','" . $_POST["quantity" . $i] . "','" . $_POST["comment" . $i] . "')";
Note : this is a short version, you must add mysql_real_escape_string, etc, etc.
Also I supposed every variable could be string so I surrounded them by ''.
$_POST["name" . $i] let you loop throught POST variables starting with the name "name" followed by a number, this must be inserted into your for loop.
As recipes are so acclaimed I'm going to give my own, concerning the actual question:
<?php
for ($i=0; $i<=$_POST['formvar']; ++$i) {
mysql_select_db("bits", $con);
$v = array_map(mysql_real_escape_string(array(_POST["upc{$i}"], $_POST["quantity{$i}"], $_POST["comment{$i}"])));
$sql = "INSERT INTO report (UPC, Quantity, Comment) VALUES('"
. implode("', '", $v)
. "')";
if (!mysql_query($sql,$con)) {
trigger_error(html_entities('Error: ' . mysql_error()));
}
}
?>
I am able to generate the activation_key in the following code. But I can't manage to insert it into the table. Blank value gets inserted into the table.
What am I doing wrong? (using PEAR text password and other extensions)
$activation_key = Text_Password::createFromLogin($data['email'], 'rot13');
$sql = "INSERT INTO auth (firstname, lastname,gender,dob,mobileno,landlineno,addressline1,addressline2,addressline3,country,state,city,pincode,email,username,password,question,answer,activation_key)
VALUES ('" . $db->escapeSimple($data['firstname']) . "','"
. $db->escapeSimple($data['lastname'])."','"
. $db->escapeSimple($data['gender'])."','"
. $db->escapeSimple($data['dob'])."','"
. $db->escapeSimple($data['mobileno'])."','"
. $db->escapeSimple($data['landlineno'])."','"
. $db->escapeSimple($data['address1'])."','"
. $db->escapeSimple($data['address2'])."','"
. $db->escapeSimple($data['address3'])."','"
. $db->escapeSimple($data['country'])."','"
. $db->escapeSimple($data['state'])."','"
. $db->escapeSimple($data['city'])."','"
. $db->escapeSimple($data['pin'])."','"
. $db->escapeSimple($data['email'])."','"
. $db->escapeSimple($data['username'])."','"
. md5($db->escapeSimple($data['pwd']))."','"
. $db->escapeSimple($data['question'])."','"
. $db->escapeSimple($data['answer']). "', '"
. $db->escapeSimple($data['activiation_key'])."')";
$db->query($sql);
$data['$activiation_key'] doesn't actually appear to hold $activation_key
plus if you really cut and paste then $activiation_key is spelt wrongly