PHP and SQL syntax issue - php

I am having problems with a (should be simple) bit of code. I am getting info from a form and trying to echo out an entry/ies in a database that match the form specifications. I think that my HTML is correct, and my problem lies in the PHP. Here is my code that I need help with:
<?php
$submit = #$_POST['submit'];
$gender = $_POST['gender'];
$hair = $_POST['hair'];
$height = $_POST['height'];
$body = $_POST['body'];
if ($submit){
//open database
$connect = mysql_connect("xxxx", "xxxx", "xxxx") or die("Couldnt Connect to Server");
mysql_select_db("xxxx") or die("Couldnt find database");
$query = mysql_query("SELECT * FROM `table` WHERE `gender`='$gender' AND `hair`='$hair' AND `height`='$height' AND `body`='$body'");
$query_run = mysql_query($query);
if ($query_run = mysql_query($query)) {
while ($query_row = mysql_fetch_assoc($query_run)) {
$pic = $query_row['picture'];
};
};
};
?>
This is a self submitting page <form action='thispage.php' method='post'>. Later down the page in the empty space is where I am going to echo $pic.
Is this method correct/the best way to do it? If need be, I will post the code for the entire page. It is only 75 lines right now.
And before I am told that I should be using SQLi, this is more of a proof of concept right now, and more importantly I don't know how to make the changes from SQL to SQLi.
edit: Within the form, there are only options, not text input (if that matters)

Here's how I would do it using modern libraries
// check that all required POST parameters are present
if (isset($_POST['submit'], $_POST['gender'], $_POST['hair'], $_POST['height'],
$_POST['body'])) {
// create DB connection
$pdo = new PDO('mysql:host=localhost;dbname=xxxx;charset=utf8',
'xxxx', 'xxxx');
// set error mode and use real prepared statements if possible
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
// prepare an SQL statement with parameter placeholders
// I changed the * to just `picture` as that's all you were using in your OP
$stmt = $pdo->prepare('SELECT `picture` FROM `table` WHERE `gender` = ? AND `hair` = ? AND `height` = ? AND `body` = ?');
// execute with the POST parameters
$stmt->execute(array(
$_POST['gender'],
$_POST['hair'],
$_POST['height'],
$_POST['body']
));
// load all "picture" results into an array
$pics = array();
while ($pic = $stmt->fetchColumn()) {
$pics[] = $pic;
}
}

$query = mysql_query("SELECT * FROM `table` WHERE `gender`='$gender' AND `hair`='$hair' AND `height`='$height' AND `body`='$body'");
$query_run = mysql_query($query);
if ($query_run = mysql_query($query)) {
while ($query_row = mysql_fetch_assoc($query_run)) {
$pic = $query_row['picture'];
};
};
should be
$query = "SELECT * FROM `table` WHERE `gender`='$gender' AND `hair`='$hair' AND `height`='$height' AND `body`='$body'";
if ($query_run = mysql_query($query)) {
while ($query_row = mysql_fetch_assoc($query_run)) {
$pic = $query_row['picture'];
};
};
$query = mysql_query("SELECT * FROM `table .........
$query_run = mysql_query($query); extra

Related

PHP Mysql how to retrieve product by category

When I enter category name manually, I'm able to get its product but when I insert a variable to like the code, I get success but data is empty.
Connection file:
<?php
//cnnection.php
$server = "localhost";
$user = "root";
$password = "";
$db = "db_ecommerce_shoes";
$connect = new mysqli($server,$user,$password,$db);
Main script:
<?php
include '../connection.php';
With this, request is successful but data is empty
$name= 'name';
$sql = "SELECT * FROM tb_shoes
WHERE
catName ='$name'
";
With this, request is successful, data is loaded successful
$sql = "SELECT * FROM tb_shoes
WHERE
catName ='Ladies Shoe'
";
$result = $connect->query($sql);
if($result) {
$data = array();
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
echo json_encode(array(
"success"=>true,
"data"=> $data,
));
} else {
echo json_encode(array(
"success"=>false,
));
}
Any other way of doing this will be much appreciated.
Any other way of doing this will be much appreciated
You should never be directly concatenating variables into the SQL query making it vulnerable to SQL injections. That is a major security issue.
Read about a simple and easy to understand version of prepared statements here.
In your case, try this out
$category = "Ladies Shoe"
$statement = $connect->prepare("SELECT * FROM tb_shoes WHERE catName = ? ")
$statement ->bind_param("s", $category);
$statement ->execute();
$result = $statement ->get_result();
Then you can loop through the results as above. Check if it works!
Try to assign
$name = 'Ladies Shoe';
$sql = "SELECT * FROM tb_shoes
WHERE
catName ='$name'
";
Does this work?

select from the whole database after applying where condtion on one of the table

I have a database consisting of 10 table listed in the $tables,
One of the table called tbl_module contain a column called delete_time, the following statment selects all data from these tables :
$statement = "SELECT * FROM tbl_".$table;
what i need to do is to add a condition to select all data from these table WHERE the value of delete_time in tbl_module IS NULL
the php code is:
<?php
// alle relevanten Tabellen abfragen und als json zurückgeben.
$json["status"] = "running";
$details[] = "started get_tables ";
// Include confi.php
include_once('confi.php');
//var_dump($_POST);
$request_body = file_get_contents('php://input');
// first store the given set of data to keep it for future analysis
$statement = "INSERT INTO tbl_archive (content) VALUES ('$request_body' );";
mysql_query($statement);
$input = json_decode($request_body, true);
// now check if valid user
$user = $input["user"];
$username = $user["username"];
$password = $user["password"];
if($password and $username){
$mySQLstring = "SELECT username, password, id FROM tbl_user where username = '$username' ;";
$json["statement"][] = $mySQLstring;
$qur = mysql_query($mySQLstring);
//var_dump ( $qur );
if ($qur){
$res = mysql_fetch_assoc($qur);
}
if ($res){
$json["res"] = $res;
if ($res["password"] == $password){
$json["username"] = $username;
$json["id"] = $res["id"];
$json["status"] = "ok";
$tables = array("class", "class_user", "module", "module_class", "module_user", "rating", "student", "student_class");
//$tables = array("class");
foreach($tables as $table){
$statement = "SELECT * FROM tbl_".$table;
$qur = mysql_query($statement);
if ($qur){
while($r = mysql_fetch_array($qur, MYSQL_ASSOC)){
//var_dump($r);
//echo (json_encode($r));
$result[$table][] = $r;
}
}
}
$json = array("status" => "ok", "data" => $result);
}
}
}
#mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
?>
That is fairly simple all you need to do is alter the $statement if the $table = module like this
$tables = array("class", "class_user", "module", "module_class",
"module_user", "rating", "student", "student_class");
foreach($tables as $table){
$statement = "SELECT * FROM tbl_".$table;
if ( $table == 'module' ) {
$statement .= ' WHERE delete_time IS NOT NULL ';
// and to add not equal to 0000-00-00 00:00:00
$statement .= " AND delete_time != '0000-00-00 00:00:00' ";
}
$qur = mysql_query($statement);
if ($qur){
while($r = mysql_fetch_array($qur, MYSQL_ASSOC)){
//var_dump($r);
//echo (json_encode($r));
$result[$table][] = $r;
}
}
}
NOTE1:
Please dont use the mysql_ database extensions, it is deprecated (gone for ever in PHP7)
Especially if you are just learning PHP, spend your energies learning the PDO or mysqli_ database extensions,
and here is some help to decide which to use
NOTE2:
You have some other major problems in this code, mainly that you are using data straight from the $_POST array without doing any validation or sanity checks on it, and putting it directly into a query. This you should fix, but using PDO and named or ? positional parameters would go a long way to mitigating this problem.

PHP PDO Insert Into statement doesn't work with no errors

At the end of this code there is a INSERT INTO statement that doesn't do anything. My connection.php is OK because I have used the same file in other projects and they work.
I am actually inserting a lot more data, but I was trying to find the problem out so I've removed a lot of variable from the INSERT statement.
<?php
include("connection.php");
include("functions.php");
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
date_default_timezone_set('Asia/Dhaka');
$mobile = (string)$_GET["mobile_number"];
$promo = (string)$_GET["promo_code"];
$type = (string)$_GET["type"];
$type_no = (($type=="imei") ? (string)$_GET["imei"] : (string)$_GET["udid"]);
$ip = (string)$_SERVER['REMOTE_ADDR'];
$signup_date = date("Y-m-d");
$q1 = "SELECT * FROM vbClient WHERE clCustomerID = :mobile";
$chk_mob_switch = $dbh->prepare($q1);
$chk_mob_switch->bindParam(':mobile', $mobile);
$chk_mob_switch->execute();
if ($chk_mob_switch->rowCount() == 0) {
$q2 = "SELECT * FROM api_db WHERE type_no = :type_no";
$chk_imei_bknd = $dbh->prepare($q2);
$chk_imei_bknd->bindParam(':type_no', $type_no);
$chk_imei_bknd->execute();
if ($chk_imei_bknd->rowCount() == 0) {
$validation_code = (string)generateValidationCode(6);
$request_id = (string)generateRequestID(15);
$q3 = "INSERT INTO api_db (mobile) VALUES (:mobile)";
$ins_info_bknd = $dbh->prepare($q3);
$ins_info_bknd->bindParam(':mobile', $mobile);
$ins_info_bknd->execute();
}
To check for errors I am using a function like the following:
function chkSyntax($dbh, $stmt, $query) {
$stmt = $dbh->prepare($query);
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
}
And then I'm calling it like this:
chkSyntax($dbh, $chk_mob_switch, $q1);
What am I doing wrong?

PHP & MYSQL: Select from where id=$id

So I'm making a usergroup function that allows me to block off pages to lower user levels. This is my function for grabbing info:
function grab_info($id, $requested_info){
$id = $_SESSION['user_id'];
$requested_info = $requested_info;
$con = new mysqli('localhost', 'root', '', 'login');
if ($con->connect_errno >0){
die("Handle your connection error here");
}
$sql = "SELECT * FROM `users` WHERE `id` = $id";
if (!$result = $con->query($sql)) {
die("There as a query error for some reason handle your query error");
}
while($row = $result-fetch_assoc()){
$info = $row[$requested_info];
return $info;
}
}
Right here:
$sql = "SELECT * FROM `users` WHERE `id` = $id";
if (!$result = $con->query($sql)) {
die("There as a query error for some reason handle your query error");
}
is where something is going wrong. This is my method for grabbing the info:
$id = $_SESSION['user_id'];
$rank = grab_info($id, 'rank');//Gets rank from our id
$meets = can_access($rank, 4, true);//We're saying our user has a rank of 1 to access this page you need a rank of 3 and only 3 hence strict
if ($meets == false){//user cant access page
header("Location: index.php");
die();
}
Basically, it just keeps giving me the "There as a query error for some reason handle your query error" and I'm stuck. New to php so sorry if it's messy.
Using prepared statements and cast the variable as an integer.
$stmt = $con->prepare("SELECT * FROM `users` WHERE `id` = ?");
$stmt->bind_param("i",$id);
$id = (int) $_SESSION['user_id'];
$stmt->execute();
$result = $stmt->get_result();
Check to make sure that $id is actually set. If it's null that will cause your query to explode.
$sql = "SELECT * FROM `users` WHERE `id`='{$id}'";
Try this :)
$query=mysql_query("SELECT * FROM user WHERE user_email='$user_email');
Please try this:
function grab_info($id, $requested_info){
$id = $_SESSION['user_id'];
$requested_info = $requested_info;
$con = new mysqli('localhost', 'root', '', 'login');
if ($con->connect_errno >0){
die("Handle your connection error here");
}
$sql = "SELECT * FROM users WHERE id =". $id;
if (!$result = $con->query($sql)) {
die("There as a query error for some reason handle your query error");
}
while($row = $result->fetch_assoc()){
$info = $row;
return $info;
}
}

How to prepare a MySQL query using a variable length parameter list in PHP

I've got a simple PHP script which queries a mysql database for basic user info based on the data fetched from an HTML form.
<?php
$age = $_POST['age'];
$gender = $_POST['gender'];
$dbc = mysqli_connect('localhost', 'root', 'abc123', 'mydb')
$query = "SELECT * FROM users WHERE AGE='$age' AND GENDER='$gender'";
$result = mysqli_query($dbc, $query) or die('Querying the db failed');
mysqli_close($dbc);
?>
The problem is that the user doesn't always have to pick a gender or age and as a result the query doesn't always succeed. In other words I'm looking for something like this:
//(In pseudocode)
if (only $age exists) then:
$query = "SELECT * FROM users WHERE AGE='$age'
if (only $gender exists) then:
$query = "SELECT * FROM users WHERE GENDER='$gender'
if (both $age and $gender exist) then:
$query = "SELECT * FROM users WHERE AGE='$age' AND GENDER='$gender'";
otherwise:
$query = "SELECT * FROM users"
How should I do this? (in the actual script there are way more variables than just age and gender).
Dynamically build your list of placeholders and values:
$opts = array();
$values = array();
if (isset($_POST['age']) && (strlen($_POST['age']) > 0)) {
$opts[] = 'AGE = ?';
$values[] = $_POST['age'];
}
if (isset($_POST .... etc...) {
$opts[] = 'somefield = ?';
$values[] = 'value for this field';
}
etc...
$sql = "SELECT ..."; // basic query, WITHOUT where clause
if (count($opts) > 0) {
$sql .= ' WHERE ' . implode(',', $opts); // add in dynamic where options
}
$stmt = $mysqli->prepare($sql);
$result = $stmt->execute($values); // pass in the values for the ? placeholders

Categories