i'm need help about sql query to select multiple table with multiple "or" condition. this is my database schema.
Hotel
id_hotel
id_state
id_city
hotel_name
State
id_state
state_name
City
id_city
city_name
thi is the query that i'm have been try, but result nothing.
$sql=mysqli_query($connection,"select * from hotel h, state s, city c where h.id_state=s.id_state and h.id_city=c.id_city and (h.hotel_name='$_GET[data]' or s.state_name='$_GET[data]' or c.city_name='$_GET[data]')");
I was try with that code.. and there is no result. Please help me guys.. tq
There are so many issues with your code that telling you and explaining everything you have to fix would take awhile, so I will list the basic and what you need to do.
You're not using any error handler at all, you should always use it while testing / developing, for instance MySQL error, code error and the such, which would have told you some of the issues you currently have.
You can read this page for more information on How to get useful error messages in php.
Continuing, you're using $_GET[data] inside double quotes which makes it loses its boundaries as you have not defined any for it, if you had any error handling it would have been pointed out.
You could have concatenated it " . $_GET['data'] . " or even used the curly brackets to define its boundaries like so {$_GET['data']}
You're injecting GET elements directly in your query without sanitizing it, which is a big mistake and a welcome to SQL injection.
All the above is based in the small portion of code you showed us and I am afraid to see the rest of it.
Here is a sample of how it would look like to use JOINs in your query along with parametized MySQLi.
<?php
// yes we want to see errors
ini_set('error_reporting', E_ALL);
// Your database info
$db_host = 'your database host address';
$db_user = 'your database username';
$db_pass = 'your database user password';
$db_name = 'your database name';
$con = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if ($con->connect_error)
{
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
}
$sql = "SELECT h.id_hotel,
h.hotel_name,
s.id_state,
s.state_name,
c.id_city,
c.city_name
FROM hotel h
JOIN state s
ON h.id_state = s.id_state
JOIN city c
ON h.id_city = c.id_city
WHERE h.hotel_name = ? OR
s.state_name = ? OR
c.city_name = ?";
if (!$result = $con->prepare($sql))
{
die('Query failed: (' . $con->errno . ') ' . $con->error);
}
if (!$result->bind_param('sss', $_GET['data'], $_GET['data'], $_GET['data']))
{
die('Binding parameters failed: (' . $result->errno . ') ' . $result->error);
}
if (!$result->execute())
{
die('Execute failed: (' . $result->errno . ') ' . $result->error);
}
$result->bind_result($hotel_id, $hotel_name, $state_id, $state_name, $city_id, $city_name);
while ($result->fetch())
{
echo $hotel_id, " - ", $hotel_name, " - ", $state_id, " - ", $state_name, " - ", $city_id, " - ", $city_name, "\n";
}
$result->close();
$con->close();
More about bind_result, click me...
More about bind_param, click me...
Related
can it be combine into 1 query?
this is the query that im trying to combine? or is there a better way to relate these to table?
$insert_row = $mysqli->query("INSERT INTO orderlist
(TransactionID,ItemName,ItemNumber, ItemAmount,ItemQTY)
VALUES ('$transactionID','$itemname','$itemnumber', $ItemTotalPrice,'$itemqty')");
$insert_row1 = $mysqli->query("INSERT INTO order
(BuyerName,BuyerEmail,TransactionID)
VALUES ('$buyerName','$buyerEmail','$transactionID')");
when i run these both only one query is functional, so what im trying to do is to make them both works.
im open to any suggestion
The reason why your second query isn't working is because of the use of order and not escaping it; it is a MySQL reserved word:
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
Sidenote: ORDER is used when performing a SELECT... ORDER BY...
https://dev.mysql.com/doc/refman/5.0/en/select.html
Checking for errors would have shown you the syntax error such as:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax near 'order
http://php.net/manual/en/mysqli.error.php
Therefore, wrap it in ticks:
$insert_row1 = $mysqli->query("INSERT INTO `order` ...
or rename your table to something other than a reserved word, say orders for example.
If you wish to combine both queries, you can use multi_query()
http://php.net/manual/en/mysqli.quickstart.multiple-statement.php
Example from the manual:
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
$sql = "SELECT COUNT(*) AS _num FROM test; ";
$sql.= "INSERT INTO test(id) VALUES (1); ";
$sql.= "SELECT COUNT(*) AS _num FROM test; ";
if (!$mysqli->multi_query($sql)) {
echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
do {
if ($res = $mysqli->store_result()) {
var_dump($res->fetch_all(MYSQLI_ASSOC));
$res->free();
}
} while ($mysqli->more_results() && $mysqli->next_result());
?>
I also need to point out that your present code may be open to SQL injection since I do not know if you are escaping your data.
If not, then use prepared statements, or PDO with prepared statements, they're much safer.
try to add IF statement.
if ($insert_row = $mysqli->query("INSERT INTO orderlist(TransactionID,ItemName,ItemNumber, ItemAmount,ItemQTY)VALUES ('$transactionID','$itemname','$itemnumber', $ItemTotalPrice,'$itemqty')"));
{
$insert_row1 = $mysqli->query("INSERT INTO order (BuyerName,BuyerEmail,TransactionID) VALUES ('$buyerName','$buyerEmail','$transactionID')");
}
so i have this php code :
session_start();
$servername = "localhost";
$username = "root";
$dbname = "3890ask3_db";
$con = mysql_connect($servername, $username, "", $dbname)
or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db($dbname,$con)
or die("Failed to connect to MySQL: " . mysql_error());
$query = mysql_query("SELECT * FROM register where Username = '$_SESSION[Username]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
if(isset($_GET['selecttoy']))
{
$clname=$row['Name'];
$clsurname=$row['Surname'];
$clemail=$row['Email'];
$stoy=$_GET['selecttoy'];
$query2 = "INSERT INTO order (ClName, ClSurname, ClEmail, ToyCode , OrderID) VALUES ('$clname', '$clsurname', '$clemail' , '$stoy', ' ' )" ;
if (mysql_query($query2)) {
echo "Order created successfully!";
} else {
echo "Error: " . "<br>" . mysql_error($con);
}
}
?>
The php page can actually read the get variable,but as soon as i try to insert something in the database, i get this error message:
"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 'order (ClName, ClSurname, ClEmail, ToyCode , OrderID) VALUES ('mar', 'kyr', 'dgg' at line 1"
i tried everything but no result...can someone please help me?
thanks in advance....
You can not use order directly because it's reserved word. try to enclose it in (``). Like below:-
$query2 = "INSERT INTO `order` (ClName, ClSurname, ClEmail, ToyCode , OrderID) VALUES ('$clname', '$clsurname', '$clemail' , '$stoy', ' ' )" ;
Note:- Try to add sql error reporting code always.
stop using mysql_*, use mysqli_* or PDO.
your above code is open for SQL Injection. thanks.
This question already has answers here:
In PHP/MySQL should I open multiple database connections or share 1?
(6 answers)
Closed 18 days ago.
Is it better/secure to create a separate DB connection for each query (sample1) or should I just make one DB connection for both (sample2) ?
I have 2 queries to make to a database.
Select (to check if email exists in table).
Insert (if email does not exist create record in table).
I'm mainly interested in the security and resource cost of one method over the other.
NOTE: the sample code below is a simplified version of a user registration code.
Sample 1.
<?php
$NEW_EMAIL="sample#gmail.com";
$prep_sel = 'SELECT email FROM users WHERE email=?';
$link1 = mysqli_stmt_init($dbc);
if (mysqli_stmt_prepare($link1, $prep_sel)) {
mysqli_stmt_bind_param($link1, 's', $e);
mysqli_stmt_execute($link1);
mysqli_stmt_store_result($link1);
}
// If record does not exist, then insert it.
if (mysqli_stmt_num_rows($link1) == 0) { // Available.
$prep_ins= 'INSERT INTO users (email) VALUES (?)';
$link2 = mysqli_stmt_init($dbc);
if (mysqli_stmt_prepare($link2, $prep_ins)) {
mysqli_stmt_bind_param($link2, 'sssss', $NEW_EMAIL);
mysqli_stmt_execute($link2);
}
}
?>
Sample 2.
<?php
$NEW_EMAIL="sample#gmail.com";
$prep_sel = 'SELECT email FROM users WHERE email=?';
$link1 = mysqli_stmt_init($dbc);
if (mysqli_stmt_prepare($link1, $prep_sel)) {
mysqli_stmt_bind_param($link1, 's', $e);
mysqli_stmt_execute($link1);
mysqli_stmt_store_result($link1);
}
// If record does not exist, then insert it.
if (mysqli_stmt_num_rows($link1) == 0) { // Available.
$prep_ins= 'INSERT INTO users (email) VALUES (?)';
if (mysqli_stmt_prepare($link1, $prep_ins)) {
mysqli_stmt_bind_param($link1, 'sssss', $NEW_EMAIL);
mysqli_stmt_execute($link1);
}
}
?>
Is there a sample 3 option? If you change your email column in your database to be UNIQUE that means no duplicated emails will be allowed. See below table sample:
CREATE TABLE users
(
id int auto_increment primary key,
email varchar(20) unique
);
And if you try to register a new account that already uses that given email you will be given an error 1062 (aka Duplicate entry error).
So instead of running both, a SELECT and a INSERT query based on that, you could simple run the INSERT query given your email column is UNIQUE:
<?php
// Your database info
$db_host = 'xxxx';
$db_user = 'xxxx';
$db_pass = 'xxxx';
$db_name = 'xxxx';
// hardcoded email for testing purposes
$test_email ="sample#gmail.com";
// SQL query
$sql = 'INSERT INTO users (email) VALUES (?)';
// connect to database
$con = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if ($con->connect_error)
{
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
}
// Prepare the query to make sure it is good to go
if (!$result = $con->prepare($sql))
{
die('Query failed: (' . $con->errno . ') ' . $con->error);
}
// bind and test if the parameters are valid
if (!$result->bind_param('s', $test_email))
{
die('Binding parameters failed: (' . $result->errno . ') ' . $result->error);
}
// execute and see if it executed as expected.
if (!$result->execute())
{
if ($result->errno === 1062)
{
die("Email already in use...");
}
else
{
die('Execute failed: (' . $result->errno . ') ' . $result->error);
}
}
else
{
echo "account created!!";
}
In regards whether its better to have a single connection or multiple connections, this is a very good reading but as a resume you could reference your self to In PHP/MySQL should I open multiple database connections or share 1?
Trying to make a prepare statement but for some reason it fails me and i'm getting errno 0 with error (text) being blank. What is causing this? Have been searching the web for a quite while now.
<?php
$dbh = new mysqli("localhost","root","","honeypot");
if ($dbh->connect_errno) {
echo "Connection failed: (" . $dbh->connect_errno . ") " . $dbh->connect_error;
die();
}
//Prepare
if (!($stmt = $dbh->prepare("SELECT tblUsers WHERE UserName = ?"))) {
echo "Prepare failed: (" . $dbh->connect_errno . ") " . $dbh->connect_error;
}
?>
You're getting error 0 because you're printing $dbh->connect_error, but you didn't have an error making the connection. For everything other than the initial connection you should use $dbh->error.
echo "Prepare failed: (" . $dbh->errno . ") " . $dbh->error;
You're getting an error because your query has a syntax error. It should be:
SELECT col1, col2, col3, ... FROM tblUsers WHERE UserName = ?
You're missing the list of columns and the FROM keyword.
I've been all up and down StackExchange, and much of the internet's cornucopia of lesser sites, looking for any good reason my code doesn't work, but this one has me stumped. I'd like to display the total number of rows in a particular MySQL table, and set the count as a variable, to use later in the script. When I run the following, the script dies, and I get a PHP warning, telling me that mysql_result() expects parameter 1 to be resource, string given.
$conn = mysql_connect('mysql_server', 'username', 'password');
if (!$conn) {
die('Connect Error ' . mysql_error());
}
mysql_select_db('my_database', $conn);
if (!mysql_select_db('my_database')) {
die('Could not select database: ' . mysql_error());
}
$max_count_query = ("SELECT COUNT(*) FROM table");
// Perform Query
$max_count_action = mysql_query($max_count_query);
$mcount = mysql_result($max_count_action, 0, 0);
printf("\nNumber of Records to Process: ", $mcount);
What does the collective genius of StackOverflow think?
In response to the comments, I have another mini-slab of code to offer:
$conn = mysql_connect('127.0.0.1', 'username', 'password');
if (!$conn) {
die('Connect Error ' . mysql_error());
}
mysql_select_db('my_database', $conn);
if (!mysql_select_db('my_database')) {
die('Could not select database: ' . mysql_error());
}
$max_count_query = ("SELECT COUNT(*) FROM directory_nap");
// Perform Query
$max_count_action = mysql_query($max_count_query);
if (!$max_count_action){
die('mysql query error: ' . mysql_error());
}
$mcount = mysql_result($max_count_action, 0, 0);
if (!$mcount){
die('mysql result error: ' . mysql_error());
}
printf("\nNumber of Records to Process: ", $mcount);
Provided the table tablename is just a sample (see answer by bitfox), there's nothing wrong with your code. I can use the same code on my test server and get results by changing the table name to one that I know exists in my own db.
What is most troubling, however, is that you indicate the error says mysql_result() expects parameter 1 to be resource, string given -- if your SQL has an error, mysql_query returns boolean (docs), not a string. So, you're either not showing the same test code as you're actually using, or you've given us an inaccurate error message.
At some point, you must be assigning a string into the variable $max_count_action. Here's what I get when I send a query with an intentional problem: Warning: mysql_result() expects parameter 1 to be resource, boolean given -- note "boolean", not string.
So, I think your first step is to choose a different table name. That said, if you're using a reserved word as a table or column name you can still access it by surrounding the string in the backtick (`) character:
SELECT COUNT(*) FROM `table`
Second step is to see what's happening to $max_count_action to turn it into a string. Finally, use mysql_error consistently to debug, I would suggest doing something a little nicer with it than die for production code, however.
// working code on my test server
$max_count_query = ("SELECT COUNT(*) FROM users");
$max_count_action = mysql_query($max_count_query);
$mcount = $max_count_action ? mysql_result($max_count_action, 0) : 'Error: '.mysql_error();
print "\nNumber of Records to Process: ". $mcount;
it's very likely that the error is here:
SELECT COUNT(*) FROM table
"table" is a reserved word of SQL language. You should change it.
The cause of the problem is not clear from the code sample (it could be a wrong table name, the parentheses around the query string, and so on), however there are a number of inaccuracies in it. You can try the following code, it should at least fix a couple side bugs and give you more details on the error:
$conn = mysql_connect('mysql_server', 'username', 'password');
if ($conn === false) {
die('Connect Error ' . mysql_error($conn));
}
if (mysql_select_db('my_database', $conn) === false) {
die('Could not select database: ' . mysql_error($conn));
}
$max_count_query = "SELECT COUNT(*) FROM table";
// Perform Query
$max_count_action = mysql_query($max_count_query, $conn);
if($max_count_action === false) {
die('Query error ' . mysql_error($conn));
}
$mcount = mysql_result($max_count_action, 0, 0);
if($mcount === false) {
die('Result retrieval error ' . mysql_error($conn));
}
printf("\nNumber of Records to Process: %s", $mcount);
mysql_free_result($max_count_action);
Hope this helps, bye!
Is the 'table' in your question a placeholder or a real name in your code? Try to change another name of your 'table' table, otherwise I would like to try mysql_fetch_array instead of mysql_result
$max_count_query = "SELECT COUNT(*) FROM t";
// Perform Query
$max_count_action = mysql_query($max_count_query) or die (mysql_error());
$mcount = mysql_fetch_array($max_count_action);
printf("\nNumber of Records to Process: ", $mcount[0]);
$conn = mysql_connect('mysql_server', 'username', 'password');
if (!$conn) {
die('Connect Error ' . mysql_error());
}
This is OK, but the connect and coditional don't need to be split across 2 lines
mysql_select_db('my_database', $conn);
Again, this is questionable. If you're using multiple databases then referencing databases in your SQL is much simpler and safer than tracking state within your PHP code.
if (!mysql_select_db('my_database')) {
die('Could not select database: ' . mysql_error());
}
Haven't you already done that?
$max_count_query = ("SELECT COUNT(*) FROM table");
Why the brackets?
// Perform Query
Isn't that obvious from the code?
$max_count_action = mysql_query($max_count_query);
$mcount = mysql_result($max_count_action, 0, 0);
It would be neater to pass the db handle to the mysql_query call.
You checked for an error after connecting, you checked for an error after switching database, but you don't check for an error after mysql_query() ?
printf("\nNumber of Records to Process: ", $mcount);
There is no placeholder in the format string for the mcount argument.Try:
printf("\nNumber of Records to Process: %d", $mcount);
I get a PHP warning, telling me that mysql_result() expects parameter 1 to be resource, string given.
Then the code you are running is not the code you've shown us; mysql_query() will not return a string.