I am using ajax to search from mysql database.
But I am getting error in query syntax saying error near where division=UNKNOWN.
what is correct syntax
code :
<?php
include('db.php');
if(isset($_POST['division'])){
$division=$database->filter($_POST['division']);
$check_user = array(
'division' => $division
);
$exists = $database->exists( 'tablename', 'division', $check_user );
if ($exists){
$sql2 = "select * from tablename where division = '".$division."' group by branch order by branch ASC";
$sql=$database->get_results($sql2);
echo '<option value="">--Select Branch--</option>';
foreach($sql as $row){
$name=$row['branch'];
echo '<option value="'.$name.'">'.$name.'</option>';
}
}
}
?>
Here Which is correct?
1)
$sql2 = "select * from tablename where division = '".$division."' group by branch order by branch ASC";
Or
2)
$sql2 = "select * from tablename where division = '$division' group by branch order by branch ASC";
As stated in many comments (Joshua Bakker / Saty / ADyson), you should really consider using PPS : Prepared Parameterized Statements. This will help Preventing SQL injection
This is a raw example of what you could use (please adapt to what you need) :
<?php
error_reporting(E_ALL); ini_set('display_errors', 1); /* let PHP help us */
$host = ""; /* your credentials here */
$user = ""; /* your credentials here */
$pwd = ""; /* your credentials here */
$db = ""; /* your credentials here */
/* store in PHP variable */
/* you may also want to perfom some other/more checking on this var */
/* NEVER trust user side data */
$division = $_POST['division'];
echo"[ division -> $division ]"; /* just checking value -> to be removed */
/* connexion to db */
$mysqli = mysqli_connect("$host", "$user", "$pwd", "$db");
if (mysqli_connect_errno()) { echo "Error: no connexion allowed : " . mysqli_connect_error($mysqli); }
/* make sure 'tablename' and 'branch' use below are correct -> adapt to your needs */
$query = " SELECT `branch` FROM `tablename` WHERE division=? GROUP BY `branch` ORDER BY `branch` ASC ";
$stmt = $mysqli->prepare($query); /* prepare query */
$stmt->bind_param("s", $division); /* bind param will sanitize :
here we make use of $var 'division' with 's' because it's a string AFAIK */
print_r($stmt->error_list); /* any error ? */
print_r($stmt->get_warnings()); /* any error ? */
print_r($stmt->error); /* any error ? */
$results = $stmt->execute();
$stmt->bind_result($branch); /* we use the result of the query */
$stmt->store_result();
if ($stmt->num_rows > 0) {
echo '<option value="">--Select Branch--</option>';
while($stmt->fetch()){
echo '<option value="'.$branch.'">'.$branch.'</option>';
}
}
else
{ echo"[ no data ]"; }
?>
Related
I'm trying to create a searchbar that search for the title .. database is working , content showing under searchbar then i search sth , it show me "connection succesfully and then no results .. what's wrong ?
<?php
include 'header.php';
?>
<h3>Rezultate</h3>
<div class"article-container">
<?php
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
echo "Connected successfully";
if(isset($_POST['submit-search']))
{
$search = mysqli_real_escape_string($conn, $_POST['search']);
$sql = "SELECT * FROM article WHERE a_title LIKE '%search%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if($queryResult >0)
{
while ($row = mysqli_fetch_assoc($result))
echo"<div>
<h3>".$row['a_title']."</h3>
<p>".$row['a_text']."</p>
<p>".$row['a_author']."</p>
<p>".$row['a_dat']."</p>
</div>";
}
else
{
echo "<br>No result!";
}
}
?>
</div>
Your SQL is wrong, when referencing the variable $search in the SQL query. Just change the %search% to %$search%:
$search = mysqli_real_escape_string($conn, $_POST['search']);
$sql = "SELECT * FROM article WHERE a_title LIKE '%$search%'";
Also, I strongly believe you should consider using Prepared Statements for anything which involves user input.
$search = "%" . $_POST['search'] . "%";
$sql = "SELECT * FROM article WHERE a_title LIKE ?";
if($stmt = $mysqli_prepare($conn, $sql)) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $search);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $district);
/* fetch value */
mysqli_stmt_fetch($stmt);
printf("%s Search Result: %s\n", $search);
/* close statement */
mysqli_stmt_close($stmt);
}
This will protect you a bit more against SQL Injections.
$sql = "SELECT * FROM article WHERE a_title LIKE '%search%'";
Your current query is searching for terms like the string "search". Fix it so it's a PHP variable.
$sql = "SELECT * FROM article WHERE a_title LIKE '%$search%'";
I am having some problem when retrieving data from my database using jquery.
This is my client.js
function get_sede_data(client) {
$('#client-detail-co').load('client.php?name='+client);
}
This is my client.php file
<?php
$name = $_GET['name'];
$sql_name = "select * from client where c_name = $name";
$re_sql_name = mysqli($con, $sql_name);
if (mysqli_num_rows($re_sql_name) > 0) {
while ($row = mysqli_fetch_assoc($re_sql_name)) {
echo
"<h1>Client details: {$row['c_name']}</h1>";
}
} else {
echo "ERROR" . mysqli_error($con);
}
mysqli_close($conexion);
?>
This normally works with clients with only one name (ex: George) but with a client with two names (ex: Mary Ann) it doesnt work. Any idea why it's not retreiving names with spaces?
To fix your issue, you need to enclose your variable with singlequotes, as it's a string and not an integer.
$name = $_GET['name'];
$sql_name = "select * from `client` where `c_name`='$name'";
$re_sql_name = mysqli($con, $sql_name);
if(mysqli_num_rows($re_sql_name) > 0) {
while($row = mysqli_fetch_assoc($re_sql_name)) {
echo "<h1>Client details: {$row['c_name']}</h1>";
}
} else {
echo "ERROR" . mysqli_error($con);
}
//you had this as "conexion" but you used "con" above, so I changed this to "con"
mysqli_close($con);
You should also convert to using prepared statements:
MySQLi Prepared Statements
$name = $_GET['name'];
/* prepare statement */
if ($stmt = $mysqli->prepare("select `c_name` from `client` where `c_name`= ?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $name);
/* execute query */
$stmt->execute();
/* bind variables to prepared statement */
$stmt->bind_result($c_name);
/* if num_rows > 0 then fetch values */
if($stmt->num_rows > 0) {
while ($stmt->fetch()) {
echo "<h1>Client details: {$c_name}</h1>";
}
} else {
//error reporting
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
PDO Prepared Statements
This is what I personally recommend, as I find it easier than mysqli.
First, you're connection handler needs to be changed to this:
$host = 'localhost';
$db = '';
$user = '';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host={$host};dbname={$db};charset={$charset}";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
Note: We edit some of the default database connection stuff here, most notibly ATTR_EMULATE_PREPARES. When this is true, prepared statements are emulated which could be only as safe as string concatenation
Then, your query will look like this:
stmt = $pdo->prepare("SELECT * FROM `client` WHERE `c_name`= ?");
$stmt->execute([$name]);
$results = $stmt->fetchAll();
if($results > 0) {
foreach($results as $result) {
echo "<h1>Client details: {$result['c_name']}</h1>";
}
} else {
//error reporting
}
I have this code in PHP where I'm trying to make a JSON based on the result of a prepared statement. The problem is that it is returning a completely white page, nothing appears.
$con = mysqli_connect(HOST,USER,PASS,DB);
$batch_sql = "select * from batchrecord";
$batch_res = mysqli_query($con,$batch_sql);
$row = mysqli_fetch_array($batch_res);
$batch_num = $row[0];
$start = $batch_num * 100;
$end = $start + 99;
if ($stmt = mysqli_prepare($con, "select tweetid, body from tweet where id >=
? and id <= ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ii", $start, $end);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $tweetid, $body);
$result = array();
/* fetch value */
while(mysqli_stmt_fetch($stmt)){
array_push($result,
array('Id'=>$tweetid,
'Body'=>$body,
));
}
/* close statement */
mysqli_stmt_close($stmt);
echo json_encode(array("result"=>$result), JSON_UNESCAPED_UNICODE);
}
else{
echo "Statement Prepare Error";
}
mysqli_close($con);
I already made the content of $tweetid and $body be printed inside the while statement as test and it works fine, meaning that the problem is not the query, but something with the array. What am I missing?
Thanks!
Try like this
$result = array();
while(mysqli_stmt_fetch($stmt)){
$result[] = array('Id'=>$tweetid,'Body'=>$body);
}
Demo :https://3v4l.org/XZOu5
I found the problem after some debugging. The problem was in the json_enconde function, which was silently failing because of JSON_ERROR_UTF8 type of error. I had some problems of special characters from my native language before I had success with just JSON_UNESCAPED_UNICODE before, but this time I added mysqli_set_charset($con, "utf8"); to the top of the code and it is now working. For the sake of completeness, the language is Brazilian Portuguese. The complete code is as follows.
$con = mysqli_connect(HOST,USER,PASS,DB);
mysqli_set_charset($con, "utf8");
$batch_sql = "select * from batchrecord";
$batch_res = mysqli_query($con,$batch_sql);
$row = mysqli_fetch_array($batch_res);
$batch_num = $row[0];
$start = $batch_num * 100;
$end = $start + 99;
if ($stmt = mysqli_prepare($con, "select tweetid, body from tweet where id >=
? and id <= ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ii", $start, $end);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $tweetid, $body);
$result = array();
/* fetch value */
while(mysqli_stmt_fetch($stmt)){
$result[] = array('Id'=>$tweetid,'Body'=>$body);
}
/* close statement */
mysqli_stmt_close($stmt);
echo json_encode(array("result"=>$result), JSON_UNESCAPED_UNICODE);
}
else{
echo "Statement Prepare Error";
}
mysqli_close($con);
Thanks for Barclick Flores Velasquez for the help. I'm new in php and I didn't know there was print_r for debugging, it helped a lot finding the solution.
I try to explain this well folks,
I have a database with 20 questions with two principles : 1) Cardiology and 2) Endocrine. And you can select using HTML selection menu either of the concepts or you can select 3) All.
And on my html page I have a selection menu with 3 options and they each have a value:
<div id="selectContainer1">
<select id="selectedPrinciple" name="selectedPrinciple">
<option value="" disabled="disabled" selected="selected">Select a System</option>
<option value="">All</option>
<option value="VASCULAR">Cardiology, Vascular System</option>
<option value="ENDOCRINE">Endocrine</option>
</select>
</div>
<input type="submit" value="Start">
I have this code on php:
$selectedPrinciple = $_POST['selectedPrinciple'];
$sql = ("SELECT * FROM qbanktable WHERE Principle = '$selectedPrinciple'"
Now when I select option "Cardiology" or "Endocrine", all the rows that are related to those are picked from my database and showed on the next page. But when I select "All" I get a syntax error because of course as it does have no value the row cannot be found on my database. Is there anything I can put for the option value for "All" that the mysql returns all the rows?
You could check if $selectedPrinciple is empty() and modify the query accordingly.
$selectedPrinciple = $_POST['selectedPrinciple'];
if(!empty($selectedPrinciple)) {
// this line indicates that you don't use prepared statements
$sql = "SELECT * FROM `qbanktable` WHERE `Principle` = '$selectedPrinciple'";
} else {
$sql = "SELECT * FROM `qbanktable`";
}
full example using mysqli prepared statement
$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);
}
$selectedPrinciple = $_POST['selectedPrinciple'];
if(!empty($selectedPrinciple)) {
// prepare and bind
$stmt = $conn->prepare("SELECT * FROM `qbanktable` WHERE `Principle` = ?");
$stmt->bind_param("s", $selectedPrinciple);
} else {
// prepare
$stmt = $conn->prepare("SELECT * FROM `qbanktable`");
}
// execute
$stmt->execute();
// fetch data
if (!($res = $stmt->get_result())) {
echo "Failed to fetch the result set: (" . $stmt->errno . ") " . $stmt->error;
}
// print data
print_r($res->fetch_all());
// close prepared statement
$stmt->close();
// close connection
$conn->close();
Personally, I like to use a few techniques to "build" my query, like so:
NOTE:
I'm demonstrating how to do this with PDO and parameter binding, because your query is open to SQL injection attacks.
$sql = "SELECT * FROM `qbanktable`";
$where = [];
$params = [];
if ( ! empty( $_POST['selectedPrinciple'] ) ) {
$where[] = '`Principle` = ?';
$params[] = $_POST['selectedPrinciple'];
}
if ( /* some other condition */ ) {
// add to the $where / $params as appropriate
}
// Glue the $where into a string
$where = implode( ' AND ', $where );
// Append where to the $sql statement
$sql .= ( $where ) ? ' WHERE ' . $where : '';
// assumes $conn is already a set-up PDO connection
$stmt = $conn->prepare( $sql );
$stmt->execute( $params );
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
I think the best way is to check in PHP if the value of selectedPrinciple is something like ALL or is empty, and then don´t add the WHERE part of the query.
If really want to use some value for All option, you can try to use one or two percents signs '%' or '%%', but I don´t remember if it works. However, I don´t recommend this approach. Take care also about SQL Injection.
I'm new to mysqli, I wrote a function as below.
1 - I couldn't find a way for SELECT * query and having bind_result to assign each column value to the same name variable. (e.g. name column value of #row stores to $name)
I think bind_result() has no function on a SELECT * query?
2 - So I tried another option, to fetch all rows and assign them to appropriate variable manually through a loop. I think I should use $query->fetch_all() or $query->fetch_assoc() for looping but I encounter with this:
Fatal error: Call to undefined method mysqli_result::fetch_all()
or
Fatal error: Call to undefined method mysqli_result::fetch_assoc()
However I did a phpinfo() and saw mysqlnd was enabled and php version is 5.4.7 (running XAMPP v1.8.1)
And 3- what finally I did is below idea that doesn't work either.
function the_names($name)
{
global $db;
if($query = $db->prepare("SELECT * FROM users where name=?"))
{
$query->bind_param('s', $name);
if($query->execute())
{
$query->store_result();
if($query->num_rows > 1)
{
while($row = $query->fetch())
{
echo $row['name']; // Here is the problem
}
}
else
echo "not valid";
$query->close();
}
}
}
I need a way to store all fetched data as what bind_result() does, or having them in an array for later use, and it's much better to know both. tnx
One word to answer all your questions at once - PDO
It has everything you are trying to get from mysqli (in vain):
function the_names($name)
{
global $db;
$query = $db->prepare("SELECT * FROM users where name=?");
$query->execute(array($name));
return $query->fetchAll();
}
$names = the_names('Joe');
foreach ($names as $row) {
echo $row['name'];
}
Note the proper way of using a function. it should never echo anything, but only return the data for the future use
If your mysqli code doesn't have binding_param() you can just write code like below :
$mysqli = new mysqli("localhost" , "root" , "" , "database_name");
$result = $mysqli->query( "SELECT * FROM users where name=" . $name) ;
while ( $row = $result->fetch_assoc() ) {
echo $row["name"];
}
If you use binding_param() code , you also need to set bind_result()
$db = new mysqli("localhost" , "root" , "" , "database_name");
function the_names($name){
global $db;
/* Prepared statement, stage 1: prepare */
if (!($query = $db->prepare("SELECT * FROM users where name=?"))) { # prepare sql
echo "Prepare failed: (" . $db->errno . ") " . $db->error;
}
/* Prepared statement, stage 2: bind and execute */
if (!$query->bind_param("s", $name)) { # giving param to "?" in prepare sql
echo "Binding parameters failed: (" . $query->errno . ") " . $query->error;
}
if (!$query->execute()) {
echo "Execute failed: (" . $query->errno . ") " . $query->error;
}
$query->store_result(); # store result so we can count it below...
if( $query->num_rows > 0){ # if data more than 0 [ that also mean "if not empty" ]
# Declare the output field of database
$out_id = NULL;
$out_name = NULL;
$out_age = NULL;
if (!$query->bind_result($out_id, $out_name , $out_age)) {
/*
* Blind result should same with your database table !
* Example : my database
* -users
* id ( 11 int )
* name ( 255 string )
* age ( 11 int )
* then the blind_result() code is : bind_result($out_id, $out_name , $out_age)
*/
echo "Binding output parameters failed: (" . $query->errno . ") " . $query->error;
}
while ($query->fetch()) {
# print the out field
printf("id = %s <br /> name = %s <br /> age = %s <br />", $out_id, $out_name , $out_age);
}
}else{
echo "not valid";
}
}
the_names("panji asmara");
Reference :
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php