sql query not working after using mysql_real_esacape_string - php

This Piece Of Code Is Not Working :
$un_name=$_POST[name];
$un_idno=$_POST[idno];
$un_hostel=$_POST[hostel];
$un_mode=$_POST[mode];
$un_date=$_POST[date];
$un_time=$_POST[time];
$un_tfno=$_POST[tfno];
$un_contact=$_POST[contact];
$sa_name=mysql_real_escape_string ($un_name);
$sa_idno=mysql_real_escape_string ($un_idno);
$sa_hostel=mysql_real_escape_string ($un_hostel);
$sa_mode=mysql_real_escape_string ($un_mode);
$sa_date=mysql_real_escape_string ($un_date);
$sa_time=mysql_real_escape_string ($un_time);
$sa_tfno=mysql_real_escape_string ($un_tfno);
$sa_contact=mysql_real_escape_string ($un_contact);
$sql="INSERT INTO cabs (NAME,IDNO,HOSTEL,MODE,DATE,TIME,TFNO,CONTACT)
VALUES
('$sa_name','$sa_idno','$sa_hostel','$sa_mode','$sa_date','$sa_time','$sa_tfno','$sa_contact')";
While the same code when normally inserted works .....
$sql="INSERT INTO cabs (NAME,IDNO,HOSTEL,MODE,DATE,TIME,TFNO,CONTACT)
VALUES
('$_POST[name]','$_POST[idno]','$_POST[hostel]','$_POST[mode]','$_POST[date]','$_POST[time]','$_POST[tfno]','$_POST[contact]')";
I was just trying my first steps to prevent sql injection..but there seems to be some problem....
Note : My host doesnt seem to support mysqli so that's why i had to use msql which is deprecated.

Why not use PDO instead?
$host = "localhost";
$user = "root";
$pass = "";
$dbname = "dbname";
$link = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$foo_var = 3;
$query_result = $link->prepare("SELECT * FROM modules
WHERE id = :foo
LIMIT 1");
$query_result->bindValue(":foo", $foo_var);
$query_result->setFetchMode(PDO::FETCH_ASSOC);
$query_result->execute();
while($row = $query_result->fetch()) {
return $row;
}

Try this
$con=mysql_connect("localhost","username","password","dbname");//connection string
$sa_name=mysql_real_escape_string($con,$un_name);
.
.
.

Related

Why does the keys of PDO query() result contain tablename?

I connected mysql with PDO like this:
$servername = 'localhost';
$servername = 'localhost';
$dbname = 'atlas';
$table = 'homepage_pv';
$username = 'root';
$password = 'mysql';
$conn = null;
try {
$conn = new PDO(
"mysql:host=$servername;dbname=$dbname",
$username,
$password,
array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
)
);
}
catch(PDOException $e) {
echo "connect to mysql failed : " . $e->getMessage();
$conn = null;
exit;
}
$result = $conn->query('SELECT * from homepage_pv')->fetchAll(PDO::FETCH_NAMED);
echo "result=" . json_encode($result);
the result is :
result=[{"homepage_pv.id":"1","homepage_pv.datetime":"2019-08-19 22:56:26"},{"homepage_pv.id":"2","homepage_pv.datetime":"2019-08-19 22:56:28"},{"homepage_pv.id":"3","homepage_pv.datetime":"2019-08-19 23:01:58"}]
The keys contain the table name "homepage_pv" , which is not expected;
But where I create PDO like this :
try {
$conn = new PDO(
"mysql:host=$servername;",
...
);
}
...
$result = $conn->query('SELECT * from atlas.homepage_pv')->fetchAll(PDO::FETCH_NAMED);
echo "result=" . json_encode($result);
the keys in the result do not contain tablename any more, like this:
result=[{"id":"1","datetime":"2019-08-19 22:56:26"},{"id":"2","datetime":"2019-08-19 22:56:28"},{"id":"3","datetime":"2019-08-19 23:01:58"},{"id":"4","datetime":"2019-08-19 23:08:48"}]
In case1 , I specified dbname when creating PDO and leaved out it when doing query;
In case2 , it's is on the contrary;
So what cause it? how can I specify dbname when creating PDO without the keys in result containing tablename?
Use PDO::FETCH_ASSOC in fetchAll(). If you use PDO::FETCH_NAMED it will return with alias name. If alias not present then with the table name. Attaching the doc for your further reference.

I'm unable to insert into MySQL using PHP (no errors are being displayed)

<?php
$q= $_REQUEST["q"];
$r = $_REQUEST["r"];
$s = $_SESSION['empid'];
$max = 0;
$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = '';
$dbname = 'employeesurvey';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$sql1 = "SELECT QuestionID FROM question";
if(!mysqli_query($conn,$sql1)){
echo 'error2 php';
}
while($rw1 = mysqli_fetch_array($sql1)){
$Q = $rw1['QuestionID'] ;
if ($max<$Q){
$max = $Q;
}
}
$Q = $Q+1;
$sql = "INSERT INTO question VALUES (".$Q.",'".$r."',".$s.",CURRENT_DATE(),".$q.",0)";
if(!mysqli_query($conn,$sql)){
echo "Error";
}
?>
The db, table names are all correct. I'm using xmlHttpRequest.open() to pass the values to this page
the call statement is:
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "gethint1.php?q=" + cid + "&r=" + question, true);
Im not getting any errors, nor the values are being inserted
Replace this line:
if(!mysqli_query($conn,$sql1)){
with these
$resultSet = mysqli_query($conn,$sql1);
if(!$resultSet){
And now replace this line:
while($rw1 = mysqli_fetch_array($sql1)){
With this one
while($rw1 = mysqli_fetch_array($resultSet)){
Reason is that you haven't executed query and stored the result set while at fetching record from result set, you are using direct query variable which is logically wrong.
why are you making a simple thing this complicated by obtaining Question id from table just use autoincrement field in your mysql table or use insert_id
and the problem is mysqli_fetch_array() function works on mysqli_query() function's output i.e. a object you are providing a string to a function which expects an object

How select from one MYSQL DB and insert it into another?

I'm running some small Updates via CRON and execute them with PHP.
Now I want to select something from DB1 and insert it into DB2
My Problem is, that these 2 DBs are on the same Server but with 2 different Users and its not possible to give 1 User permission to both DB's.
So I know this works with one user and dbconnect:
insert into db1.tbl1(data1,data2) values (select data2, data1 from db2.tbl2)
How can I do it with 2 db connects in one Loop?
Thanks
you can create two files of connection like this
<?PHP
function connect(){
$servername = "localhost";
$username = "user";
$password = "psw";
$database = "database";
$conn = new mysqli($servername, $username, $password, $database);
if(mysqli_connect_errno()){
echo "Error conectando a la base de datos: " . mysqli_connect_error();
exit();
}
else{
$conn->query("SET NAMES 'utf8'");
return $conn;
}
}
function disconnect($connection){
$disconnect = mysqli_close($connection);
}
?>
and in your php file and like this
require("connection.php");
$connection=connect();
require("connection2.php");
$connection2=connect2();
obviously in your connection2.php your funtion named connect2(); and in your loop you can use the two connection
$query="insert into db1.tbl1(data1,data2) values (select data2, data1 from db2.tbl2)";
$messageResult = "Good";
$band = true;
if(!($connection -> query($query))){
$messageResult = "Error";
$band = false;
}
or..
$query="insert into db1.tbl1(data1,data2) values (select data2, data1 from db2.tbl2)";
$messageResult = "Good";
$band = true;
if(!($connection2 -> query($query))){
$messageResult = "Error";
$band = false;
}
If u r using pdo. U declare 2 different connection.
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass)
$dbh2 = new PDO('mysql:host=localhost;dbname=test', $user2, $pass)
Then u do this
$query = $dbh->prepare(select statement);
$query->execute();
$data = $query->fetchAll(); // you get array of data
$query = $dbh2->prepare(insert statement);
$query->execute()
Create 2 dB connection in two different variable and make that work .... Take value of first db in one variable and simply dump that variable into second db .... Or you can use another dB or caching dB like redis to store one time temporary base.

PHP PDO always give only one result

I wrote a SQL query with PDO. DB table has 3 results with match the query. But the PDO shows only one result.
my code is this
conn.php
function connect() {
$servername = "localhost";
$dbname = "guiding_db";
$username = "user";
$password = "pass";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
}
_admin.php
include_once './conn.php';
function getStudentsRequests(){
$sql = "SELECT * FROM `user` WHERE signas = 'student' AND accept='0'";
$result = connect()->query($sql);
$out = $result->fetch(PDO::FETCH_ASSOC);
print_r($out);
return $out;
}
getStudentsRequests();
PDOStatement::fetch() loads a single row only. Use PDOStatement::fetchAll() to load all rows (or use a while loop):
$out = $result->fetchAll(PDO::FETCH_ASSOC);
fetch method return only one row from query. If you want all you need to use while loop or fetchAll method
fetch method return next result (one). If you wish get all results - use methods like fetchAll

Use SET #variable=? inside of mysqli prepared statement

i have a query that uses a few variables in mysql. The query looks something like this:
SET #var1 = 1;
SET #var2 = 2;
SELECT * FROM table WHERE table.column1=#var1
AND table.column2=#var2
AND table.colum3=#var1 * #var2;
I would like to make a prepared statement like:
$sql=' SET #var1 = ?;
SET #var2 = ?;
SELECT * FROM table WHERE table.column1=#var1
AND table.column2=#var2
AND table.colum3=#var1 * #var2;'
and then just bind two params to it. But this gives me an mysql sytax error near the SET #var1=?;
Of course, in the example, I could bind three variables and do the calculations before querying. In my real query there are more advanced calculations and I would need to bind the same variable to multiple places. And that seems like repeating and bad coding practice.
Any solutions for this?
PHP offers prepared statements and parametrized queries out of the box, you can just use them.
$var1 = 1;
$var2 = 2;
$connection = new PDO($dsn, $user, $password);
$sql = 'SELECT * FROM table WHERE table.column1=:var1 AND table.column2=:var2 AND table.colum3=:varSum';
$statement = $connection->prepare($sql);
$statement->bindValue(':var1', $var1, PDO::PARAM_INT);
$statement->bindValue(':var2', $var2, PDO::PARAM_INT);
$statement->bindValue(':varSum', $var1 + $var2, PDO::PARAM_INT);
$statement->execute();
This code is just an example, it is not tested.
you should use multi_query
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql=' SET #var1 = '.$v1.';
SET #var2 = '.$v2.';
SELECT * FROM table WHERE table.column1=#var1
AND table.column2=#var2
AND table.colum3=#var1 * #var2;'
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Here's an alternative solution: feed your values in to a subquery, then you can reference them from there:
function GetStuffFromTable(mysqli $db, int $column1, int $column2): array
{
$sql = '
SELECT *
FROM (SELECT ? var1, ? var2) vars
INNER JOIN table
ON table.column1 = vars.var1
AND table.column2 = vars.var2
AND table.column3 = vars.var1 * vars.var2;
';
$statement = $db->prepare($sql);
try
{
$statement->bind_param("ii", $column1, $column2);
$statement->execute();
$result = $stmt->get_result();
return $statement->fetch_all($result);
} finally {
$statement->close();
}
}
Note: I came here looking for an answer to the same question / I don't know PHP well, so can't comment on the quality of this solution from a PHP perspective.

Categories