How to minify an INSERT and PRINT query? - php

I have two PHP/SQL functions and I am wondering how I would minify them. I'd like to run the 3 insert commands as a single $import rather than three, but I am not sure how to minify it.
$import9="INSERT into wp_postmeta (meta_id,post_id,meta_key,meta_value) values(',','$data[37]','lower_electric_costs','$data[5]')";
$import10="INSERT into wp_postmeta (meta_id,post_id,meta_key,meta_value) values(',','$data[37]','cheapest_green_electric','$data[6]')";
$import11="INSERT into wp_postmeta (meta_id,post_id,meta_key,meta_value) values(',','$data[37]','contract_type','$data[11]')";
Its the same thing with my PRINT results - how would I minify this down?
mysql_query($import9) or die("mysql_error()");
print $import9."<br>";
mysql_query($import10) or die("mysql_error()");
print $import10."<br>";
mysql_query($import11) or die("mysql_error()");
print $import11."<br>";
I am still learning PHP/SQL and learning how to minify my code is an important part of it I think. If someone can just how me an example of what a minified version would look like, then I can probably take it from there.
Thanks

You could combine it into a single query as follows:
$import9="
INSERT into
wp_postmeta
(meta_id,post_id,meta_key,meta_value)
values
(',','$data[37]','lower_electric_costs','$data[5]'),
(',','$data[37]','cheapest_green_electric','$data[6]'),
(',','$data[37]','contract_type','$data[11]')
";
However, you should use mysqli instead of mysql functions, as mysql functions are deprecated.
mysqli_query($import9);
It is also advised that you do not use INSERT queries with mysqli_query but rather use Prepared Statements for security reasons. You should check out PDO and Prepared Statements.
First, create a PDO instance.
$db = new PDO("mysql:host=localhost;port=3306;dbname=mydb", "username", "password");
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //Turn off prepared statement emulation too.
With a prepared statement, you would prepare your statement with the server:
$stmt = $db->prepare("
INSERT into
wp_postmeta
(meta_id,post_id,meta_key,meta_value)
values
(?,?,?,?)
");
With an array like:
$values = array(
array(',',$data[37], 'lower_electric_costs', $data[5]),
array(',',$data[37], 'cheapest_green_electric', $data[6]),
array(',',$data[37], 'contract_type', $data[11]),
);
Next, you'd issue a series of execute statements:
foreach ($values as $v) {
$stmt->execute($v);
}
Finally, close the statement so that more statements can be executed:
$stmt->closeCursor();

Related

PHP Insert Into Error

I am started to learn coding start with HTML, CSS, and php. I created a basic form to test my skill. However, I got stuck with this. Can you help me on that?
I know that it is open to SQL injections, I am just trying to improve myself in coding and will use prepared statements and parameterized queries in real life.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$mysql_host = "";
$mysql_username = "";
$mysql_password = "";
$mysql_database = "";
$conn = new mysqli ($mysql_host, $mysql_username, $mysql_password, $mysql_database);
$c_name = $_POST["club_name"];
$c_league = $_POST["league"];
$c_rank = $_POST["ranking"];
$c_prank = $_POST["previous_rank"];
$sql = "INSERT INTO `club_data` (`club_name`, `league`, `ranking`, `previous_rank`)
VALUES ('$c_name', '$c_league, $c_rank, $c_prank);";
mysqli_query($conn, $sql);
if ($conn->query($sql) === TRUE) {
echo "kayit islendi";
}
else {
echo "Error". $sql ."<br>". $conn->error;
}
$conn->close();
}
?>
Everytime I used the form I got this error.
ErrorINSERT INTO... etc.
You are missing quotes around your insert values, here's the fixed sql:
$sql = "INSERT INTO `club_data` (`club_name`, `league`, `ranking`, `previous_rank`)
VALUES ('$c_name', '$c_league', '$c_rank', '$c_prank');"
You were missing quotes around each value!
HOWEVER, this is an ill advised way of making database queries in production. Either use mysqli_real_escape_string to sanitize your strings(each of your variables will need this treatment) or use prepared statements.
Alternatively, and the way you should always use your DB is via the PDO wrapper. In this case you would use: PDO::quote. PDO offers a unified interface to the most popular databases there are. Here you can read more about PDO: http://php.net/manual/en/book.pdo.php
Coders prefer prepared statements to sanitizing their input. However this incurs extra communication with the mysql server vs writing a bit more code in php. Prepared statements are more involved then normal queries as they are cached on the SQL server and preprocessed waiting for data to be used, also having a miriad of question marks makes the code very hard to read especially if you start working in production and have a miriad of columns to fill. Here you can read more about the prepared statements:
https://dev.mysql.com/doc/refman/5.7/en/sql-syntax-prepared-statements.html
Main takeaway:
never, EVER, EVER save unsanitized data to the DB!!Use mysqli_real_escape_string or PDO::quote or prepared statements, depending on situation.
use prepared statements for what they have been created for not just as a wholesale sanitizer tool, use them when you have to execute the same query repeatedly. Especially if this query is not an insert in which case I suggest you do mass insert like so:INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9); read more here: https://dev.mysql.com/doc/refman/5.7/en/insert.html This has a caveat in that the maximum size of the sql with inserted values should never be larger then max_allowed_packet config.
You should use prepared statements. Not only does it prevent SQL injection attacks, it also avoids the pesky quoting issues you are currently facing
$sql = "INSERT INTO `club_data` (`club_name`, `league`, `ranking`, `previous_rank`)
VALUES (?, ?, ?, ?);";
$result = $conn->prepare($sql);
$result->bind_param('ssss', $c_name, $c_league, $c_rank, $c_prank);
echo $result->execute() === true ? 'kayit islendi' : 'Error'.$conn->error;

How can I make a prepared statement with IN() and have a while loop for PDO in PHP

I am new to PDO, and have got stuck on trying to create a prepared statement for using IN()
I have an array of different URLs ($urls), which I use for the IN(). I am not getting any errors, but the results are not showing.
$in = str_repeat('?,', count($urls) - 1) . '?';
$qry = $this->pdo->prepare("SELECT categories_url,categories_id,parent_id,categories_name FROM categories WHERE categories_url IN($in)");
$qry->execute($urls);
while($row = $qry->fetch(PDO::FETCH_ASSOC)) {
echo $row['categories_url'];
}
When I test the query with $qry->fetchColumn(), then it seems to have 0 results. But if I do the same query in mysqli, it has multiple results.
The things I am unsure about it, I dont think my prepared statement is quite right, or maybe its the execution. And I dont know how to do while loops with fetch_assoc with PDO prepared either. What have I done wrong?

PHP Procedural Prepared Statement for Mysqli Multi Query

I have a PHP code that opens a CSV file using fgetcsv then reads through each rows then constructs a "Insert Into" query and attaches it to a variable named $MyQuery. This is the most understandable way for me when trying to update my database using information from a CSV file downloaded from the company website. This is working as I expected using the code below:
if (mysqli_multi_query($conn, $MyQuery))
{
do
{
/* store first result set */
if ($result = mysqli_store_result($conn))
{
mysqli_free_result($result);
}
} while (mysqli_next_result($conn));
}
Recently I learned about Prepared Statements and how they can secure your queries.
PROBLEM: How can I do multiquery with prepared statement in Procedural Mysqli way? I tried researching, a lot says it isn't possible. Some say it is possible but by creating different variables for each queries which is impossible for me as I will be inserting over 10000 records to my database from the CSV file. Is there any other ways to achieve this?
I'm thinking it can be done by looping through each records then doing a prepared-statement version of Insert Into but I thought doing 10000 Insert Into SQL commands would be very slow.
I am not 100% sure what you are asking but fallowing might work. First of all I would use pdo for connecting to a database. Fallowing is just a basic outline of what I think you want to do.
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'myusername', 'mypassowrd');
$query = "
INSERT INTO table (colum1, colum2, colum3)
VALUES (:info1, :info2, :info3)
";
$stmt = $pdo->prepare($query);
do
{
$stmt->execute(array(':info1'=>$my_info1, ':info2'=>$my_info2, ':info3'=>$my_info3));
} while( your condition);
There is two advantages for prepared statements. First is security and the second allows to do the same query over and over changing the values. This will make each of queries fast if you prepare them.
here is a ling that can explain more about prepared statements
http://php.net/manual/en/pdo.prepared-statements.php
I am adding a Procedural way of doing it using mysqli.
$query = "
INSERT INTO table (colum1, colum2, colum3)
VALUES (?, ?, ?)
";
if ($stmt = mysqli_prepare($conn, $query))
{
do
{
mysqli_stmt_bind_param($stmt, "sss", $my_info1, $my_info2, $my_info3);
mysqli_stmt_execute($stmt);
} while( your condition)
}
I am not sure why you are using mysqli_store_result(), mysqli_free_result(), or mysqli_next_result(). Since inserting rows produces no results.

Using PDO, do I really need to run two separate prepared statements to get the number of rows returned?

What is the preferred method for getting the number of rows that are returned for a SELECT state when using PDO with prepared statements?
I am currently using rowCount() but the docs say I shouldn't be using that since "most databases" don't support it (It is actually working just fine for me, so I'm tempted to keep using it. I can't find any sources that list exactly which databases do not support it, but apparently mine is fine).
Instead they recommend I use fetchColumn() but that requires writing a completely separate SQL statement that includes the COUNT(*) in my sql statement.
This is what they propose (http://php.net/manual/en/pdostatement.rowcount.php#example-1038):
//SQL TO GET ROWS TO OUTPUT
$sql = 'SELECT *
FROM properties
WHERE lister_id = :lister_id
AND lister_type = "landlord"';
$result = $dbh->prepare($sql);
$result->bindParam(':lister_id', $_SESSION['loggedin_lister_id'], PDO::PARAM_INT);
$result->execute();
//SQL TO GET NUMBER OF RETURNED ROWS
$row_num_sql = 'SELECT COUNT(*)
FROM properties
WHERE lister_id = :lister_id
AND lister_type = "landlord"';
$row_num_result = $dbh->prepare($row_num_sql);
$row_num_result->bindParam(':lister_id', $_SESSION['loggedin_lister_id'], PDO::PARAM_INT);
$row_num_result->execute();
$num_rows = $row_num_result->fetchColumn();
if($num_rows > 0) {
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo $row['name'];
}
}
I find this method that requires me to write a separate and nearly identical sql statement to be redundant and a serious pain when using prepared statements. I can understand how this approach might be acceptable when using a short SQL statement with a basic query, but not in the case of a prepared statement.
1. Is there any other way I can use the fetchColumn() approach
without having to rewrite what is almost exactly the same code?
2. Where can I find an official list of which databases
rowCount() supports when using a SELECT statement? And since it is
working on the database I am currently using, can I assume it is safe
to use(assuming I am not updating my database anytime soon)?
If you don't want to use rowCount I'm think you should two query, or you can use fetchAll and count(fetchAll) for rowCount
the second way, Use SELECT *,COUNT(*) ...

how to avoid mysqli prepared statement everytime in php

I am newbie to php. I have a php file which would insert values to mysql table. So considering the efficiency that this would be hit very frequently, I decided to go with mysqli_prepare statement in my php file.
I am wondering for everytime this php file is executed, it would prepare statement which might be a burden which is not necessary. Is there any way to avoid it by preparing the statement only once or Am I missing some concept of prepared statement?
Thanks,
Marutha
mysqli_query
But i use PDO and my code seems like this:
$query = 'INSERT INTO tbl (param, new_param) VALUES (:param, :new_param)';
$stmt = DB::prepare($query);
foreach( $data as $param => $new_param )
{
$stmt->execute(':param' => $param, ':new_param' => $new_param);
}
OR like this
DB::query("INSERT "); // PDOChild::getInstance()->query("INSERT ");
If you insert data from users input you should to prepare statement...
You may want to consider caching SQL result, or caching entire php script output (page cache) if script do not contain any changeable information.
For caching check more about it here.
If you are using some kind of php framework like ZendFramework, Symfony, Kohana, they usually have much more flexible caching handlers.

Categories