i building simple WebService for my web app which contain only two php files connecttodatabase.php contain the code of mysql connection and index.php contain the code of my webService but i got sql error:
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 'desc, cat, price FROM itmes' at line 3
connecttodatabase.php
<?php
$requesturi = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$pos = strpos($requesturi, "localhost:99/self/index.php");
$hostname = "localhost";
$database = "self";
$username = "root";
$password = "";
$self = mysql_pconnect($hostname, $username, $password) or trigger_error(mysql_error(),E_USER_ERROR);
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
//get data
require_once('connecttodatabase.php');
mysql_select_db($database, $self);
//build query
$query =
"SELECT
name,
desc,
cat,
price
FROM itmes";
$rsPackages = mysql_query($query, $self) or
die(mysql_error());
$arRows = array();
while ($row_rsPackages = mysql_fetch_assoc($rsPackages)) {
array_push($arRows, $row_rsPackages);
}
header('Content-type: application/json');
echo json_encode($arRows);
?>
</body>
</html>
It is because you used command DESC in selection, which throws an Exception. Use special symbols to prevent these problems:
`something`
So your code will have this form:
$query =
"SELECT
`name`,
`desc`,
`cat`,
`price`
FROM `itmes`";
and it should be working.
Related
This question already has answers here:
How to secure database passwords in PHP?
(17 answers)
Closed 2 years ago.
I have a main page on my site and I am trying to make a connection to the MySQL server and get some data from the database.
But the problem is that when I want to establish a connection I have to put the username and password in the page which doesn't seem wise to me.
I added a part of my code related to this problem.
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<?php
$host = "localhost";
$userName = "username";
$password = "12345678";
$dbName = "MyDB";
$connection = new mysqli($host , $userName , $password , $dbName);
if ($connection->connect_error) {
die("Connection failed due to this error : " . $connection->connect_error . '<br>');
}
else{
echo "Connected successfully";
{
</body>
</html>
Put your connection code into another file, like connection.php and in every page you want to connect you should require_once "connection.php", also you could use variables from that file if you connect it, also instead of require_once you can use just require, but look at the internet differences between them
Normal practice is to put the mysql data in a separate php file. For example:
dbmain.php
<?php
$host = "localhost";
$userName = "username";
$password = "12345678";
$dbName = "MyDB";
$connection = new mysqli($host , $userName , $password , $dbName);
?>
then you can include this file in all php files which require db connection.
<?php include_once("dbmain.php"); ?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<?php
/// php commands, such as
//if ($result = $mysqli -> query("SELECT * FROM dbtable1")) {
// echo "Returned rows are: " . $result -> num_rows;
// Free result set
// $result -> free_result();
//}
//$mysqli -> close();
?>
</body>
</html>
I get this error when trying to get this details page for a project to work. Its for school and I dont really understand PHP that well yet.
"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 '' at line 1"
Here is the code for that page.
<?php
require_once('connection.php');
mysqli_select_db($conn, $dbname);
$recordID = $_GET['recordID'];
$query_Shoe_Details = "SELECT * FROM Products WHERE Shoe_Brand = $recordID";
$Shoe_Details = mysqli_query($conn, $query_Shoe_Details) or die(mysqli_error(($conn)));
$row_Shoe_Details= mysqli_fetch_assoc($Shoe_Details);
$totalRows_Shoe_Details = mysqli_num_rows($Shoe_Details);
?>
<!DOCTYPE html>
<html>
<head>
<title>details</title><?php include 'connection.php';?>
</head>
<body>
<p>Product Name: <?php echo $row_Shoe_Details['Product_Name']; ?></p>
<p><img src=
"images/%3C?php%20echo%20$row_Shoe_Details['Image_Name'];%20?%3E"></p>
<p>Description: <?php echo $row_Shoe_Details['Product_Description']; ?></p>
<p>Price: $<?php echo $row_Shoe_Details['Product_Price']; ?></p><?php
mysqli_free_result($Shoe_Details);
?>
</body>
</html>
change your query as, use single quotes
$query_Shoe_Details = "SELECT * FROM Products WHERE Shoe_Brand = '$recordID'";
Also remove this <?php include 'connection.php';?>, No need to include again
Pl. prepare connection.php file in followng way like
$dbHost = '';
$dbUser = '';
$dbPass = '';
$dbName = '';
// setting up the web root and server root for
// this shopping cart application
$con=mysql_connect('','','');
if(!$con)
{
die('connection failed');
}
$db=mysql_select_db('',$con);
if(!$db)
{
die('db is not selected');
}
pass proper value in this syntax save it and in your code remove second line and test then and give feedback
I'm new at creating login scripts with php and MySQL and was hoping for some help. I've already gotten the basics down for actually checking that the entered information is correct and I've gotten the sessions to work correctly. However, I'm having trouble getting the user's info to pull from his/her row and displaying on the membership page. Do I need to do another query and add a while loop within this page to collect the information? Here are the scripts:
login.php
$p_num = "";
$pwd = "";
$errors = "";
$num_rows = 0;
$user_id = "";
$user_name = "";
$password = "";
$image = "";
$user_email = "";
$program = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
include("database.php");
$p_num = $_POST["username"];
$pwd = $_POST["password"];
$query = "SELECT * FROM $user_table WHERE user_id = '$p_num' AND password = '$pwd'";
$result = mysqli_query($connect, $query);
$num_rows = mysqli_num_rows($result);
if($result){
echo "There is/are " .$num_rows ." set(s) in the database with this info.<br>";
if($num_rows > 0){
session_start();
$_SESSION["login"] = 1;
header("Location: ../pages/instructor.php");
}
else{
echo "Unable to login";
}
}
}
instructor.php
<!DOCTYPE html>
<?php
include("../php/login.php");
include("../php/database.php");
?>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<link href="../css/style.css" rel="stylesheet/less" type="text/css">
<script src="../js/jquery.2.0.3.js"></script>
<script src="../js/script.js"></script>
<script src="../js/less-1.7.4.min.js"></script>
</head>
<body>
<div id="page">
<header>
<div id="logo" class="logo_bg"></div>
<div id="fsi_logo" class="logo_bg"></div>
</header>
<div id="main">
<?php
session_start();
if(isset($_SESSION["login"])){
echo "Hello";
}
?>
<div id="bleg">
<h1>BUILD SCENARIO</h1>
<h1>SEARCH SCENARIOS</h1>
<h1>VIEW SCENARIOS</h1>
</div>
</div>
<footer>Copyright© 2014 FlightSafety International</footer>
</div>
</body>
</html>
database.php
$db = "spartan";
$host = "localhost";
$user = "root";
$password = "";
$connect = mysqli_connect($host, $user, $password) or die(mysqli_error($connect));
$user_table = "users";
$user_info = "user_info";
$create_db_spartan = "CREATE DATABASE IF NOT EXISTS $db";
$create_table_users = "CREATE TABLE IF NOT EXISTS $user_table(user_id VARCHAR(10) NOT NULL, user_name VARCHAR(100), password VARCHAR(16), PRIMARY KEY(user_id))";
$create_table_users_info = "CREATE TABLE IF NOT EXISTS $user_info(user_id VARCHAR(10) NOT NULL, user_name VARCHAR(100), email VARCHAR(50), program VARCHAR(4), PRIMARY KEY(user_name))";
mysqli_query($connect, $create_db_spartan) or die(mysqli_error($connect));
mysqli_select_db($connect, $db) or die(mysqli_error($connect));
mysqli_query($connect, $create_table_users) or die(mysqli_error($connect));
mysqli_query($connect, $create_table_users_info) or die(mysqli_error($connect));
Just as an FYI, I am not concerned with SQL Injection at this point in time, this isn't something that's been released and it's on an internal network. Thanks in advance.
In both of your scripts, session_start() is issued after data has been sent to the browser. This means that the opportunity for setting headers has passed, and so session cookies cannot be set. Thus, sessions will not work.
In both cases, put this command at the top of your script, or at least before the opening DOCTYPE. Your sessions should then start working.
Similarly, your header('Location: X') needs to be used prior to output being sent, otherwise the redirect will not work. However this appears just after an echo and the output of the DOCTYPE. Remove the echo and then edit the start of your instructor.php file thus:
<?php
include("../php/login.php");
include("../php/database.php");
?>
<!DOCTYPE html>
Here the output of the DOCTYPE should not happen until the loading of files and initialisation is complete. If there is any cookies/sessions/redirects to do, they can be done here.
All of these 'headers already sent' issues should raise a warning. If you are not seeing this in your development environment, you may have on-screen errors disabled - make sure they are turned on.
I'm getting the error: No database selected
Here is the code:
<?php
$host = "localhost";
$user = "root";
$password = "";
$database_name = "Student";
mysql_connect($host, $user, $password);
mysql_select_db($database_name);
?>
This code is for php-connect.php class and for the form:
<!DOCTYPE html>
<html>
<body>
<?php
//load database connection
include("php-connect.php");
$id = "1";
$name = "Elena";
$city = "Lahore";
//Command to insert into table
$query = "INSERT INTO studentdata (id,name,city) VALUES ('$id','$name','$city')";
//run the query to insert the person.
$result = mysql_query($query) OR die(mysql_error());
//let them know the person has been added.
echo "Data successfully inserted into the database table ... ";
?>
</body>
</html>
This is the code for the form.. I've tried a lot of things to fix this error but it does not work. Is there any problem with my database?
Try this...
<?php
$host = "localhost";
$user = "root";
$password = "";
$database_name = "Student";
$mLink = mysql_connect($host, $user, $password) or die(mysql_error());
mysql_select_db($database_name , $mLink);
another file
<?php
require 'php-connect.php';
//...... etc..
but, read this first:
This extension is deprecated as of PHP 5.5.0, and will be removed in
the future. Instead, the MySQLi or PDO_MySQL extension should be used.
See also MySQL: choosing an API guide and related FAQ for more
information. Alternatives to this function include:
mysqli_select_db()
PDO::__construct() (part of dsn)
http://br.php.net/mysql_select_db
I have a form with PHP that saves a variable to a MySQL database. That form worked on a VPS, but when trying it on another VPS it gives an error when trying to write to the database when the field contains a ' character. So the same PHP code works on 1 VPS when the field contains a ' character, but not on the other VPS.
Here it works: http://www.zoekmachineoptimalisatie.us/test.php
and here (it's the other VPS) it gives an error: http://www.onzebruidsfotograaf.nl/test.php
My form:
<?php
$hostname = "localhost"; //host name
$dbname = "xxxxxxxx"; //database name
$username = "xxxxxxxx"; //username you use to login to php my admin
$password = "xxxxxxxx"; //password you use to login
$conn = new MySQLi($hostname, $username, $password, $dbname);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Untitled Document</title>
</head>
<body>
<?php
if (isset($_POST['Submit'])) { //if the submit button is clicked
$title = $_POST['updatetitle'];
$bookid = 1;
$update = "UPDATE test SET Title='$title' WHERE BookID = " . $bookid;
$conn->query($update) or die("Cannot update"); //update or error
}
?>
<?php
$bookid = 1;
$sql = "SELECT * FROM test WHERE BookID = '" . $bookid . "'";
$result = $conn->query($sql) or die(mysql_error());
$query = getenv(QUERY_STRING);
parse_str($query);
?>
<h2>Update Record <?php echo $bookid;?></h2>
<form action="" method="post">
<?php
while ($row = $result->fetch_assoc()) {
?>
<textarea name="updatetitle" cols="100" rows="30"><?php echo $row['Title']; ?></textarea>
<table border="0" cellspacing="10">
<tr>
<td><INPUT TYPE="Submit" VALUE="Update the Record" NAME="Submit"></td>
</tr>
</table>
<?php
}
?>
</form>
<?php
if ($update) { //if the update worked
echo "<b>Update successful!</b>";
}
?>
</body>
</html>
An unescaped quote in your query will produce a syntax error. Instead of building the SQL fully your own, make use of SQL variables for your PHP variables with a Prepared Statement:
if (isset($_POST['Submit'])) { //if the submit button is clicked
$title = $_POST['updatetitle'];
$bookid = 1;
$update = $conn->prepare('UPDATE test SET Title = ? WHERE BookID = ?;');
$update->bind_param('sd', $title, $bookid);
$update->execute();
}
One of your servers has Magic Quotes enabled and the other doesn't. Magic Quotes is now considered undesirable and is deprecated, it automatically escapes input. You should turn off Magic Quotes and use a parameterised query/prepared statement instead - then there is no need to escape anything and it prevents SQL Injection.
Paramterised queries are supported by the MySQLi and PDO APIs.
because the single quote breaks the query statement. In order to prevent from it or from SQL Injection you need to use PDO or MySQLI extension. For more infor, see the article below
How can I prevent SQL injection in PHP?