I have written below to extract data from webpage, but this is running continuously with out inserting data into table. How do I split this trancation in below code.
I want to insert for each url immediately and commit in loop. This is not working:
<?php
// example of how to use basic selector to retrieve HTML contents
ini_set('log_errors','0');
ini_set('display_errors','1');
error_reporting(2047);
include('simple_html_dom.php');
include('parameters.php');
// get DOM from URL or file
set_time_limit(0);
$site_name="sitename";
mysql_connect($hostname, $user, $pass) or
die("Could not connect: " . mysql_error());
mysql_select_db($database);
$query="select site_name,category,subcategory,link,first_no,last_no
from `search_links` where site_name='".$site_name."'";
echo $query;
$res=mysql_query($query);
while ($row = mysql_fetch_assoc($res))
{
$links[]=array(
"site_name"=>$row["site_name"],
"category"=>$row["category"],
"subcategory"=>$row["subcategory"],
"url"=>$row["link"],
"first_no"=>$row["first_no"],
"last_no"=>$row["last_no"]);
}
foreach ($links as $link)
{
for ($i=$link["first_no"];$i<$link["last_no"];$i++)
{
try
{
$html = file_get_html($link["url"].$i);
$sql = array();
foreach($html->find('a') as $e)
{
$sql[] = "('".$e->href."',
'".$site_name."',
'".$link["category"]."',
'".$link["subcategory"]."','N')";
}
#var_dump($sql);
mysql_connect($hostname, $user, $pass) or
die("Could not connect: " . mysql_error());
mysql_select_db($database);
$sql_ext=" ON DUPLICATE KEY update duplicate='Y'";
/*//echo('INSERT INTO table (link,site,category,subcategory, archived)
VALUES '.implode(',', $sql));*/
mysql_query(
'INSERT INTO classifieds (link,site,category,subcategory, archived)
VALUES '.implode(',', $sql).$sql_ext);
mysql_query("COMMIT");
}
catch(Exception $e)
{
echo 'Message: ' .$e->getMessage();
}
}
}
?>
mysql extension does not throw exceptions.
so, either use regular error reporting
$sql = 'INSERT INTO classifieds (link,site,category,subcategory, archived)
VALUES '.implode(',', $sql).$sql_ext;
mysql_query($sql) or trigger_error(mysql_error().$sql);
or throw an exception this way
if (!mysql_query($sql)) {
throw new Exception(mysql_error().$sql);
}
Related
I have this script that deletes a certain picture from the website. It's written with mysql functions so i wanted to update it to mysqli but doing so makes the script stop working. No die message from the script are shown no php errors and adding error_reporting(E_ALL); doesn't show any errors either.
Original script:
if(isset($_POST['F3Verwijderen']))
try
{
//delete the file
$sql = "SELECT PandFoto3 FROM tblpand WHERE `PK_Pand` = '".$pandid."'";
$con = mysql_connect('WEBSITE.mysql', 'WEBSITE', 'PASS');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("WEBSITE");
$result = mysql_query($sql, $con);
while ($row = mysql_fetch_array($result)) {
if(file_exists($_SERVER['DOCUMENT_ROOT'].'/'.$row['PandFoto3'])) {
unlink($_SERVER['DOCUMENT_ROOT'].'/'.$row['PandFoto3']);
} else {
echo $row['PandFoto3'];
}
}
//delete the path url from the database field
mysql_query("UPDATE tblpand SET PandFoto3 = NULL WHERE `PK_Pand` = '".$pandid."'");
mysql_close($con);
header('Location: ../admin/pand-aanpassen.php?id='.$pandid);
}
Updated to mysqli:
try
{
//delete the file
$sql = "SELECT PandFoto3 FROM tblpand WHERE `PK_Pand` = '".$pandid."'";
$con = mysqli_connect('WEBSITE.mysql', 'WEBSITE', 'PASS');
if (!$con) {
die('Could not connect: ' . mysqli_error());
}
mysqli_select_db("WEBSITE");
$result = mysqli_query($sql, $con);
while ($row = mysqli_fetch_array($result)) {
if(file_exists($_SERVER['DOCUMENT_ROOT'].'/'.$row['PandFoto3'])) {
unlink($_SERVER['DOCUMENT_ROOT'].'/'.$row['PandFoto3']);
} else {
echo $row['PandFoto3'];
}
}
//delete the path url from the database field
mysqli_query("UPDATE tblpand SET PandFoto3 = NULL WHERE `PK_Pand` = '".$pandid."'");
mysqli_close($con);
header('Location: ../admin/pand-aanpassen.php?id='.$pandid);
}
Edit:
"no php errors and adding error_reporting(E_ALL); doesn't show any errors either."
That's because it isn't a PHP issue, it's a MySQL issue.
Those are two different animals altogether.
As I said in commments, you need to switch these variables ($sql, $con) around ($con, $sql).
Then this:
$con = mysqli_connect('WEBSITE.mysql', 'WEBSITE', 'PASS');
Just use the 4th parameter instead of mysqli_select_db("WEBSITE"); where you didn't pass the connection variable to.
$con = mysqli_connect('WEBSITE.mysql', 'WEBSITE', 'PASS', 'WEBSITE');
The syntax is:
host
username
password (if any)
database
You also could have done mysqli_select_db($con, "WEBSITE");
Sidenote: In mysql_ (see footnotes), the connection comes last, unlike in mysqli_ which comes first.
Do the same for your UPDATE and pass the connection parameter first.
mysqli_query($con, "UPDATE...
Sidenote: To verify that the update truly was successful, use affected_rows()
http://php.net/manual/en/mysqli.affected-rows.php.
Another thing, mysqli_error() requires a connection to it mysqli_error($con) and check for errors for your queries.
I.e.:
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
References:
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/mysqli.select-db.php
Sidenote:
You're using try() but no catch(). Either remove it, or consult the manual:
http://php.net/manual/en/language.exceptions.php
Example #4 pulled from the manual:
<?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
return 1/$x;
}
try {
echo inverse(5) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} finally {
echo "First finally.\n";
}
try {
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} finally {
echo "Second finally.\n";
}
// Continue execution
echo "Hello World\n";
?>
Final notes:
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.
Footnotes: (MySQL and MySQLi comparison)
In regards to mysql_query():
mixed mysql_query ( string $query [, resource $link_identifier = NULL ]
http://php.net/manual/en/function.mysql-query.php
For mysqli_query():
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
http://php.net/manual/en/mysqli.query.php
I'm having some trouble inputting some data into a table.
I'm retrieving some values from a form and inputting them to a table, but this error shows up every time:
Error: Unknown column 'planner_id' in 'field list'
<?php
session_start();
include 'conexion_data.php';
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$teacherid = $_POST["teacherid"];
$plannerid = $_POST["plannerid"];
$yeargroup = $_POST["yeargroup"];
$subject = $_POST["subject"];
$planner_event = htmlspecialchars($_POST["event_comment"]);
$event_date = $_POST["event_date"];
echo "$teacherid $plannerid $yeargroup $planner_event $event_date <br/><br />";
if (empty($event_date) or empty($planner_event)) {
echo "One of the fields was left blank! <br />";
} else {
$sql = "INSERT INTO subject_directorio (planner_id, teacher_id, subject, yeargroup, date, comment ) VALUES ('$plannerid', '$teacherid', '$subject', '$yeargroup', '$event_date', '$planner_event')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
} else {
/* header('Location: user_area.php'); */
echo "Data was inputed to DB";
mysqli_close($con);
}
}
?>
It's very straight
while you are getting this type error :{Error: Unknown column 'planner_id' in 'field list'}
Troubleshoot first step will be Just Describe The Table [subject_directorio]
Desc subject_directorio and check planner_id is exist or not. According to to the error
subject_directorio not holding any column called as planner_id
Hope it helps!!
It's self explanatory that your table doesn't have a column planner_id. Even if you see that it has, you may have trialing spaces before or after planner_id in the column name. Check carefully.
Database
You are using wrong way how to connect to database and fetch its data.
Because you database may be hacked using SQL Injection
The right way how to do this is:
Using PDO
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
For error catching:
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
And data fetching:
$id = 5;
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));
while($row = $stmt->fetch()) {
print_r($row);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
Using Mysqli
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
And your problem
I think problem is in your query and binding params to it.So try to use proper way as I shown you, and then show us results.
SQLFiddle
Well here is the script:
<?php
session_start();
$con = mysql_connect("localhost","***","***");
mysql_query("SET NAMES UTF8");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("**8", $con);
$sql = mysql_query("TRUNCATE TABLE headset");
$qry= "INSERT INTO `headset` (`WebTitle`) VALUES ('". $_POST[webtitle] ."')";
$sql = mysql_query("TRUNCATE TABLE headset2");
$qry= "INSERT INTO `headset2` (`WebSlogan`) VALUES ('". $_POST[webslogan] ."')";
if (!mysql_query($qry,$con))
{
die('Error: ' . mysql_error());
}
header("location: ../generalsettings.php");
exit();
mysql_close($con);
?>
This is just for the one value:
I have a form with 2 boxes and I want to achieve the following: if only one of the boxes is filled I would like to truncate and insert only the value that is filled, and do nothing with the other unfilled box.
I hope you got my point.
Don't use the mysql_query functions!!! Better use the pdo class
http://php.net/manual/de/book.pdo.php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 'username', 'password');
if (isset($_POST['webtitle']) && $_POST['webtitle'] != '') {
try {
$db->query('TRUNCATE TABLE headset');
$stmt = $db->prepare("INSERT INTO headset (WebTitle) VALUES (?)");
$stmt->bindParam(1, $_POST[webtitle]);
$stmt->execute();
} catch(PDOException $ex) {
echo "An Error occured!"; //user friendly message
}
}
to check if there is value in database do this
$myquery= mysql_query(" select * from headset ");
if(mysql_fetch_row($myquery)==0){ --//there is no data in your database
}
else { --//there is data do what you like
}
*please use mysqli or PDO instead of mysql
if (isset($_POST['webtitle']) && $_POST['webtitle'] != '') {
// $_POST['webtitle'] code here
}
if (isset($_POST['webslogan']) && $_POST['webslogan'] != '') {
// $_POST['webslogan'] code here
}
And the same for the other one
This is my first post so please bear with me with inputting the code into here. Im trying to output some images to a PDF and need to create a if statement that looks for data with in a row.
$connection = mysql_connect("localhost", "testdb", "********")
or die ("Unable to connect!");
// select database
mysql_select_db("testdb") or die ("Unable to select database!");
// Select all the rows in the test table
$query = "SELECT * FROM test2 WHERE testid=89";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while ($row= mysql_fetch_array($result)) {
$image = $row[1];
$text = $row[2];
}
That's what I have so far and basically I need something along the line of this:
If (data in row 1) {
print $image;
} else {
print $text;
}
It's hard to say exactly what you're looking for since it isn't very clear, but I think what you're wanting to do is check to see if $image has a value, and if so, display it. If not, display $text instead.
If this is the case use empty(). It will tell you if a variable is empty or not.
if (!empty($image))
{
print $image;
}
else
{
print $text;
}
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
looks like you just need to test for data in $image
if(!empty($image))
{
echo $image;
}
else
{
echo $text;
}
if( !empty($row[1]) ) {
...
Use isset to check variable.
Like
if(isset($images) !='')
{
echo $images;
}
Although you are using old mysql_* functions which are depreciated, you are almost there
$connection = mysql_connect("localhost", "testdb", "********") or die ("Unable to connect!");
// select database
mysql_select_db("testdb") or die ("Unable to select database!");
// Select all the rows in the test table
$query = "SELECT * FROM test2 WHERE testid=89";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while ($row= mysql_fetch_array($result))
// This will only be called if there is a matching result.
{
echo $row[1];
echo $row[2];
}
Edit: Here is a cut and paste of a section of a query that happen to be open in eclipse:
$arrKPIData = Array();
try{
$dbh = new PDO($this->mySQLAccessData->hostname, $this->mySQLAccessData->username, $this->mySQLAccessData->password);
$stmt = $dbh->query($sql);
$obj = $stmt->setFetchMode(PDO::FETCH_INTO, new kpiData);
$dataCount=0;
foreach($stmt as $kpiData)
{
$arrKPIData[$dataCount]['year']=$kpiData->year;
$arrKPIData[$dataCount]['month']=$kpiData->month;
$arrKPIData[$dataCount]['measure']=$kpiData->kpiMeasure;
$arrKPIData[$dataCount]['var1']=$kpiData->var1;
$arrKPIData[$dataCount]['var2']=$kpiData->var2;
$dataCount++;
unset($stmt);
}
unset($dbh);
}
catch(PDOException $e){
echo 'Error : '.$e->getMessage();
exit();
}
unset($arrKPIData);
I am populating a simple array with data before I cleanse it and convert it into a class further in the code.
The below script works fine but only for the first record in the array.
$codes = array(1,2,3,4,5,6,7,8,9,10); // demo for this question, i actually have 1000+
$con = mysql_connect("localhost","user","pass");
if (!$con)
{
die('Could not connect1: ' . mysql_error());
}
$con2 = mysql_select_db("db", $con);
if (!$con2)
{
die('Could not connect2: ' . mysql_error());
}
$productsid = "select `products_id` from `coupons_products` where `coupons_id`=58386264";
$productsquery = mysql_query($productsid);
foreach ($codes as $code) {
while ($productid = mysql_fetch_assoc($productsquery)){
$sql = "insert into discount_coupons_to_products values (
'$code',
'{$productid['products_id']}')";
$con4 = mysql_query($sql);
if (!$con4)
{
die('Could not connect4: ' . mysql_error());
}
}
} // end foreach
I have an array of codes from the database that need apply only to specific products(same as 58386264). The codes works but only for the first coupon in the array ($codes).
If I understand what it means, you will need to run mysql_query command every step inside foreach, not just run mysql_fetch_assoc like you're actually doing.