I have a table structure like this:
sender| receiver| message|date|time
----------------------------------
How do I select all the messages written on the same date, with them appearing at the top, just like Facebook Chat?
I've tried something like this:
<?php
$con=mysql_connect("localhost","root","");
$db=mysql_select_db ("chat",$con);
$query=" select * from chat where sender='$send'
and receiver='$rec' order by date";
$result=mysql_query($query);
while($r2=mysql_fetch_array($result))
echo "<div>{$r2['date']}</div>";
{
echo"<div>{$r2['message']}</div>";
}
?>
You're trying to run an SQL query directly from PHP, which you can't do - you'll need to connect to your database first. Then you need to pass the $send and $rec variables to your database, preferably through prepared statements to prevent SQL injection.
It depends on whether you're using MySQLi or PDO as to exactly how you should do that, but I'll assume you're not using the mysql_ constructor, as that was deprecated as of PHP 5.5, and is removed in PHP 7.
As such, here's an example of how to do this through MySQLi with prepared statements:
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
$stmt = $mysqli->prepare(
"SELECT * FROM tablename WHERE sender = ? && receiver = ?");
$stmt->bind_param("ss", $send, $rec);
// "ss' is a format string, each "s" means string
// Each variable gets passed to the question marks, in order
$stmt->execute();
$stmt->bind_result($result);
You then have the results stored in $result, and are free to manipulate from there.
Hope this helps! :)
Related
This is my first time to try PDO and still learning it. I am more familiar in using mysql or mysqli in developing php system.
After deep searching and searching I still can't seem to understand how to query using PDO
In my code I used mysqli inside a function to be called in index.php
function getUsery(){
$ip = getIPAddress();
$query = mysqli_query("select userID from tblUsers where logged='1' AND ip='$ip'");
$row = mysqli_fetch_array($query);
$emp = $row['userID'];
$logged = $row['logged'];
$userlvl = $row['userLevel'];
$_SESSION['logged'] = $logged;
$_SESSION['userLevel'] = $userlvl;
return $emp;
}
I don't really know how to select sql query using PDO with 'where' statement. Most of what I found is using array with no 'where' statement
How can I select the userID where logged is equal to '1' and ip is equal to the computer's ip address and return and display the result to the index.php
There's SQL statement with WHERE in PDO
$sql = "SELECT * FROM Users
WHERE userID = ?";
$result = $pdo->prepare($sql);
$result->execute([$id]);
Assuming that you know how to connect database using PDO, here is how to select SQL with PDO.
$stmt = $db->prepare("select userID from tblUsers where logged = '1' AND ip = :ip");
$stmt->execute(array('ip' => $ip));
$listArray = $stmt->fetchAll();
Notice the :ip at the end of SELECT. If you don't use ? as a parameters, the prefix : is mandatory and the word after that should be the same as the key in the execute function.
EDIT
In case that the above code is inside the function and $db is outside the function, declare $db as global variable inside the function.
This one is imo one of best guides on PDO and how to use it:
https://phpdelusions.net/pdo
WHERE is a part of query and queries in PDO are not much different from pure *sql queries, just there is going on a bit filtering on execution. Read the guide carefully and you will be able to execute any query you need to.
I'm having some trouble using a variable declared in PHP with an SQL query. I have used the resources at How to include a PHP variable inside a MySQL insert statement but have had no luck with them. I realize this is prone to SQL injection and if someone wants to show me how to protect against that, I will gladly implement that. (I think by using mysql_real_escape_string but that may be deprecated?)
<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'hospital_name' AND value = '$q'";
$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
echo $row['value'];
}
?>
I have tried switching '$q' with $q and that doesn't work. If I substitute the hospital name directly into the query, the SQL query and PHP output code works so I know that's not the problem unless for some reason it uses different logic with a variable when connecting to the database and executing the query.
Thank you in advance.
Edit: I'll go ahead and post more of my actual code instead of just the problem areas since unfortunately none of the answers provided have worked. I am trying to print out a "Case ID" that is the primary key tied to a patient. I am using a REDCap clinical database and their table structure is a little different than normal relational databases. My code is as follows:
<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'case_id' AND record in (SELECT distinct record FROM database.table WHERE field_name = 'hospital_name' AND value = '$q')";
$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
echo $row['value'];
}
?>
I have tried substituting $q with '$q' and '".$q."' and none of those print out the case_id that I need. I also tried using the mysqli_stmt_* functions but they printed nothing but blank as well. Our server uses PHP version 5.3.3 if that is helpful.
Thanks again.
Do it like so
<?php
$q = 'mercy_west';
$query = "SELECT col1,col2,col3,col4 FROM database.table WHERE field_name = 'hospital_name' AND value = ?";
if($stmt = $db->query($query)){
$stmt->bind_param("s",$q); // s is for string, i for integer, number of these must match your ? marks in query. Then variable you're binding is the $q, Must match number of ? as well
$stmt->execute();
$stmt->bind_result($col1,$col2,$col3,$col4); // Can initialize these above with $col1 = "", but these bind what you're selecting. If you select 5 times, must have 5 variables, and they go in in order. select id,name, bind_result($id,name)
$stmt->store_result();
while($stmt->fetch()){ // fetch the results
echo $col1;
}
$stmt->close();
}
?>
Yes mysql_real_escape_string() is deprecated.
One solution, as hinted by answers like this one in that post you included a link to, is to use prepared statements. MySQLi and PDO both support binding parameters with prepared statements.
To continue using the mysqli_* functions, use:
mysqli_prepare() to get a prepared statement
mysqli_stmt_bind_param() to bind the parameter (e.g. for the WHERE condition value='$q')
mysqli_stmt_execute() to execute the statement
mysqli_stmt_bind_result() to send the output to a variable.
<?php
$q = 'Hospital_Name';
$query = "SELECT value FROM database.table WHERE field_name = 'hospital_name' AND value = ?";
$statement = mysqli_prepare($conn, $query);
//Bind parameter for $q; substituted for first ? in $query
//first parameter: 's' -> string
mysqli_stmt_bind_param($statement, 's', $q);
//execute the statement
mysqli_stmt_execute($statement);
//bind an output variable
mysqli_stmt_bind_result($stmt, $value);
while ( mysqli_stmt_fetch($stmt)) {
echo $value; //print the value from each returned row
}
If you consider using PDO, look at bindparam(). You will need to determine the parameters for the PDO constructor but then can use it to get prepared statements with the prepare() method.
My question supposed to be simple! although, I couldn't find the correct answer!
I need to retrieve the "hashed password" for the giving "username" from mySql database with php, then I need to store it in a variable, how could I do that?
All what I get is "Resource id #5"!
This is my code:
$query = "SELECT hashed_password ";
$query .= "FROM users ";
$query .= "WHERE username = '{$username}' ";
$query .= "AND hashed_password = '{$hashed_password}' ";
$query .= "LIMIT 1";
$result_set = mysql_query($query);
echo "$result_set";
echo '</br>';
To start off, let's use a MySQL library that supports prepared statements - otherwise, we'll run into SQL Injection issues in the future. Now, back to the actual question / answer.
If we use MySQLi, we have a few functions that will help us. Here's an example of an answer to your question w/ code comments to help walk through it:
// create our db connection
$mysqli = new mysqli('localhost', 'db_username', 'db_password', 'db_table');
// create a Prepared Statement to query to db
$stmt = $mysqli->prepare('SELECT hashed_password FROM users WHERE username = ? LIMIT 1');
// dynamically bind the supplied "username" value
$stmt->bind_param('s', $username);
// execute the query
$stmt->execute();
// get the first result and store the first column in the `$hashed_password` variable
$stmt->bind_result($hashed_password);
$stmt->fetch();
// close our Prepared Statement and the db connection
$stmt->close();
$mysqli->close();
echo $hashed_password;
Check out the PHP Doc for mysqli::prepare() for more examples =]
Note: I highly recommend avoiding the mysql_query() (and family) functions. They are not only deprecated, but they are quite insecure to use.
You need to fetch the data out of the mysql-resource that is returned by a query.
Just pass it through mysql_fetch_assoc($result_set). It will return your data in a nice and ordered arraay, moving ahead one row every call.
Meaning you can do
while ($row = mysql_fetch_assoc($result_set).
Also, please use mysqli. Its basically the same just with mysqli instead of mysql in commands. See the docs here for more info: http://php.net/manual/en/book.mysqli.php
Okay so i am new to PDO statements so i am unsure if i have done a syntax error or whatnot. The php file does not show any errors:
<?php
include('db_config.php');
$itemName = 'Item1';
$sql = "SELECT * FROM order WHERE itemName = $itemName;";
$stmt = $conn->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo $row['itemName'];
}
?>
My objective is to pull an item using bootstraps datepicker, but for the purpose of this testing i am using the itemName.
The php file comes up blank?
I have checked the field names, db_config, and am unsure where the issue is coming from.
Please let me know if i have done an error in my statement or anything that seems wrong.
Firstly, you're using a MySQL reserved word, being order and it requires special attention; mainly using ticks around it.
Then since we're dealing with a string, $itemName needs to be wrapped in quotes.
<?php
include('db_config.php');
$itemName = 'Item1';
$sql = "SELECT * FROM `order` WHERE itemName = '$itemName';";
$stmt = $conn->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo $row['itemName'];
}
?>
Either use ticks around your table name, or rename it to "orders", it's not a reserved keyword.
"The php file does not show any errors:"
That's because you're not checking for them.
Add $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); right after the connection is opened.
Now, if you're going to use PDO, use PDO with prepared statements, they're much safer.
As per a comment you left under your question containing the MySQL error:
1064 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
Read it near 'order it starts at "order".
Now, if ever your query should ever contain any character that MySQL will complain about, such as a quote etc. then you will need to escape your query and use prepared statements.
For example, if using:
$itemName = "Timmy's Sour Dough";
would translate to
WHERE itemName = 'Timmy's Sour Dough'
in turn throwing a syntax error.
So, it's best to immediately escape any data right away.
Edit
Your use of prepare and new to PDO collectively suggest that you are already trying to use prepared statements, just not the right way. You're just a little off from a well prepared statement. One correct way in your code would be
$sql = "SELECT * FROM `order` WHERE itemName = ? ";
$stmt = $conn->prepare($sql);
$stmt->execute(array($itemName));
Notice how we have a ? in your query then we are sending a value for it in your execute call. There you go :)
Using PDO with prepared statements will take care of that.
You're completely ignoring the main reason people use PDO. Prepared statements are what you should be using, which would make your query look like this:
$itemName = 'Item1';
$sql = "SELECT * FROM order WHERE itemName = ?";
$stmt = $conn->prepare($sql);
$stmt->bindParam(1, $item, PDO::PARAM_STR);
$stmt->execute();
Read up on bindParam().
In future, turn on your error reporting at the beginning of the script with this:
ini_set('display_errors', 1);
error_reporting(E_ALL);
That will save you a lot of time.
Looks like there is an error in you sql statement. since itemName is either a varchar or text in your database, you need to put it in single quotes in the query:
$sql = "SELECT * FROM order WHERE itemName = '$itemName';";
I have a problem with mysql_query
I tried to find members who are online, there is a field "Online" in the members table are always updated with the time server. This is the query.
$ now = time ();
$ olline = mysql_num_rows (mysql_query ("select * from members where gender = 'Man' and (online - '$ now')> 10"));
in phpmyadmin there are 7 members in accordance with the above query. tp I get a value of 0. what is wrong with my code. tq for the answer and sorry for bad english
You should try and always use Mysqli these days as before long Mysql will be gone completely. Mysqli example of your code:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$now = time(); // The time now for query calc
$gender = "Man"; // Gender for query
$stmt = $mysqli->stmt_init(); //Initialise statement
$stmt->prepare("SELECT * FROM members WHERE gender = ? AND (online - ?)> 10"); //Prepare the query
$stmt->bind_param('ss', $gender, $now); //Assign the query parameters
$stmt->execute(); // Execute the query
$stmt->store_result(); // store result of prepared statement
echo $stmt->num_rows;
$stmt->free_result(); //free up the $stmt var
Variable names cannot contain spaces, so your variable names are invalid. It should be $now or $_now and NOT $ now. See Language variable basics for more information:
Correct code :
$now = time ();
$olline = mysql_num_rows (mysql_query ("select * from members where gender = 'Man' and (online - '$now')> 10"));
Also , avoid using mysql_ functions cause they are deprecated. Use mysqli_ or PDO.
I am not sure, I have clearly understood your question.
If I have understood correctly, you want to display the online available members.
Do you have any flag for checking if the member online or not? If there is a flag then use that flag and filter by online status. This how we have to do for chat operations.
I am not sure, why you going with subtraction.