I am using PHP and MySql. TeX is posted to server.php file through a form and exploded into an array:
foreach($_POST['ques'] as $i){
$arr = explode('~', $i);
}
$sql = "INSERT INTO `QUESTIONS`(`Text`) VALUES ('$arr[2]')";
$run = mysql_query( $sql, $conn ) or die(mysql_error());
Btw echo $arr[2]; shows correct Tex syntax : "[\Rightarrow{z=\frac{43}{-44}}]"
But on database it is stored without backslashes "[Rightarrow{z=frac{43}{-44}}]"
Do not use old mysql_* functions. Use mysqli_*. or PDO as in this example.
The parameterized/prepared query makes you to stop worrying about quoting and malicious sql-attacks. (But drive safely anyway)
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$dbh = new PDO($dsn, $user, $password);
$sth = $dbh->prepare("INSERT INTO `QUESTIONS`(`Text`) VALUES (?)");
$sth->execute(array($arr[2]));
Related
MySQL is not using the variables as it should. it is not taking any value from them it is incrementing the auto-increment numbers in the MYSQL table, however the row is not saved. I am not given any errors.
I have tried like this:
$sql = "INSERT INTO `tbl_bike` (`userID`, `ManuPartNo`, `BikeManufacturer`, `BikeModel`, `BikeType`, `BikeWheel`, `BikeColour`, `BikeSpeed`, `BrakeType`, `FrameGender`, `AgeGroup`, `DistFeatures`)
VALUES (“.$userID.”, “.$PartNo.”, “.$BikeManufacturer.”, “.$BikeModel.”, “.$BikeType.”, “.$BikeWheel.”, “.$BikeColour.”, “.$BikeSpeed.”, “.$BrakeType.”, “.$FrameGender.”, “.$AgeGroup.”, “.$DistFeatures.”)";
I have also tried replacing the " with ', Removing the . and even completely removing the ". Nothing has helped with this issue. When I use this query but remove the variables and instead put string, int etc in the correct places the query will function perfectly and put the results into the table. My variables are normally as follows:
$PartNo = $_POST['ManuPartNo’];
$BikeManufacturer = $_POST['BikeManufacturer’];
$BikeModel = $_POST['BikeModel’];
$BikeType = $_POST['BikeType’];
$BikeWheel = $_POST['BikeWheel’];
$BikeColour = $_POST['BikeColour’];
$BikeSpeed = $_POST['BikeSpeed’];
$BrakeType = $_POST['BrakeType’];
$FrameGender = $_POST['FrameGender’];
$AgeGroup = $_POST['AgeGroup’];
$DistFeatures = $_POST['DistFeatures’];
These variables normally take input from a separate PHP/HTML file with the '$_POST['DistFeatures’];'
I have tried removing the $_POST['DistFeatures’]; from the ends of each of them and just replacing the values with normal string or int values but still nothing helps. I am completely stuck and would appreciate any help with this.
This is all running on a plesk server.
Please stop using deprecated MySQL. I will suggest an answer using PDO. You can use this to frame your other queries using PDO.
// Establish a connection in db.php (or your connection file)
$dbname = "dbname"; // your database name
$username = "root"; // your database username
$password = ""; // your database password or leave blank if none
$dbhost = "localhost";
$dbport = "10832";
$dsn = "mysql:dbname=$dbname;host=$dbhost";
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
// Include db.php on every page where queries are executed and perform queries the following way
// Take Inputs this way (your method is obsolete and will return "Undefined Index" error)
$userId = (!empty($_SESSION['sessionname']))?$_SESSION['sessionname']:null; // If session is empty it will be set to Null else the session value will be set
$PartNo = (!empty($_POST['ManuPartNo']))?$_POST['ManuPartNo']:null; // If post value is empty it will be set to Null else the posted value will be set
$BikeManufacturer = (!empty($_POST['BikeManufacturer']))?$_POST['BikeManufacturer']:null;
$BikeModel = (!empty($_POST['BikeModel']))?$_POST['BikeModel']:null;
$BikeType = (!empty($_POST['BikeType']))?$_POST['BikeType']:null;
$BikeWheel = (!empty($_POST['BikeWheel']))?$_POST['BikeWheel']:null;
// Query like this
$stmt = $pdo->prepare("INSERT INTO(`userID`, `ManuPartNo`, `BikeManufacturer`, `BikeModel`, `BikeType`)VALUES(:uid, :manuptno, :bkman, :bkmodel, :bktype)");
$stmt-> bindValue(':uid', $userId);
$stmt-> bindValue(':manuptno', $PartNo);
$stmt-> bindValue(':bkman', $BikeManufacturer);
$stmt-> bindValue(':bkmodel', $BikeModel);
$stmt-> bindValue(':bktype', $BikeType);
$stmt-> execute();
if($stmt){
echo "Row inserted";
}else{
echo "Error!";
}
See, it's that simple. Use PDO from now on. It's more secured. To try this, just copy the whole code in a blank PHP file and and run it. Your database will receive an entry. Make sure to change your database values here.
You should try this
$sql = "INSERT INTO tbl_bike (userID, ManuPartNo, BikeManufacturer, BikeModel, BikeType, BikeWheel, BikeColour, BikeSpeed, BrakeType, FrameGender, AgeGroup, DistFeatures) VALUES ('$userID', '$PartNo', '$BikeManufacturer', '$BikeModel', '$BikeType', '$BikeWheel', '$BikeColour', '$BikeSpeed', '$BrakeType', '$FrameGender', '$AgeGroup', '$DistFeatures')";
If this doesn't work, enable the null property in sql values. So you can find out where the error originated.
I've tried to debug this times without success. Here is what I've tried so far
<?php
$cid= (string)$_GET['cid'];//I passed this from another page using get method
echo $cid; //My code works up to this point
$record = mysql_query("select * from questions where QType = '$cid'");
$array = array();
while($row = mysql_fetch_assoc($record))
{
$array[] = $row;
}
for($var = 0; $var<count($array);$var++)
{
echo $array[$var]['Question'].'<br>';
}
?>
This code will work and is a bit safer
<?php
//Connection part
$servername = "server_adress"; //It can be localhost or 127.0.0.1 or some other IP
$username = "XXXXXX"; //Username for DB
$password = "YYYYYY"; //Password for that user
$database = "ZZZZZZ"; //DB name you are connecting to
//Create a new connection
$conn_to_db = new mysqli($servername, $username, $password,$database);
// Check connection
if ($conn_to_db -> connect_error) {
die("Connection failed: " . $conn_to_db ->connect_error);
}
//Finished connection part
$cid = mysqli_real_escape_string($conn_to_db, $_GET['cid']); //Escapes special characters in a string for use in an SQL statement
$array = array();
if($stmt = $conn_to_db -> ("SELECT * FROM questions WHERE QType = ?")) {
$stmt -> bind_param("s", $cid);
$stmt -> execute();
$stmt -> bind_result($question_from_db); //Here you can put all variables you are fetching from DB
while($stmt -> fetch()){
//Iterate over rows - put your code here to fetch everything you need from DB and put in array
$array[] = array('question' => $question_from_db);
}
$stmt -> close();
}
}
//you can iterate over rows like this
foreach($array as $key => $value) {
echo $value['question'];
}
?>
Couple of things to keep in mind:
it's a good practice to avoid * (selecting everything from DB) and
put only columns you need from DB
use prepared statement which is a safer way and protects you from SQL injection
MySQL is depreciated so try to avoid it (use mysqli or PDO)
The code above you need to adjust to your needs! It will not work as copy/paste. Put your DB connection and select columns from DB you need and add variables which you fetch from DB
Keep in mind there are more ways to do this, and someone will probably give another solution.
if you are not on a production server, it's good to have some error reporting to see the errors that are happening
I am new in Php and MYsql,
I am trying to create a simple query using which contain a variable using php.
however I think I am not writing the querty correctly with the variable since the result of this query is 0.
would be happy for assistance here is my code:
<?php
$phone = $_GET['phone'];
echo $phone;
$query = "SELECT * FROM `APPUsers` WHERE `Phone` LIKE "."'".$phone."' ";
echo $query;
$result = mysqli_query($mysqli, $query);
echo mysqli_num_rows($result);
?>
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM APPUsers WHERE Phone LIKE '%$phone%'";
$result = $conn->query($sql);
Above there is a fast solution , but it is not safe ,
because is vulnerable to injection ...
Below let's see how to do it and why to do it in this way
It is a good practice to store sensible information in a separate file
out of the document root , it means will be not accesible from the web .
So let's create a file configDB.ini for example and put in db informations
servername = something;
username = something;
password = something;
dbname = something;
Once did it we can create a script called dbconn.php and import the file with credentials ,
in this way there is an abstraction between credentials and connection .
in dbconn.php :
$config = parse_ini_file('../configDB.ini');
$conn = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
We can even improve the code connecting to db only once and use the same connection all the time we need query .
function db_connect() {
// static will not connect more than once
static $conn;
if(!isset($conn)) {
$config = parse_ini_file('../configDB.ini');
$conn = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
}
return $conn;
}
...
$conn = db_connect();
$sql = "SELECT * FROM APPUsers WHERE Phone LIKE '%$phone%'";
$result = mysqli_query($conn,$sql);
In the end let's say something about mysqli_query
Reasons why you should use MySQLi extension instead of the MySQL extension are many:
from PHP 5.5.0 mysql is deprecated and was introduced mysqli
Why choose mysqli (strenghts)
object oriented
prepared statements
many features
no injection
Do you connect to the database?
The apostrophes around APPUsers and Phone might not be the right ones, as they are not the single apostrophes but some weird squiggly ones.
Try this :
$query = "SELECT * FROM 'APPUsers' WHERE 'Phone' LIKE '".$phone."' ";
Sometimes it sucks when you have these ; " ' (semicolon, single and double quotation marks) everything in a string.
Question is simple what is the easiest way to send those sting into the database.
base64_encode();
base64_decode();
// Is not an option. I need to keep those data just same as it is.
You need
addslashes('your text') // in your php page
PDO statements is the best solution to your problem of executing SQL queries to your database with values that have single/double quotation marks... but more importantly PDO statements help prevent SQL injection.
To show you how this works, this very simple example gives you a basic understanding of how PDO statements work. All this example does is make the connection to the database and insert the username, email and password to the users table.
<?php
// START ESTABLISHING CONNECTION...
$dsn = 'mysql:host=host_name_here;dbname=db_name_here';
//DB username
$uname = 'username_here';
//DB password
$pass = 'password_here';
try
{
$db = new PDO($dsn, $uname, $pass);
$db->setAttribute(PDO::ERRMODE_SILENT, PDO::ATTR_EMULATE_PREPARES);
error_reporting(0);
} catch (PDOException $ex)
{
echo "Database error:" . $ex->getMessage();
}
// END ESTABLISHING CONNECTION - CONNECTION IS MADE.
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$hashed_password = password_hash($password, DEFAULT_BCRYPT);
//Validation on inputs here...
// Your SQL query... here is a sample one.
$query = "INSERT INTO users (userName, email, password) VALUES (:userName, :email, :password)";
$statement = $db->prepare($query);
// The values you wish to put in.
$statementInputs = array("userName" => $username, "email" => $email, "password" => $hashed_password);
$statement->execute($statementInputs);
$statement->closeCursor();
?>
You could put the establishing connection part in a separate file and require_once that file to avoid having to write the same code, again and again to establish a connection to your database.
Use mysqli_real_escape_string
$someText = mysqli_real_escape_string($con,"It's a test.");
where $con is your database connection variable.
Following this blog post, I managed to connect to a MSSQL Server form PHP/CentOS machine. I can get result, however I can not use comparison in the where clause. I should be due to different encoding. Here is my code:
$db = new PDO("odbc:USERS", "username", "password");
$sql = "SELECT top 1 name FROM user where name='تست'";
$stmt = $db->prepare($sql);
$result = $stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
var_dump($row);
Also using $name = mb_convert_encoding('تست', 'utf16'); (also 'UCS-2LE' encoding) Was not helpful. How config PHP/MSSQL to use a single encoding?