What is wrong with the SQL Syntax in this PHP code? - php

I am learning PHP so I was practicing SQL and CRUD in PHP however I seem to have an issue but I don't see what is wrong. There are two files:
databases.php
<?php
// 1. Create a database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$dbname = "widget_corp";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Test if connection occured
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
?>
<?php
// Perform database query
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
// Test if there was a query error
if (!$result) {
die("Database query failed.");
}
?>
<!DOCTYPE html PUBLIC "-//W3C/DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<title>Databases</title>
<body>
<ul>
<?php
// 3. Use returned data (if any)
while($subject = mysqli_fetch_assoc($result)) {
// Output data from each row
?>
<li><?php echo $subject["menu_name"] . " (" .$subject["id"] . ")"; ?></li>
<?php
}
?>
</ul>
<?php
// 4. Release returned data
mysqli_free_result($result);
?>
</body>
<?php
// Close database connection
mysqli_close($connection);
?>
and databases_update.php
<?php
// 1. Create a database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$dbname = "widget_corp";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Test if connection occured
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
?>
<?php
// Often these are form values in $_POST
$id = 5;
$menu_name = "Delete me";
$position = 4;
$visible = 1;
// 2. Perform database query
$query = "UPDATE subjects SET ";
$query .= "menu_name = '{$menu_name}', ";
$query .= "position = {$position}, ";
$query .= "visible = {$visible}, ";
$query .= "WHERE id = {$id}";
$result = mysqli_query($connection, $query);
// Test if there was a query error
if ($result) {
// Success
// redirect_to("somepage.php");
echo "Success!";
} else {
// Failure
// message = "Subject creation failed";
die("Database query failed. " . mysqli_error($connection));
}
?>
<!DOCTYPE html PUBLIC "-//W3C/DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<title>Databases</title>
<body>
</body>
<?php
// Close database connection
mysqli_close($connection);
?>
The error I am receiving is when I go to localhost:8888/databases_update.php.
This is the error:
Database query failed. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id = 5' at line 1
What is causing this?

$query .= "visible = {$visible}, ";
$query .= "WHERE id = {$id}";
is the problem where there is a comma preceding the "WHERE" keyword.
visible = {$visible}, WHERE id = {$id}

The answer by Wallyk is correct. However it would be better (safer!) to use prepared statements as they prevent SQL injection by improper escaping.
What you then need to do is use the mysqli_prepare function (or $connection->prepare()), then bind the required parameters to the query, and execute it. Like so:
Replace:
$query = "UPDATE subjects SET ";
$query .= "menu_name = '{$menu_name}', ";
$query .= "position = {$position}, ";
$query .= "visible = {$visible}, ";
$query .= "WHERE id = {$id}";
$result = mysqli_query($connection, $query);
With:
$query = $connection->prepare("UPDATE subjects SET menu_name=?, position=?, visible=? WHERE id=?");
$query->bind_param('siii', $menu_name, $position, $visible, $id); // siii means 1 string, followed by 3 integer values
$result = $query->execute(); // actually run the query

Related

How to get all values when parameter is null

I have a query form where I need to fetch details from a custom table in MYSQL. If the parameter is left blank all records should be fetched. If there is a value entered in the parameter then records for that value should be fetched.
This is my code so far:
<?php
$host = 'localhost';
$dbname = 'test';
$username = 'test';
$password = 'xxx';
session_start();
global $wpdb, $current_user;
$conn = mysqli_connect($host, $username, $password, $dbname);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$param_1=mysqli_real_escape_string($conn,$_GET['param_1']);
if (!empty($param_1)){
$sql = "SELECT column1 ,column2,column3,column4,column5
FROM xxx
WHERE column1='$param_1'";
} else {
$sql = 'SELECT column1 ,column2,column3,column4,column5
FROM xxx';
}
$query = mysqli_query($conn, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>
This works fine with one parameter. I will need to add more parameters and those could also be null.
For e.g.
$sql = "SELECT column1 ,column2,column3,column4,column5
FROM xxx
WHERE column1='$param_1' AND column2='$param_2";
Either of these could be null. How do I take care of this in MYSQL?
My question is what would be the best way to take care of this situation?
Thanks in advance.
You can keep appending the query like this:
$sql = "SELECT column1 ,column2,column3,column4,column5
FROM xxx
WHERE 1=1 ";
if(!empty($param1)){
$sql.= " and column1='$param1'";
}
if(!empty($param2)){
$sql.= " and column2='$param2'";
}
if(!empty($param3)){
$sql.= " and column3='$param3'";
}
Note: Passing parameters like this would lead to SQL injection, use binding to pass parameters to avoid SQL Injection. Here is a good read about it.
You can follow the below steps
<?php
$host = 'localhost';
$dbname = 'test';
$username = 'test';
$password = 'xxx';
session_start();
global $wpdb, $current_user;
$conn = mysqli_connect($host, $username, $password, $dbname);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$whereArr=[];
if(isset($_GET['param_1'])){
$whereArr[]="column1=" . mysqli_real_escape_string($conn,$_GET['param_1']);
}
if(isset($_GET['param_2'])){
$whereArr[]="column2=" . mysqli_real_escape_string($conn,$_GET['param_2']);
}
if(isset($_GET['param_3'])){
$whereArr[]="column3=" . mysqli_real_escape_string($conn,$_GET['param_3']);
}
$whereStr='';
if(count($whereArr)>0){
$whereStr="WHERE " . implode(" AND ",$whereArr);
}
$sql = "SELECT column1 ,column2,column3,column4,column5
FROM xxx " . $whereStr;
$query = mysqli_query($conn, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>
Check for each param in the above demonstrated, Put them in array.
Then check if array is isset or not, if isset create a where string and the append it to your query.
Even if no param is set your query will run without where clause.
You can do something like this for optimization of your code,
$getArr = array_filter($_GET);
// checking sql injection
$getArr = array_map(function ($v) use ($conn) {
return mysqli_real_escape_string($conn, $v);
}, $getArr);
$temp = [];
// fetching numbers for that key
foreach ($getArr as $key => $value) {
$temp[$key] = preg_replace('/[^\d]/', '', $key);
}
$str = '';
// creating condition for data fetched in get
array_walk($temp, function ($item, $key) use (&$str, $getArr) {
$str .= " column$item = '" . $getArr[$key] . "' AND ";
});
// raw query
$sql = 'SELECT column1 ,column2,column3,column4,column5 FROM xxx';
// if not empty string
if (!empty($str)) {
$sql .= rtrim($str,'AND ');
}
echo $sql;die;

Load MySQL Data into Corresponding PHP Variables

I got this work for me, but I'm sure there's a better way to get this done. But, I've searched many hours without finding the exact answer to what I'm looking to do. Basically getting the variable usrID from the URL, I need to search MySQL for the corresponding information to this user. Later I want to use the different fields on my page (better website) to personalize the experience.
<?php
$servername = "localhost";
$username = "authorized-user";
$password = "secret";
$dbname = "agentDB";
$usrID = "001";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM agentInfo WHERE usrID = '$usrID'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$Lname = $row["Lname"];
$Fname = $row["Fname"];
$tl = $row["tl"];
}
}
mysqli_close($conn);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Load MySQL Data into Corresponding PHP Variables</title>
</head>
<body>
here is the body<br>
My name is: <?php echo $Fname; ?> <?php echo $Lname; ?><?php echo $tl; ?>
</body>
</html>
You could create a variable to store a full name and then "tl" on it like this:
$user_info = $Lname . ", " . $Fname . ": " . $tl;
Then:
<?php echo $user_info; ?>
Wherever you need that information.
If you want to minimize the amount of variables being assigned you could wrap it in a function and return the desired data field:
function fetchUserData(userData) {
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM agentInfo WHERE usrID = '$usrID'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$userData = $row[userData];
}
}
return $userData;
}
mysqli_close($conn);
You can the get the specified data like this:
<?php echo fetchUserData("Fname"); ?>

how mysql query written in php to get json format output [duplicate]

This question already has answers here:
JSON encode MySQL results
(16 answers)
Closed 6 years ago.
i have written code in php file that to connect to database and get the requested data .
<?php
// 1. Create a database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$dbname = "widget_corp";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
$subject = mysqli_fetch_assoc($result);
print_r($subject);
?>
i am getting the output in array format ,i want to get the out put in json format.how to change the code ,please help me .
You need to use php json_encode() method. Please check php doc for json_encode here
Use json_encode:
I suppose you're making API to return JSON string, make sure you return it as a JSON response instead of HTML. It's a good practice :)
To return JSON string as a JSON response, You can do the following.
<?php
header('Content-Type: application/json');
echo json_encode($subject);
?>
create a array or results and use json_encode.
$subject = array();
while($row = $result->fetch_assoc() ){
$subject[] = $row;
}
echo json_encode($subject);
You have to use json_encode($subject).
<?php
// 1. Create a database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$dbname = "widget_corp";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
$subject = mysqli_fetch_assoc($result);
if($subject)
{
$json_subject = json_encode($subject);
print_r($json_subject);
}
?>

Mysqli wont allow table's to show when called on

As of recently ive been learning php and at that conjuntion in between where i have to now use Mysql in order to keep my bigger info table ogranized, well i wrote this code in order to show the tables (or so i think i did it right). im completely stumped because i can not see any of the displaying tables that i am calling on and the more ive tried the less i works so i was wondering if anyone can see a loop hole in my code or maybe im doing something wrong? or maybe everything ive done is wrong...?
`
$dbhost = "localhost";
$dbuser = "juliegri_AAlassa";
$dbpass = "********"; // to not show real password
$dbname = "juliegri_AAlassaly";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno () . ")"
);
}
?>
<?php
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
if (!$result) {
die("Database query failed");
}
?>
<!doctype html>
<html lang="en">
<head>
<title>databases</title>
</head>
<body>
<ul>
<?php
while($subject = mysqli_fetch_assoc($result)) {
?>
<li><?php echo $subject["menu_name"] . "(" . $subject["id"] . ")"; ?></li>
<?php
}
?>
</ul>
<?php
mysqli_free_result($result);
?>
</body>
</html>
<?php
mysqli_close($connection);
?>`
Have you forgotten the opening PHP tag at the beginning of your page?
<?php
$dbhost = "localhost";
$dbuser = "juliegri_AAlassa";
$dbpass = "********"; // to not show real password
$dbname = "juliegri_AAlassaly";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno () . ")"
);
}
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
if (!$result) {
die("Database query failed");
}
?>
Two things i think could be wrong.
Here is a correct implementation to compare. It could be the first PHP opening tag, i also added the default port to the connect statement, and added some try catches with error messages, these can tell if the connect or query is not working.
<?php
$dbhost = "localhost";
$dbuser = "juliegri_AAlassa";
$dbpass = "********"; // to not show real password
$dbname = "juliegri_AAlassaly";
//original connect statement with a port added in
try {
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname , 3306);
} catch(Exception $e) { echo $e->getMessage(); }
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
//Query looks fine, easier to trouble shoot when its one line, first get it working then break it up
$query = "SELECT * FROM subjects WHERE visible = 1 ORDER BY position ASC";
// This will try to fetch the result and give an error if it can't.
try { $result = mysqli_query($connection, $query);
} catch(Exception $e) { echo $e->getMessage(); }
if (!$result) { die("Database query failed"); }
?>
Is it alright if I alter some of your codes?
See this:
<!doctype html>
<html lang="en">
<head>
<title>databases</title>
</head>
<body>
<?php
/* ESTABLISH CONNECTION */
$connection=mysqli_connect("localhost","juliegri_AAlassa","YourPassword","juliegri_Aalassaly");
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
/* START QUERY */
$result=mysqli_query($connection,"SELECT * FROM subjects WHERE visible='1' ORDER BY position ASC");
?>
<ul>
<?php
/* DO THE WHILE LOOP */
while($subject = mysqli_fetch_array($result)) {
?>
<li><?php echo $subject['menu_name'] . "(" . $subject['id'] . ")"; ?></li>
<?php
} /* END OF WHILE LOOP */
?>
</ul>
</body>
</html>

Getting data from MySQL table via Codeigniter

I'm having issues getting this data from within a codeigniter Controller.
$q = $this->db->get('offers_orders');
$this->db->select('total');
$this->db->where('order_number', $orderid);
$orderdata = $q->result_array();
$orderamount = $orderdata[0]['total'];
Do you see anything wrong with this code ?.
Yes, Try :
$this->db->select('count(*) as total', false);
$this->db->where('order_number', $orderid);
$q = $this->db->get('offers_orders');
OR,
$q = $this->db->select('count(*) as total', false)->where('order_number', $orderid)->get('offers_orders');
You need first to defined your select and where method then you call the get() method which are used for get data.
Like this:
$this->db->select('total');
$this->db->where('order_number', $orderid);
$q = $this->db->get('offers_orders');
And as I see from your query, you need to fetch only one result and for it better solution is to use row() function because this function returns a single result row.
Like this:
$orderdata = $q->row();
$orderamount = $orderdata->total;
Also to learn more about it you can read this acticle.
<!DOCTYPE html>
<html>
<body>
<?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 = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> id: ". $row["id"]. " - Name: ". $row["firstname"]. " " . $row["lastname"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</body>
</html>

Categories