I have this error:
Call to a member function bind_param() on a non-object
in /home/ccraft50/public_html/C-Blog/InsertDataPosts.php on line 15
<?php
$servername2 = "localhost";
$username2 = "My DB";
$password2 = "My Pass";
$dbname2 = "My DB";
// Create connection
$dbconn2 = new mysqli($servername2, $username2, $password2, $dbname2);
// Check connection
if ($dbconn2->connect_error) {
die("Connection failed: " . $dbconn2->connect_error);
}
$insIndexData = $dbconn2->prepare("INSERT INTO " . str_replace(str_split('\\/:*?"<>|.$+-%##!~&;\',=~` '), "_", $_POST['filename']) . "_Index (SubjectName, IndexData) VALUES (?, ?)");
$str_prot_index = array('<script>', '</script>', '<?php', '?>', '<html', '</html>', '<body', '</body>', '<head', '</head>', '<pre', '</pre>', '<div', '</div>');
$insIndexData->bind_param('ss', $_POST['filename'], str_replace($str_prot_index, '', $_POST['comment']));
$insIndexData->execute();
$insIndexData->close();
if($dbconn2->prepare($insIndexData)) {
echo "Successfuly Insert data for index!";
} else {
echo "Error: " . $dbconn2->error;
}
$dbconn2->close();
?>
You are using a database wrong way.
A database have to consist of tables, each holding multiple rows. While you apparently want to create a distinct table for each file. Instead, you have to store all your files in a single table, adding a filename as a field, not a table name.
$stmt = $dbconn2->prepare("INSERT INTO files (SubjectName, IndexData) VALUES (?, ?)");
$stmt->bind_param('ss', $_POST['filename'], $_POST['comment']);
$stmt->execute();
echo "Successfuly Insert data for index!";
Note that the second part of code which is preparing the same query in a second time makes no sense. To test whether the insert were successful or not, you have to add this line before new mysqli(:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
And it will throw an error if insert fails.
Your prepare is failing. Try to add some testing to make sure its preparing correctly. After you ->prepare
if($insIndexData !== false)
{
etc...
Related
My question is, how efficient are PHP Mysqli prepared statements? From what I have understand from basic reading, prepared statements 1) help in security using bound inputs 2) speed up and 'reduce' data sent to the server by somewhat 'pre-packaging' or 'preparing' the sql query to an extent, and once data is available, it just attaches the data to the prepared statement and executes it. This also helps on 'repeated' use of the same statement when inserting the same data (different values) repeatedly, because the statement is prepared only once.
Now, I am building a website with several functionalities, and all (or most) of them use JQuery and AJAX to get obtain user input, do some checks (either in the JS/JQ or in PHP), Send the data to a PHP file PHP_AJAX_Handler.php specified in the AJAX URL. The PHP file prepares the SQL statemtns to insert data into database, then return JSON success/failure messages. For example, most of my features/functionality are programmed as follows; below is one file which I am using to 1) check for existing continent-country pair, and 2) insert the new continent-country pair.
HTML:
<input type='text' id='continent'>
<input type='text' id='country'>
<button id='btn1'></button>
<p id='p1'></p>
<p id='p2'></p>
<p id='p3'></p>
JQuery:
$("#btn1")click(function(){
var Cntt = $("#continent").val();
var Ctry = $("#country").val();
$.post("PHP_AJAX_Handler.php",{CN:cntt,CT:ctry},function(DAT)
{ var RET_j = json.PARSE(dat);
if(RET_j.PASS=='FAIL')
{ $('#p1').html(RET_j.PASS);
$('#p2').html(RET_j.MSG1);
}
if(RET_j.PASS=='OKAY')
{ $('#p1').html(RET_j.PASS);
$('#p3').html(RET_j.MSG2);
} }
);
});
PHP_AJAX_Handler.php
<?PHP
session_start();
if( (isset($_POST['CT'])) && (isset($_POST['CN'])))
{ require_once ("golin_2.php");
$CN = $_POST['CN'];
$CT = $_POST['CT'];
$ER = "";
$CONN = mysqli_connect($SERVER, $USER, $PASS, $DBNAME);
If($CONN == FALSE)
{ $ER = $ER . "Err: Conn Could not connect to Databse ".mysqli_connect_errno().' '.mysqli_connect_error();
}
else
{ $SQL_1 = "SELECT * FROM sailors.continental_regions WHERE CONTINENT = ? AND COUNTRY = ?";
if(!($STMT_1 = mysqli_stmt_init($CONN)))
{ $ER = $ER . "Err: Stmt Prepare Failed";
}
else
{ if(!mysqli_stmt_prepare($STMT_1, $SQL_1)) ///FIRST SET of prepared statement lines
{ $ER = $ER . "Err: Stmt Prepare Failed";
}
else
{ if(!mysqli_stmt_bind_param($STMT_1,"ss",$CN, $CT))
{ $ER = $ER . "Err: Stmt Prepare Failed";
}
else
{ if(!(mysqli_stmt_execute($STMT_1)))
{ $ER = $ER . "Err: Stmt_1 Execute Failed";
}
else
{ $RES_1 = mysqli_stmt_get_result($STMT_1);
$NUMROWS_1 = mysqli_num_rows($RES_1);
if($NUMROWS_1>0)
{ $ER = $ER . "Err: duplicate '$CN' '$CT' pair";
}
if($NUMROWS_1==0)
{ $SQL_2 = "INSERT INTO DB.continental_regions (CONTINENT,COUNTRY) values (?, ?)";
if(!($STMT_2=(mysqli_stmt_init($CONN))))
{ $ER = $ER . "Err: Init2 failed";
}
else
{ if(!mysqli_stmt_prepare($STMT_2, $SQL_2)) ///SECOND SET of prepared statement lines
{ $ER = $ER . "Err: Prep2 failed".mysqli_error($CONN);
}
else
{ if(!mysqli_stmt_bind_param($STMT_2,"ss",$CN, $CT))
{ $ER = $ER . "Err: Bind2 failed";
}
else
{
if(!(mysqli_stmt_execute($STMT_2)))
{ $ER = $ER . "Err: Exec failed";
}
else
{ $arr['PASS'] = 'OK';
}
}
}
}
}
}
}
}
}
mysqli_free_result($RES_1);
mysqli_stmt_close($STMT_1);
mysqli_stmt_close($STMT_2);
mysqli_close($CONN);
}
if($ER!=="")
{ $arr['MSG'] = $ER;
$arr['PASS'] = 'FAIL';
}
if($arr['PASS']=="OK")
{ $arr['MSG2'] = "Insert Success";
}
echo json_encode($arr);
}
else
{ header("location: ../Error_Fail.php");
}
?>
As you can see, the PHP file is turning out to be pretty long. There is one set of prepare statements to check if the CC pair exists already in table, then another to insert the CC pair.
From what I see, for each AJAX request to add a new pair of values, the mysqli statements are prepared over again. Then again for the next request, and so on. I imagine this is creating a lot of overhead and data to the server just to achieve Security. Is this true for other people developing web applications with AJAX-POST-PHP? to me it seems unavoidable that for each prepare, values can only be inserted one time? How to get around to preparing this statement once, and only doing repeat executes whence data is available? I can't seem to get my head around the 'efficiency' factor of prepared statements..
Thanks.. would appreciate some advise from some seasoned programmers out there..
You said:
As you can see, the PHP file is turning out to be pretty long.
That is true, but that is not the fault of prepared statements. You must have been learning PHP development from a poorly written tutorial. This code does not need to be so long. In fact, it can be severely shortened.
Just fixing your existing code made it much more readable. I used OOP-style mysqli and I removed all these if statements. You should enable error reporting instead.
<?php
session_start();
if (isset($_POST['CT'],$_POST['CN'])) {
require_once "golin_2.php";
$CN = $_POST['CN'];
$CT = $_POST['CT'];
$ER = "";
$arr = [
'PASS' => "OK",
'MSG2' => "Insert Success",
]; // successful state should be the default outcome
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$CONN = new mysqli($SERVER, $USER, $PASS, $DBNAME);
$CONN->set_charset('utf8mb4'); // always set the charset
// To check existance of data in database we use COUNT(*)
$stmt = $CONN->prepare("SELECT COUNT(*) FROM sailors.continental_regions WHERE CONTINENT = ? AND COUNTRY = ?");
$stmt->bind_param("ss", $CN, $CT);
$stmt->execute();
$NUMROWS = $stmt->get_result()->fetch_row()[0];
if ($NUMROWS) {
$ER .= "Err: duplicate '$CN' '$CT' pair";
} else {
$stmt = $CONN->prepare("INSERT INTO DB.continental_regions (CONTINENT,COUNTRY) values (?, ?)");
$stmt->bind_param("ss", $CN, $CT);
$stmt->execute();
}
if ($ER) {
$arr = [
'PASS' => "FAIL",
'MSG' => $ER,
];
}
echo json_encode($arr);
} else {
header("location: ../Error_Fail.php");
}
If you have a composite UNIQUE key on these two columns in your table then you can remove the select statement. Also, you should clean up your response preparation. The successful state should be the default and it should be replaced with the error message only if something went wrong.
In this example, I removed one SQL statement. The whole thing is now much simpler.
<?php
define('DUPLICATE_KEY', 1062);
session_start();
if (isset($_POST['CT'],$_POST['CN'])) {
require_once "golin_2.php";
$CN = $_POST['CN'];
$CT = $_POST['CT'];
$arr = [
'PASS' => "OK",
'MSG2' => "Insert Success",
]; // successful state should be the default outcome
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$CONN = new mysqli($SERVER, $USER, $PASS, $DBNAME);
$CONN->set_charset('utf8mb4'); // always set the charset
try {
$stmt = $CONN->prepare("INSERT INTO continental_regions (CONTINENT,COUNTRY) values (?, ?)");
$stmt->bind_param("ss", $CN, $CT);
$stmt->execute();
} catch (mysqli_sql_exception $e) {
if ($e->getCode() !== DUPLICATE_KEY) {
// if it failed for any other reason than duplicate key rethrow the exception
throw $e;
}
// if SQL failed due to duplicate entry then set the error message
$arr = [
'PASS' => "FAIL",
'MSG' => "Err: duplicate '$CN' '$CT' pair",
];
}
echo json_encode($arr);
} else {
header("location: ../Error_Fail.php");
}
Regarding performance.
There is no problem with performance in this example and prepared statements don't improve or degrade the performance. I assume you are trying to compare the performance to static SQL queries, but in your simple example there should be no difference at all. Prepared statements can make your code faster compared to static queries when you need to execute the same SQL many times.
If you find writing the 3 lines of code each time too much, then you can create a wrapper function that will reduce it for you to a single function call. In fairness you should avoid using mysqli on its own. Either switch to PDO or use some kind of abstraction library around mysqli.
I am getting error
Undefined variable: company_name.
but some fields are inserted in database.
<?php
$con=mysqli_connect("localhost","root","","vdl");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$Company_name = $_POST['company_name'];
$since = $_POST['since'];
$strength = $_POST['strength'];
$head_quarter = $_POST['head_quarter'];
if($company_name !=''||$since !=''){
mysqli_query($con,"insert into digital_library(company_name, since, strength, head_quarter) values ('$company_name', '$since', '$strength', '$head_quarter')");
mysqli_close($con);
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
?>
First of all, mysql_* functions are deprecated as of PHP 5.5, and have been completely removed as of PHP 7.0.
Staying up to date with whats new and good now you reguarly want to update things aswell as PHP. Knowing that the mysql_* functions are deprecated (not under active development) we should not use them anymore (we can't even use them anymore if you have updated your php). Anyways back to the point you should not use mysql_* functions especially not now you are new to programming because you will have to update your php someday meaning you will have to change all of your code.
As of the code below:
This is mysqli_* mysqli.php
I have added a check on the db connection checking if that is actually working since you did not check the connection. Because even without that connection working that if loop would still return you your echo.
In mysqli_* you also have to add the connection in the query string.
<?php
$con=mysqli_connect("localhost","root","","vd1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$company_name = $_POST['company_name'];
$since = $_POST['since'];
$strength = $_POST['strength'];
$head_quarter = $_POST['head_quarter'];
if($company_name !=''||$since !=''){
mysqli_query($con,"insert into digital_library(company_name, since, strength, head_quarter) values ('$company_name', '$since', '$strength', '$head_quarter')");
mysqli_close($con);
}
}
?>
First of all mysql is deprecated. Don't use mysql. Use either mysqli or pdo.
In your given code,
Add condition after $query statement to get exact error.
if (!$query) {
$message = 'Invalid query: ' . mysql_error() . "\n";
die($message);
}
else {
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
You should trace all errors that may occur. I suggest to use prepared statement, try this:
<?php
$sql = new mysqli("localhost", "root", "", "vdl");
if($sql->connect_errno)
return printf("MySQL Connection Error #%d: %s", $sql->connect_errno, $sql->connect_error);
// I'd recommend to not use $_POST['submit'], it'd be better to check all the fields (company_name, since, strength, head_quarter) using the strlen() function
// for example: if(strlen($company = $_POST["company_name"]) && strlen($since = $_POST["since"])) ... etc.
if(isset($_POST["submit"]))
{
if(!$sm = $sql->prepare("INSERT INTO `digital_library` (`company_name`, `since`, `strength`, `head_quarter`) VALUES (?, ?, ?, ?)"))
return printf("Unable to prepare statement. Error #%d: %s", $sm->errno, $sm->error);
if(!$sm->bind("ssss", $_POST["company_name"], $_POST["since"], $_POST["strength"], $_POST["head_quarter"]))
return printf("Unable to bind parameters. Error #%d: %s", $sm->errno, $sm->error);
if(!$sm->execute())
return printf("MySQL Query Error #%d: %s", $sm->errno, $sm->error);
printf("The query has successfully executed!");
} else
printf("There's nothing to see, get outta here");
?>
If you don't want to use prepared statement, do this:
<?php
$sql = new mysqli("localhost", "root", "", "vdl");
if($sql->connect_errno)
return printf("MySQL Connection Error #%d: %s", $sql->connect_errno, $sql->connect_error);
if(
strlen( $company = $sql->real_escape_string($_POST["company_name"]) )
&& strlen( $since = $sql->real_escape_string($_POST["since"]) )
&& strlen( $strength = $sql->real_escape_string($_POST["strength"]) )
&& strlen( $head_quarter = $sql->real_escape_string($_POST["head_quarter"]) )
) {
$query = sprintf("INSERT INTO `digital_library` (`company_name`, `since`, `strength`, `head_quarter`) VALUES ('%s', '%s', '%s', '%s')", $company, $since, $strength, $head_quarter);
if(!$q = $sql->query($query))
return printf("MySQL Query Error #%d: %s", $sql->errno, $sql->error);
printf("The query has successfully executed!");
} else
printf("There's nothing to see, get outta here");
?>
Do one thing and It will be easy for you to debug-
Change this
$query = mysql_query("insert into digital_library(company_name, since, strength, head_quarter) values ('$company_name', '$since', '$strength', '$head_quarter')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
to
echo "insert into digital_library(company_name, since, strength, head_quarter) values ('$company_name', '$since', '$strength', '$head_quarter')";
Now when you submit you get the original query in response.
Now run this query in phpmyadmin manually and see the results. Correct the issues phpmyadmin gives you and update your query in your script accordingly.
I have already a script which scrapes all the urls of one csv with simple HTML dom.
The output is like this:
CoolerMaster Devastator II Azul
Coolbox DeepTeam - Combo teclado, ratón y alfombrilla
Asus Claymore RED - Teclado gaming
INSERT INTO productos (nombre) VALUES('Asus Claymore RED - Teclado gaming')
Items added to the database!
INSERT INTO productos (nombre) VALUES('Asus Claymore RED - Teclado gaming')
Items added to the database!
INSERT INTO productos (nombre) VALUES('Asus Claymore RED - Teclado gaming')
Items added to the database!
As you can see, the scrape contains 3 different products, but when I try to insert to the MySQL database, it only saves the last product --- but three times.
Here you can see my PHP Code for that:
<?php
require 'libs/simple_html_dom/simple_html_dom.php';
set_time_limit(0);
function scrapUrl($url)
{
$html = new simple_html_dom();
$html->load_file($url);
global $name;
$names = $html->find('h1');
foreach ($names as $name) {
echo $name->innertext;
echo '<br>';
}
$rutaCSV = 'csv/urls1.csv'; // Ruta del csv.
$csv = array_map('str_getcsv', file($rutaCSV));
foreach ($csv as $linea) {
$url = $linea[0];
scrapUrl($url);
}
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
foreach ($csv as $linea) {
$url = $linea[0];
$sql = "INSERT INTO productos (nombre) VALUES('$name->plaintext')";
print ("<p> $sql </p>");
if ($conn->query($sql) === TRUE) {
echo "Items added to the database!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
So, what I need is the MySQL query add:
INSERT INTO productos (nombre) VALUES('CoolerMaster Devastator II Azul')
Items added to the database!
INSERT INTO productos (nombre) VALUES('Coolbox DeepTeam - Combo teclado, ratón y alfombrilla')
Items added to the database!
INSERT INTO productos (nombre) VALUES('Asus Claymore RED - Teclado gaming')
Items added to the database!
You have a bunch of problems in your code.
First, you have function scrapUrl, that takes $url as an argument, but doesn't output anyhting. It's setting global $name variable, but, although it's find several names, it putting only the last one to the $name variable, because it's walking through a series of $names, put it's text into $name, and go for the next one, so, only last item is stored to your $name variable.
I would recommend, that your change your scrapUrl function, so it store names of scrapped products into an array, and return that array.
Second, I'm cannot understand how do you put your data into a csv file, the code, you've privided looks like it shouldn't work properly. Are you sure, that you are writing the right data in a csv file? Maybe here you are just reading data from file - in that case, I'm sorry.
The third: you are reading data from csv, and when moving line by line in the cycle, but the data is going nowhere. To my opinion, you should but $linea[0] into your SQL query, but you are putting $name->plaintext where, when $name is set only once in your scrapUrl, as I've mentioned above.
I would recommend, that you use the right variable in your SQL-query to pass data to it.
Also, it's better to use PDO and prepared statements instead of inserting raw data in your string-literals SQL queries.
Here is your code, just formatted: ( please check it you have a missing } )
function scrapUrl($url)
{
$html = new simple_html_dom();
$html->load_file($url);
global $name; // -- using global is crap - I would avoid that. Pass the object in as an argument of the function eg. scrapUrl($url, $name)
$names = $html->find('h1');
foreach ($names as $name) {
// -- your re-assigning $name overwriting you global on each iteration of this loop
// -- What is the purpose of this? it does nothing but output?
echo $name->innertext;
echo '<br>';
}
// -- missing } where is this function closed at?
$rutaCSV = 'csv/urls1.csv'; // Ruta del csv.
$csv = array_map('str_getcsv', file($rutaCSV));
foreach ($csv as $linea) {
// -- this can be combined with the one with the query
// -- just put the function call in that one and delete this one
$url = $linea[0];
scrapUrl($url); //recursive? depends where you function is closed
// -- whats the purpose of this function, it returns nothing?
}
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
foreach ($csv as $linea) {
$url = $linea[0]; // -- whats this url used for?
$sql = "INSERT INTO productos (nombre) VALUES('$name->plaintext')";
// -- query is vulnerable to SQL injection? prepared statement
// -- whats $name->plaintext? where is it assigned at?
print ("<p> $sql </p>");
if ($conn->query($sql) === TRUE) {
echo "Items added to the database!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// -- when you loop over the CSV but insert $name->plaintext multiple times
// -- where is that property changed inside this loop, how is it correlated to the csv data
}
$conn->close();
So first off you are missing a closing } Depending where that should be, depends on what else you have wrong.
One of you loops for the CSV can be eliminated ( maybe ), anyway I put bunch of notes in with comments like this // --
Your main issue, or the reason you inserts are the same is these lines
foreach ($csv as $linea) {
$url = $linea[0]; // -- whats this url used for?
$sql = "INSERT INTO productos (nombre) VALUES('$name->plaintext')";
// -- $name->plaintext does not change per iteration of the loop
// -- you are just repeatedly inserting that data
...
See you insert the value of $name->plaintext but this has no correlation to the $csv variable and you are not modifying it. It's no surprise it stays the same.
Ok, now that I picked apart your code ( nothing personal ). Let's see if we can simplify it a bit.
UPDATE This is the best I can do given the above code. I just combined it, fixed some logical errors, trimmed it down and simplified it. It's a common mistake of beginners to over-complicate the task. ( but there is no way for me to test this )
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$rutaCSV = 'csv/urls1.csv'; // Ruta del csv.
$csv = array_map('str_getcsv', file($rutaCSV));
//prepare query outside of the loops
$stmt = $conn->prepare("INSERT INTO productos (nombre)VALUES(?)");
foreach ($csv as $linea) {
//iterate over each csv line
$html = new simple_html_dom();
//load url $linea[0]
$html->load_file($linea[0]);
//find names in the document, and return them
foreach( $html->find('h1') as $name ){
//iterate over each name and bind elements text to the query
$stmt->bind_param('s', $name->plaintext);
if ($stmt->execute()){
echo "Items added to the database!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
There I further simplified it as it doesn't really make sense to have the function scrapUrl(). We're not re-using that code, so it adds a function call and makes the code harder to read by having it.
Even if it doesn't work strait away, I encourage you to compare the original code to what I have. And sort of walk through it in your mind, so you can get an feel for how I removed some of those redundancies etc.
For reference
mysqli prepare: http://php.net/manual/en/mysqli.prepare.php
mysqli bind_param: http://php.net/manual/en/mysqli-stmt.bind-param.php
mysqli execute: http://php.net/manual/en/mysqli-stmt.execute.php
Hope that helps, cheers!
Well, after been thinking about this for quite some time, I've managed to make it work.
I leave the code in case someone else can use it.
<?php
require 'libs/simple_html_dom/simple_html_dom.php';
set_time_limit(0);
function scrapUrl($url)
{
$html = new simple_html_dom();
$html->load_file($url);
global $name;
global $price;
global $manufacturer;
$result = array();
foreach($html->find('h1') as $name){
$result[] = $name->plaintext;
echo $name->plaintext;
echo '<br>';
}
foreach($html->find('h2') as $manufacturer){
$result[] = $manufacturer->plaintext;
echo $manufacturer->plaintext;
echo '<br>';
}
foreach($html->find('.our_price_display') as $price){
$result[] = $price->plaintext;
echo $price->plaintext;
echo '<br>';
}
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$price_go=str_replace(",",".",str_replace(" €","",$price->plaintext));
$sql = "INSERT INTO productos (nombre, nombreFabricante, precio) VALUES('$name->plaintext', '$manufacturer->plaintext', $price_go)";
print ("<p> $sql </p>");
if ($conn->query($sql) === TRUE) {
echo "Producto añadido al comparador!";
echo '<br>';
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
//echo $url;
}
$rutaCSV = 'csv/urls1.csv'; // Ruta del csv.
$csv = array_map('str_getcsv', file($rutaCSV));
//print_r($csv); // Verás que es un array donde cada elemento es array con una de las url.
foreach ($csv as $linea) {
$url = $linea[0];
scrapUrl($url);
}
?>
I'm pretty sure i have some trash in my code, but it works.
I hope it help for someone.
Regards and thanks for all the help.
ok so I have written some code that is doing a backup of configuration items. This script runs fine for everything else, but fails when it gets to this long query for this specific configuration item.
for sanity purposes I am just going to include the code for this section.
function writepool($pool, $device){
$pooltext = implode('', $pool['list']);
$sql = "INSERT into pools (deviceid, name, config) VALUES (
'".$device."',
'".$pool['pool']."',
'".addslashes($pooltext)."'
)";
echo $sql;
$addpool = insertdb($sql);
}
function insertdb($sql){
include('/var/www/db_login.php');
$conn = new mysqli($db_host, $db_username, $db_password, "F5");
// check connection
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
if($conn->query($sql) === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
$last_inserted_id = $conn->insert_id;
$affected_rows = $conn->affected_rows;
}
$result["lastid"] = $last_inserted_id;
$result["affectedrow"] = $affected_rows;
return $result;
$conn->close();
}
The error message I get is as follows
Fatal error: Wrong SQL: INSERT into pools (deviceid, name, config) VALUES ( '71', 'shopping.a.prod_pool_53601', 'ltm pool /Common/shopping.a.prod_pool_53601 { load-balancing-mode weighted-least-connections-node members { /Common/10.216.26.55:53601 { address 10.216.26.55 priority-group 1 } /Common/10.216.26.57:53601 { address 10.216.26.57 priority-group 1 } /Common/10.216.26.58:53601 { address 10.216.26.58 priority-group 1 } /Common/10.216.26.59:53601 { address 10.216.26.59 priority-group 1 } /Common/10.216.26.60:53601 { address 10.216.26.60 priority-group 1 } /Common/10.216.26.61:53601 { address 10.216.26.61 priority-group 1 } /Common/10.216.26.62:53601 { address 10.216.26.62 priority-group 1 } /Common/10.216.26.66:53601 { in /var/www/html/functions.php on line 2286
Note the query is extremely long. This particular configuration item is huge. I am storing this inside a BLOB in MYSQL.
If I echo the $sql variable I can see my entire query string. The query is too long to place here.
'If I copy the query string to MYSQL it works.
Also if I copy the query string from my echo. and use a test page and put $sql= to the string echo'd by my failed script. it works. I wish I could post the query but it is too long due to blob data.
****** UPDATE *********
I did what tadman suggested, I moved to a prepared statement. However, now I am not getting any data input into the blob in my table.
function writepool($pool, $device){
$pooltext = implode('', $pool['list']);
/*
$sql = "INSERT into pools (deviceid, name, config) VALUES (
'".$device."',
'".$pool['pool']."',
'".addslashes($pooltext)."'
)";
*/
#$addpool = insertdb($sql);
include('/var/www/db_login.php');
$mysqli = new mysqli($db_host, $db_username, $db_password, "F5");
// Check connection
if($mysqli === false){
die("ERROR: Could not connect. " . $mysqli->connect_error);
}
// Prepare an insert statement
$sql = "INSERT into pools (deviceid, name, config) VALUES (?, ?, ?)";
if($stmt = $mysqli->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("ssb", $db_device, $db_pool, $db_text);
// Set parameters
$db_device = $device;
$db_pool = $pool['pool'];
$db_text = addslashes($pooltext);
// Attempt to execute the prepared statement
if($stmt->execute()){
#echo "Records inserted successfully.";
} else{
echo "ERROR: Could not execute query: $sql. " . $mysqli->error;
}
} else{
echo "ERROR: Could not prepare query: $sql. " . $mysqli->error;
}
// Close statement
$stmt->close();
// Close connection
$mysqli->close();
}
$db_text is a section of configuration data generated by a system file. I was storing this as a blob since it is huge (1600+ lines long).
I have a problem when i try to check if email is alredy registered. can someone help? I have this error:
mysql_fetch_array(): supplied argument is not a valid MySQL result resource in line...
($record =mysql_fetch_array($result); )
<?php
$nome = $_REQUEST["nome"];
$cognome = $_REQUEST["cognome"];
$psw = $_REQUEST["psw"];
$email = $_REQUEST["email"];
$nikName = $_REQUEST["nikName"];
$conn = mysql_connect("host,name","userName","Password","databaseName");
if(!$conn) {
echo "connessione non satabilita";
} else {
if(!mysql_select_db("databaseName",$conn)) {
echo "database non trovato";
} else {
$sql = "select * from utenti where User='$email'"; //costruzione comando di ricerca
$result = mysql_query($sql,$conn); //assegnazione risultati
$record =mysql_fetch_array($result); //estrazione primo risultato
if(!$record) {
$sql = "INSERT INTO User (UserId, Nome, Cognome, Email, Username, Password, TimeStamp) VALUES (NULL,'$nome','$cognome','$email','$nikName','$psw', NULL)";
$result=mysql_query($sql);
if($result) {
echo "utente registrato correttamente";
} else {
//Error
echo "errore registrazione, riprovare più tardi";
}
echo "<br />";
echo "utente registrato";
} else {
echo "utente gia registrato";
}
}
}
?>
Before this gets out of hand.
$conn = mysql_connect("host,name","userName","Password","databaseName");
You're using 4 parameters rather than 3.
Sidenote: 4 parameters is mysqli_ syntax http://php.net/manual/en/function.mysqli-connect.php
Be careful though, those different MySQL APIs do not intermix. So you cannot have mysql_ with mysqli_ should you decide to change it to that.
The manual http://php.net/manual/en/function.mysql-connect.php states:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
the fourth is for something else.
If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The new_link parameter modifies this behavior and makes mysql_connect() always open a new link, even if mysql_connect() was called before with the same parameters. In SQL safe mode, this parameter is ignored.
So, just remove the 4th parameter.
Sidenote: This is questionable "host,name" (with the comma). Double check it as to what your host (if hosted) has provided you with. Most of the time, that should read as "localhost".
As stated, you're open to SQL injection.
Use a prepared statement:
https://en.wikipedia.org/wiki/Prepared_statement
As for the rest of your code:
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Also add or die(mysql_error()) to mysql_query().
About you're wanting to check if an email exists; you may be better off using mysql_num_rows().
I.e.:
$sql = "select * from utenti where User='$email'";
$result = mysql_query($sql,$conn) or die(mysql_error($conn));
if(mysql_num_rows($result) > 0)
{...}
else {...}
I noticed you may be storing passwords in plain text. If this is the case, it is highly discouraged.
I recommend you use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
Also, this doesn't help you:
if(!mysql_select_db("databaseName",$conn)){
echo "database non trovato";
}
This does:
if(!mysql_select_db("databaseName",$conn)){
die ('Can\'t use the database : ' . mysql_error());
}
In order to get the real error, should there be one.
Reference:
http://php.net/manual/en/function.mysql-select-db.php
As mentioned above there is a syntax error with mysql_connect(); where you're trying to use invalid number of params. The best way is to make a config.php file and then use it whenever you need it. This is a basic connection code in PDO.
<?php
$host = "localhost";
$database = "yourdbnamehere";
$username = "yourusernamehere";
$password = "yourpasswordhere";
try {
$dbo = new PDO('mysql:host='.$host.';dbname='.$database, $username, $password);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
You will need a solution like this. But you must switch towards PDO or MySQLi to ensure that your code stays valid in long run as well as you will be able to write secure and stable code.
Go through these at first:
http://php.net/manual/en/book.pdo.php
http://php.net/manual/en/book.mysqli.php
An example code for you solving your current problem:
<?php
$nome = $_REQUEST["nome"];
$cognome = $_REQUEST["cognome"];
$psw = $_REQUEST["psw"];
$email = $_REQUEST["email"];
$nikName = $_REQUEST["nikName"];
try{
$pdo = new PDO('mysql:dbhost=hostname; dbname=databaseName', 'userName', 'Password');
} catch (PDOException $e) {
echo "Error connecting to database with error ".$e;
die();
}
// check for email
$sql = $pdo->prepare("select * from utenti where User= ?");
$sql->bindParam('1', $email);
$sql->execute();
/* if you aren't hashing the password,
then do it first
$psw = PASSWORD_HASH($psw, PASSWORD_DEFAULT);
*/
// Insert if email not registered
if($sql->rowCount() == 0) {
$insert = $pdo->prepare("INSERT INTO User (Nome,Cognome,Email,Username,Password) VALUES (?, ?, ?, ?, ?)");
$insert->bindParam('1', $nome);
$insert->bindParam('2', $cognome);
$insert->bindParam('3', $email);
$insert->bindParam('4', $nikName);
$insert->bindParam('5', $psw);
$insert->execute();
if($insert->rowCount() > 0) {
echo "utente registrato correttamente";
} else {
echo "errore registrazione, riprovare più tardi";
}
} else {
echo "utente gia registrato";
}
?>