PHP Prepared statements from web form issues [duplicate] - php

This question already has answers here:
Apache shows PHP code instead of executing it
(28 answers)
Closed 4 years ago.
Only recently started using mysql so I'm slowly getting to grips with it, but trying to use PHP prepared statements for a webform, and upon submitting the webform, it's just displaying the php code. Any suggestions?
Thanks
<?php
$link = mysqli_connect("localhost", "root", "", "contactform");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "INSERT INTO contactform (firstname, surname, address1, address2,
towncity, county, postcode) VALUES (?,?,?,?,?,?,?)";
if($stmt = mysqli_prepare($link, $sql)){
mysqli_stmt_bind_param($stmt, "sssssss", $firstname, $surname, $address1,
$address2, $towncity, $county, $postcode);
$firstname = $_REQUEST['firstname'];
$surname = $_REQUEST['surname'];
$address1 = $_REQUEST['address1'];
$address2 = $_REQUEST['address2'];
$towncity = $_REQUEST['towncity'];
$county = $_REQUEST['county'];
$postcode = $_REQUEST['postcode'];
if(mysqli_stmt_execute($stmt)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not execute query: $sql. " . mysqli_error($link);
}
} else{
echo "ERROR: Could not prepare query: $sql. " . mysqli_error($link);
}
mysqli_stmt_close($stmt);
mysqli_close($link);
?>

using eval( $text ); will execute your string as PHP code.
is that what you are looking for ?
PHP eval() function
Caution The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data

Related

Uncaught TypeError: mysqli_query(): Argument #2 ($query) must be of type string, mysqli_stmt given in PHP [duplicate]

This question already has answers here:
how to use $_GET inside mysqli_query? [duplicate]
(7 answers)
PHP: Inserting Values from the Form into MySQL
(2 answers)
PHP MySQLInsert prepared statements
(4 answers)
Closed last year.
I created a prepared statement in my PHP script but when I submit my form to insert, I get this error, Fatal error: Uncaught TypeError: mysqli_query(): Argument #2 ($query) must be of type string, mysqli_stmt given in C:\xampp\htdocs\7058\insert.php:100 Stack trace: #0 C:\xampp\htdocs\7058\insert.php(100): mysqli_query(Object(mysqli), Object(mysqli_stmt)) #1 {main} thrown in C:\xampp\htdocs\7058\insert.php on line 100.
It is my first time trying prepared SQL statements, so I am not sure what I am doing wrong.
<?php
session_start();
// servername => localhost
// username => root
// password => empty
// database name => staff
$conn = mysqli_connect("localhost", "root", "", "survey");
// Check connection
if ($conn === false) {
die("ERROR: Could not connect. "
. mysqli_connect_error());
}
$name = $_SESSION['name'];
$paygoid = $_SESSION['paygoid'];
$product_exist_satisfaction = $_SESSION['product_exist_satisfaction'];
$system_battery_runout = $_SESSION['system_battery_runout'];
$rank_appliances = $_POST['rank_appliances']; //return an array.
$checkboxvalue = implode(",", $rank_appliances);
$sql = $conn->prepare("INSERT INTO cus_survey (name,paygoid,product_exist_satisfaction,system_battery_runout,rank_appliances) VALUES (?, ?, ?, ?, ?)");
$sql->bind_param("sssss", $name, $paygoid, $product_exist_satisfaction, $system_battery_runout, $checkboxvalue);
if (mysqli_query($conn, $sql)) { **//this is line 97**
echo "<h3>Your survey was captured successfully. Thank You!"
} else {
echo "<h3>Sorry, Your ID has already been used. Please enter a valid ID</h3> "
echo "<h3><a href='/7058/index.php'>Click here to edit your ID</a></h3>";
}
// Close connection
mysqli_close($conn);
?>
I hope the following will help point you in the right direction. Initially you should make a sanity check that the variables you intend to use are actually available to avoid silly errors and then, using the considerably less verbose OO style of mySQLi, prepare the sql statement, bind the placeholders, execute the statement and then find if it succeeded.
<?php
session_start();
if( isset(
$_SESSION['name'],
$_SESSION['paygoid'],
$_SESSION['product_exist_satisfaction'],
$_SESSION['system_battery_runout'],
$_POST['rank_appliances']
)){
$conn = new mysqli("localhost", "root", "", "survey");
$name = $_SESSION['name'];
$paygoid = $_SESSION['paygoid'];
$product_exist_satisfaction = $_SESSION['product_exist_satisfaction'];
$system_battery_runout = $_SESSION['system_battery_runout'];
$rank_appliances = $_POST['rank_appliances'];
$checkboxvalue = implode(",", $rank_appliances);
$stmt = $conn->prepare( "INSERT INTO `cus_survey` ( `name`, `paygoid`, `product_exist_satisfaction`, `system_battery_runout`, `rank_appliances` ) VALUES (?, ?, ?, ?, ?)" );
$stmt->bind_param("sssss", $name, $paygoid, $product_exist_satisfaction, $system_battery_runout, $checkboxvalue );
$stmt->execute();
if ( $stmt->affected_rows==1 ) {
echo "<h3>Your survey was captured successfully. Thank You!"
} else {
echo "<h3>Sorry, Your ID has already been used. Please enter a valid ID</h3> "
echo "<h3><a href='/7058/index.php'>Click here to edit your ID</a></h3>";
}
$stmt->close();
$conn->close();
exit();
}
?>

How to query my table if there is an apostrophe in search term?

How can I search for a name in my table if there is an apostrophe in the name?
If I insert name with an apostrophe like Ender's Game in my search box, it gives an error.
I already tried solutions provided on stackoverflow, but I am not able to solve this.
Here is my code:
$string1 = $_GET['name'];
$quer = "SELECT * FROM info WHERE name = '$string1'";
$q = mysqli_query($conn, $quer);
If there is an apostrophe in $_GET['name'], an error is shown.
How can I solve this?
Code in that form is vulnerable to SQL injection. Use mysqli::prepare instead:
$string1 = $_GET['name'];
$quer = "SELECT * FROM info WHERE name = ?";
$stmt = $conn->prepare($quer);
$stmt->bind_param('s', $string1);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
$stmt->close();
var_export($result);
If you're adapting legacy, insecure code, it may be faster to use mysqli_real_escape_string. This should be reserved as a last resort, but it's there if you need it, and it's better than a regex.
The best practice that you can expect to hear over and over again from knowledgeable StackOverflow volunteers is to use prepared statements to ensure query security and reliability.
For your case, I recommend the following snippet which not only safely executes your SELECT query, but also provides informative diagnostic/debugging checkpoints throughout the process and allows you to process the resultset - represented by an multi-dimensional associative array.
$_GET['name'] = "vinay's name";
$string1 = $_GET['name'];
if (!$conn = new mysqli("host", "user", "pass", "db")) {
echo "Database Connection Error: " , $conn->connect_error; // do not show this to public
} elseif (!$stmt = $conn->prepare("SELECT * FROM info WHERE name = ?")) {
echo "Prepare Syntax Error: " , $conn->error; // do not show this to public
} elseif (!$stmt->bind_param("s", $string1) || !$stmt->execute()) {
echo "Statement Error: " , $stmt->error; // do not show this to public
}else{
$result = $stmt->get_result();
while($row = $result->fetch_array(MYSQLI_ASSOC)){
var_export($row); // do what you like here
}
}
It is important to note that using $stmt->bind_result($result) (like in Zenexer's answer) will not work (generates $result = NULL) if the info table contains more than one column (I assume it will work with one column, but I didn't test); and it will generate a Warning because of an imbalance between the number of selected columns from SELECT * and the number of nominated variables.
Warning: mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement
If you want to enjoy the benefits of explicitly binding a result variable, you should specify your desired columns in the SELECT clause like this:
if (!$conn = new mysqli("host", "user", "pass", "db")) {
echo "Database Connection Error: " , $conn->connect_error; // do not show this to public
} elseif (!$stmt = $conn->prepare("SELECT id FROM info WHERE name = ?")) {
echo "Prepare Syntax Error: " , $conn->error; // do not show this to public
} else {
if (!$stmt->bind_param("s", $string1) || !$stmt->execute() || !$stmt->bind_result($id)) {
echo "Statement Error: " , $stmt->error; // do not show this to public
} else {
while ($stmt->fetch()) {
echo "<div>$id</div>";
}
}
$stmt->close();
}

Error in my sql

I am facing problem which is mentioned as follows.
ERROR: Could not able to execute
INSERT INTO user_db (Name,UserId,Ip_addr) VALUES ('jayesh vyas', 'jay', ::1).
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version
for the right syntax to use near '::1)' at line 1.
My code is mentioned as below.
<?php
$link = mysqli_connect("localhost", "root", "", "apptitude");
$ip_user = $_SERVER['REMOTE_ADDR'];
// Check connection
if($link == false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$uname = mysqli_real_escape_string($link, $_REQUEST['uname']);
$username = mysqli_real_escape_string($link, $_REQUEST['username']);
// attempt insert query execution
$sql = "INSERT INTO user_db (Name,UserId,Ip_addr) VALUES ('$uname', '$username', " . $ip_user . ")";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
can anyone please help me to understand that why it is happened???
Thanks in advance.
Your SQL statement is missing single quotes around the IP address.
So as you did it for $user and $username, just use it again on $_SERVER['REMOTE_ADDR'] (after connecting to the MySQL server): $ip_user = mysqli_real_escape_string($link, $_SERVER['REMOTE_ADDR']);.
And as tadman said, please use prepared statements.
Btw. $_SERVER['REMOTE_ADDR'] must not the clients IP address. Take a look at this Post.

Invalid query: You have an error in your SQL syntax; special characters

I am doing php and writing some code to insert data into different tables at the same time. I wrote a foreach loop and one part of my code is as follows:
while ($datarow = dbgetrow($dataresult)) {
if ( $dotcount > $datanumrows) {
showarchivestatus(" .", true);
$dotcount = 1;
}
$sqlvalues = "";
You need to escape your string before putting it into the database.
Here is a basic example of how to do it in MySQLi
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$lastname = mysqli_real_escape_string($con, $_POST['lastname']);
$age = mysqli_real_escape_string($con, $_POST['age']);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('$firstname', '$lastname', '$age')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
Here is an example of PDO:
<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');
/* Dangerous string */
$string = 'Naughty \' string';
print "Unquoted string: $string\n";
print "Quoted string:" . $conn->quote($string) . "\n";
?>
You may want to consider using a prepared statement. There are several benefits to this including:
Security - Helps prevent SQL injection
Speed - You only are sending the values.
http://www.w3schools.com/php/php_mysql_prepared_statements.asp
Sources:
http://www.w3schools.com/php/func_mysqli_real_escape_string.asp
http://php.net/manual/en/mysqli.real-escape-string.php
http://php.net/manual/en/pdo.quote.php

PHP Sql injection vulnerable [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I wrote the below script as my very first ever php mysql application. I am self taught and the code works as intended. My host thinks it may be vulnerable to sql injection attacks but cannot tell me why or what I should change to make it better. I'm sure it's not as clean as it could be but if anyone has any suggestions or insight I would certainly appreciate it.
<form method="post" action="search.php?go" id="searchform">
<?php
$db=mysql_connect ("server", "*", "*") or die ('I cannot connect to the database because: ' . mysql_error());
$mydb=mysql_select_db("*");
$category_sql="SELECT distinct category FROM Members";
$category_Options="";
$category_result=mysql_query($category_sql) or die ('Error: '.mysql_error ());
while ($row=mysql_fetch_array($category_result)) {
$category=$row["category"];
$category_Options.="<OPTION VALUE=\"$category\">".$category.'</option>';
}
?>
<p>
<SELECT NAME="category"><OPTION VALUE=0>Choose<?=$category_Options?></SELECT>
</p>
<input name="submit" "id="submit" type="submit" value="submit" />
</form>
<?php
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
$category=$_POST['category'];
$category=mysql_real_escape_string($category);
$sql="SELECT category, company, address, city, state, zip, phone, web, addescription, image
FROM Members
WHERE category LIKE '$category'";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)){
$category2=$row["category"];
$company=$row["company"];
$address=$row["address"];
$city=$row["city"];
$state=$row["state"];
$zip=$row["zip"];
$phone=$row["phone"];
$web = $row["web"];
$addescription = $row["addescription"];
$image = $row["image"];
echo "<blockquote>";
if(#file_get_contents($image))
{
echo "<img src='".$image ."' class='image'/>\n";
}
else
{
}
echo "<p>\n";
echo "</br>".$category2 . "\n";
echo "</br><b>".$company . "</b>\n";
echo "</br>".$address . "\n";
echo "</br>".$city . ", ".$state. " ".$zip . "\n";
echo "</br>".$phone . "\n";
echo "</br>".$web ."\n";
echo "</br>".$addescription . "\n";
echo "</br><a href=http://www.printfriendly.com style=color:#6D9F00;text-decoration:none; class=printfriendly onclick=window.print();return false; title=Printer Friendly and PDF><img style=border:none; src=http://cdn.printfriendly.com/pf-button.gif alt=Print Friendly and PDF/></a>\n";
echo "</p>";
echo "</blockquote>"
;
}
}
else{
echo "<p>Please select a Category</p>";
}
}
mysql_close($db)
?>
The MySQL functions are deprecated. Using the MySQLi functions, and prepared statements, are a better way to protect against sql injection attacks.
$stmt = $mysqli->prepare('SELECT category, company, address, city, state, zip, phone, web, addescription, image FROM Members WHERE category LIKE ?');
$stmt->bind_param('s', $category);
I'll show the implementation of a PDO connection and how to query with it. Here it goes!
First we create the connection variable with your database credentials. We'll store this connection in $db.
$username = "root";
$password = "";
$host = "localhost";
$dbname = "my_database";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8"; $username, $password, $options);
}catch(PDOException $ex){
die("Failed to connect: ".$ex->getMessage());
}
Now you have a PDO connection stored in $db which you can query through. You may want to account for magic quotes if you're not using PHP 5.4, so keep that in mind.
Otherwise, create your query statement like so..
$query = "SELECT category, company, address, city, state, zip, phone, web, addescription, image FROM Members WHERE category LIKE :category"
Afterwards, you want to bind the value from the $_POST['category'] variable (or $category since you created that) to the parameter :category. Do that like so:
$query_params = array( ':category' => $category);
Finally, now that you have the statement and the parameters, use the previously created $db variable to prepare and execute the statement.
$statement = $db->prepare($query);
$result = $statement->execute($query_params);
Since we're SELECTing data where it could return multiple rows (assuming you have multiple rows within a category), we need to account for that. Grab the rows that the statement returns like so:
$rows = $statement->fetchAll();
And now you could refer to column headers within each $row of the database table by utilizing a foreach statement.
$citiesArray = array();
foreach($rows as $row){
if(isset($row['city'])){
$citiesArray[] = $row['city'];
}
}
Hope that helps out!
Just remember the golden rule of never trusting your users. Never take any raw user input and insert it into a database, as there's a chance that you have left yourself wide open for a security issue.
Your code seems fine. However, do note that MySQL is deprecated as of PHP 5.5.0, and instead you should use MySQLi or PDO extension which provide more security.
Maybe that's the reason your host said such thing, but from a quick look on your code it seemed fine to me.
Cheers.
The problem is the follwoing part in your code
$sql = "SELECT category, company, address, city, state, zip,
phone, web, addescription, image
FROM Members
WHERE category LIKE '$category'";
$result=mysql_query($sql);
If the parameter $category is read from the GET or POST parameters, it should be escaped:
$sql = "SELECT category, company, address, city, state, zip,
phone, web, addescription, image
FROM Members
WHERE category LIKE '" . mysql_real_escape_string($category) . "';";
If you are doing it this way, the variable cannot be used for SQL Injection
By the way (like Matthew Johnson said), the procedural mysql extension is deprecated since PHP 5.5. You should better use Mysqli or PDO.
The OOP way (strongly recommended) would look like:
$pdo = new PDO($dsn, $user, $password, $options);
$statement = $pdo->prepareStatement(
"SELECT category, company, address,
city, state, zip, phone, web,
addescription, image
FROM Members
WHERE category LIKE :category;");
$statement->bindParam(':category', $category, PDO::PARAM_STR);
$statement->execute();
$categories = $statement->fetchAll();

Categories