This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
I know this has been asked many times before but I'm still stumped.
I'm obviously missing something but I have been unable to figure out how to successfully escape the apostrophe when sending a mysql query from php. Why does this not work when everything I have read says it should.
<?php
$title = "havin' fun";
$con=mysqli_connect($server,$username,$password,$database);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$title = mysqli_real_escape_string($title);
$result = mysqli_query($con,"SELECT id,artist,title FROM songs WHERE title = '$title'");
if($result) {
while($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$artist = $row['artist'];
$title = $row['title'];
echo $id.' - '.$artist.' - '.$title.'<br>';
}
}else echo 'No Results';
mysqli_close($mysqli);
?>
$title = mysqli_real_escape_string($title);// add another parameter for connection
For example:
$title = mysqli_real_escape_string($conn, $title)
Related
I want to perform a query on a database with genomic information.
This is part of the php code:
$db = mysqli_connect($servername,$username,$password,$database)
$fields = "name, chrom, strand, txStart, txEnd, exonCount, name2";
$query = "SELECT $fields FROM $table WHERE name2 LIKE '%$gene%';";
$result = mysqli_query($db,$query);
$items = mysqli_affected_rows($result);
if ($items == 0)
{
print_error("The gene $gene is not found in the RefSeq database");
}
else
{
$transcripts = $items;
echo "<html>\n";
echo "<head>\n";
echo "<title> Catalogue web server </title>\n";
echo "<link href=\"styles.css\" rel=\"stylesheet\">\n";
echo "</head>\n";
echo "<body>\n";
echo "<h1>Catalogue output ($gene)</h1>\n";
echo "<table>\n";
echo "<tr><th>GENE</th><th>TRANSCRIPTS</th><th>CHR</th><th>STRAND</th><th>POS1</th><th>POS2</th><th>EXONS</th>\n";
for ($i = 0; $i<$items; $i++)
{
$row = mysqli_fetch_array($result);
$name2 = $row["name2"];
$name = $row["name"];
$chrom = $row["chrom"];
$strand = $row["strand"];
$txStart = $row["txStart"];
$txEnd = $row["txEnd"];
$exonCount = $row["exonCount"];
echo "<tr><td>$name2</td><td>$name</td><td>$chrom</td><td>$strand</td><td>$txStart</td><td>$txEnd</td><td>$exonCount</td>\n";
}
echo"</table><br><br>\n";
}
However, when I submit the query from html localhost, I´m always getting the error message:
The gene is not in the database
When I know it is.
Any help finding the error would be appreciated it.
ALSO: $servername, $username, $password and $database are correct, checked several times
I don´t mind about mysql injections as I´m not publishing this web
Try instead with:
$items = mysqli_num_rows($result);
The mysqli_affected_rows is used after insert, update, replace or delete queries.
This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
How can I prevent SQL injection in PHP?
(27 answers)
Closed 3 years ago.
I'm trying to insert data into the database, it run my coding and i get output as 'SOP data Added Successfully', but the data does not get into the database.
if (isset($_SESSION['admin_id']))
{
include 'databaseConnection.php';
if (isset($_POST['add_btn']))
{
$sop_name = $_POST['sop_name'];
$sop_step = $_POST['sop_step'];
$sop_comment = $_POST['sop_comment'];
$department_id = $_POST['department_id'];
$admin_id = $_SESSION['admin_id'];
$query = "SELECT * FROM sop WHERE sop_name = '$sop_name' && admin_id = '".$_SESSION['admin_id']."'";
$result = mysqli_query($connection, $query);
$count = mysqli_num_rows($result);
if ($count == 1)
{
echo '<script language="javascript">';
echo 'alert("SOP Data Already Existed")';
echo '</script>';
}
else
{
$addSOP = "INSERT INTO sop(sop_name, sop_step, sop_comment, department_id, admin_id) VALUES('$sop_name' , '$sop_step' , '$sop_comment' , '$department_id' ,'$admin_id')";
mysqli_query($connection, $addSOP);
echo '<script language="javascript">';
echo "alert('SOP Data Added Succesfully'); window.location.href='dashboardOrganizationDepartment.php'";
echo '</script>';
}
}
?>
I expect that the result can be post into the database, but it is not. There is also not showing any errors for me to refer.
Can you put some try catch within your insert query, you will get the actual error in query
try {
$addSOP = "INSERT INTO sop(sop_name, sop_step, sop_comment, department_id, admin_id) VALUES('$sop_name' , '$sop_step' , '$sop_comment' , '$department_id' ,'$admin_id')";
mysqli_query($connection, $addSOP);
} catch (Exception $e) {
die($e->getMessage());
}
This question already has answers here:
Why shouldn't I use mysql_* functions in PHP?
(14 answers)
Closed 4 years ago.
Here is my php and mysql code. It don't show any data . please tell me where is my error:
<?php
$ddaa = mysql_query("SELECT ref FROM users WHERE id='$uid'");
$mallu2 = mysql_query("SELECT mallu FROM users WHERE id='$ddaa'");
$result = mysql_fetch_array($mallu2);
echo $result['mallu'];
?>
You can use Mysqli,mysql is deprecated
a little example:
conection to db test
$mysqli = new mysqli('127.0.0.1', 'user', 'password', 'test');
if ($mysqli->connect_errno) {
echo "Error: Errot on connection : \n";
echo "Errno: " . $mysqli->connect_errno . "\n";
}
// the query
$sql = "SELECT ref FROM users WHERE id=$uid";
//if don't have result
if ($resultado->num_rows === 0) {
echo "we can't find data with $uid. try again !.";
exit;
}
//print the result
while ($dato = $resultado->fetch_assoc()) {
echo $dato['ref'];
}
Mysqli Php documentation
This question already has answers here:
Warning: preg_replace(): Unknown modifier
(3 answers)
Closed 7 years ago.
I'm sure I'm just doing something stupid but I think I'm close. What I'm trying to do as add validation to my submission. With my current code regardless of what data I enter into the serial field it always comes up with Invalid Serial. Any suggestions?
<?php
$serial=$_POST['serial'];
$model=$_POST['model'];
$deviceCondition=$_POST['deviceCondition'];
$sealCondition=$_POST['sealCondition'];
$location=$_POST['location'];
$deployDate=$_POST['deployDate'];
$weight=$_POST['weight'];
$connectedTerminal=$_POST['connectedTerminal'];
$notes=$_POST['notes'];
//NEW PDO connection
$serialVal = "[a-zA-Z0-9-]+";
if ( preg_match( $serialVal, $serial ) ) {
try{
$conn = new PDO("mysql:host=$sql_server;dbname=$sql_db", $sql_user, $sql_pass);
$sql = "INSERT INTO web01dev4s2.ingenicoInfo (serial, model, deviceCondition, sealCondition, location, deployDate, weight, connectedTerminal, notes) VALUES ('".$serial."', '".$model."', '".$deviceCondition."', '".$sealCondition."', '".$location."', '".$deployDate."', '".$weight."', '".$connectedTerminal."', '".$notes."')";
$q = $conn->prepare($sql);
$result_1=($sql);
$q->execute();
}
catch (PDOException $pe) {
die("Could not connect to the database" . $pe->getMessage());
}
$count = $q->rowCount();
print("Saved $count record(s).\n");
header( "refresh:2;url=devicelist.php" );
}
else {
echo $serial . "Invalid serial number.";
}
?>
You forgot the delimiters "/"
if(preg_match("/[a-zA-Z0-9-]+/", $serial))
echo 'oui';
else
echo 'no';
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
How do i display an image stored in mySQL database as BLOB ?
What it tried so far:
1. Created a new php function/file to get picture (getpicture.php).
2. In the html, I have the following code:
<img src="getpicture.php?id=2" border ="0" height="250" width="250" />
/*below is the getpicture.php*/
<?php
# $db = new MySQLi('localhost','root','','myDatabase');
if(mysqli_connect_errno()) {
echo 'Connection to database failed:'.mysqli_connect_error();
exit();
}
if(isset($_GET['People_Id'])) {
$id = mysqli_real_escape_string($_GET['People_Id']);
$query = mysqli_query("SELECT * FROM 'people' WHERE 'People_Id' = '$id'");
while($row = mysqli_fetch_assoc($query)) {
$imageData =$row['image'];
}
header("content-type: image/jpeg");
echo $imageData;
echo $id;
}
else {
echo "Error!";
echo $id;
}
?>
What's wrong with the codes ? Please help!
I answered my own question, it's working now..
Below is the getpicture.php:
<?php
$db = new MySQLi('localhost', '', '', 'mydatabase');
if ($db->connect_errno) {
echo 'Connection to database failed: '. $db->connect_error;
exit();
}
if (isset($_GET['id'])) {
$id = $db->real_escape_string($_GET['id']);
$query = "SELECT `Picture` FROM member WHERE `Id` = '$id'";
$result = $db->query($query);
while($row = mysqli_fetch_array($result)) {
$imageData = $row['Picture'];
header("Content-type:image/jpeg");
echo $imageData;
}
}
?>
The php script which retrieve the getpicture.php above looks like this:
echo '<img src="getpicture.php?id=' . htmlspecialchars($_GET["id"]) . '"border ="0" height="250" width="250" />';
Thaank you all for the help
This is wrong:
$query = mysqli_query("SELECT * FROM 'people' WHERE 'People_Id' = '$id'");
you use wrong quotes for table name (must be backtick instead of single quote (see tylda ~ key). See docs: http://dev.mysql.com/doc/refman/5.1/en/reserved-words.html
Also this is wrong too
header("content-type: image/jpeg");
echo $imageData;
echo $id;
get rid of last echo $i; and replace it with exit(); otherwise you corrupt the image data stream you just sent.
Plenty is wrong.
your SQL is wrong. Remove the single quotes from the table and column and replace with back ticks.
Although it may still work, you should have a couple of new lines after your header
You shouldn't echo out your $id after you echo your image data.
You're checking for the wrong value when you check isset
Also, you should be using OOP for mysqli
Since your image data is only a single row, you don't need to wrap it in a while loop
Here is an updated code example
<?php
$db = new MySQLi('localhost', 'user', 'password', 'myDatabase');
if ($db->connect_errno) {
echo 'Connection to database failed: '. $db->connect_error;
exit();
}
if (isset($_GET['id'])) {
$id = $db->real_escape_string($_GET['id']);
$result = $db->query("SELECT * FROM `people` WHERE `People_Id` = '$id'");
$row = $result->fetch_assoc();
$imageData = $row['image'];
header("Content-type: image/jpeg\n\n");
echo $imageData;
}
else {
echo "Error!";
}