I have a query and works:
$sql2 = "SELECT id FROM table WHERE '2022-06-06' BETWEEN date(se_from) AND date(se_to)";
But when the date is dynamic the query fails:
$pick_date = '2022-06-06';
$sql2 = "SELECT id FROM tblseasons WHERE $pick_date BETWEEN date(se_from) AND date(se_to)";
Can't understand, can anyone explain.
Thanks
Your query lacks parentheses in the date (so it fails to do what you want as the query will be invalid)
For security, please use parameterized prepared statement to avoid SQL injection attacks instead
For mysqli, it will be:
$conn = mysqli_connect("localhost", "user", "dbpass", "dbname1");
$pick_date = '2022-06-06';
$sql2 = "SELECT id FROM tblseasons WHERE ? BETWEEN date(se_from) AND date(se_to)";
$stmt = $conn->prepare($sql2);
$stmt->bind_param("s", $pick_date);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
while ($row = $result->fetch_assoc()) {
echo $row['id'] . "<br>"; // if you want to see the result;
}
For PDO, it will be
$dbh = new PDO('mysql:host=localhost;dbname=dbname1', "user", "dbpass");
$pick_date = '2022-06-06';
$string1 = "SELECT id FROM tblseasons WHERE :pick_date BETWEEN date(se_from) AND date(se_to)";
$stmt = $dbh->prepare($string1, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute([':pick_date' => $pick_date]);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row["id"] . "<br>"; // if you want to see the result;
}
Related
I am trying to make SQL in php to return all the entries that matches a keyword that is entered by the user (from search bar).
I want to return all the entries that their name "partial" matches with the keyword.
I want at least to match the keyword, if an entry name in database before has space and after maybe another letter/space.
For example I have three entries with names "Milk", "Semi skimmed Milk" and "Full Milk 2". If the keyword is "Milk" or "milk" or "MiLK", I want to get all these three entries.
The only case I am thinking it might be the problem is case sensitive.
I tried with a keyword that exists exactly in database, but my app (on android) stops .
Based on user3783243 answer.
PHP FILE
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name FROM items WHERE name LIKE CONCAT ('%', ?, '%')";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $keyword);
$res = $stmt->get_result();
while($row = $res->fetch_assoc()) {
echo $row["name"] . ",";
}
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["name"] . ",";
}
} else {
echo "0";
}
$conn->close();
?>
Your query should be:
$sql = "SELECT * FROM items WHERE name LIKE CONCAT ('%', ?, '%')";
and then $keyword should be bound with whatever syntax the driver you are using supports.
As is your query would have been:
SELECT * FROM items WHERE name LIKE CONCAT ('%', Milk, '%')
and you wanted Milk to be a string so it needed to be quoted. As is mysql would have thought that was a column.
Alternatively you could do:
$keyword = '%' . $_POST['keyword'] . '%';
$sql = "SELECT * FROM items WHERE name LIKE CONCAT ?";
that is the same and still requires the binding though.
The binding also takes away the SQL injection. See How can I prevent SQL injection in PHP? and/or https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet#Defense_Option_1:_Prepared_Statements_.28with_Parameterized_Queries.29
Per update.. replace:
$keyword =$_POST['keyword'];
$sql = "SELECT * FROM items WHERE name LIKE '%$keyword%)";
$result = $conn->query($sql);
with:
$sql = "SELECT name FROM items WHERE name LIKE CONCAT ('%', ?, '%')";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $keyword);
$stmt->execute();
$res = $stmt->get_result();
if(empty($conn->errno) && !empty($res)) {
while($row = $res->fetch_assoc()) {
echo $row["name"] . ",";
}
} else {
echo '0';
//print_r($conn->errno);
}
$conn->close();
...
also remove
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["name"] . ",";
}
} else {
echo "0";
}
$conn->close();
In this case you can convert the input in search bar to either upper or lower case by default then apply query in db like
For Upper case:
$keyword =strtoupper($_POST['keyword']);
$sql = "SELECT * FROM items WHERE upper(name) LIKE '%$keyword%)";
Or for lower case:
$keyword =strtolower($_POST['keyword']);
$sql = "SELECT * FROM items WHERE lower(name) LIKE '%$keyword%)";
If I try to create a sql query such as this:
$sql2 = mysqli_query($connection,"SELECT * FROM CHILD_IMG WHERE PROD_ID='$delID'") or die(mysqli_error());
$getQuery = $connection->query($sql2);
while($row = $getQuery->fetch_array()){
$childID = $row['ID'];
$parentID = $row['PROD_ID'];
$childName = '../ProductImages/ChildImages/'.$parentID . "_".$childID.".jpg";
unlink($childName);
}
I get the following error:
Fatal error: Call to a member function fetch_array() on null in
If I run and store the query to $sql like this:
$sql2 = ("SELECT * FROM CHILD_IMG WHERE PROD_ID = '$delID'") or die(mysqli_error());
$getQuery = $connection->query($sql2);
while($row = $getQuery->fetch_array()){
$childID = $row['ID'];
$parentID = $row['PROD_ID'];
$childName = '../ProductImages/ChildImages/'.$parentID . "_".$childID.".jpg";
unlink($childName);
}
The query run smoothly without any issues.
What is the problem why doesn't the first option works?
See this bit of code?
$sql2 = mysqli_query($connection,"SELECT * FROM CHILD_IMG WHERE PROD_ID='$delID'") or die(mysqli_error());
^^^^^^^^^^^^
$getQuery = $connection->query($sql2);
^^^^^
You're actually querying twice, that's why you're getting the error.
Plus, the or die(mysqli_error()) belongs after the query call and it requires a db connection as the argument.
I.e.: or die(mysqli_error($connection)).
So you'd do the following to check if the query failed:
if(!$getQuery){
echo "Error: " . die(mysqli_error($connection));
}
Rewrite:
$sql2 = "SELECT * FROM CHILD_IMG WHERE PROD_ID='$delID'";
$getQuery = $connection->query($sql2);
while($row = $getQuery->fetch_array()){
$childID = $row['ID'];
$parentID = $row['PROD_ID'];
$childName = '../ProductImages/ChildImages/'.$parentID . "_".$childID.".jpg";
unlink($childName);
}
You're also open to an SQL injection; use a prepared statement.
References:
https://en.wikipedia.org/wiki/Prepared_statement
http://php.net/manual/en/mysqli.prepare.php (mysqli)
http://php.net/manual/en/pdo.prepared-statements.php (PDO)
Note: If you intend on going with PDO, remember to not mix the different MySQL APIs.
I wanted to display a page content with PHP and MySQL. But i don't know how to select and display data from PHP.
$name = $_GET['title'];
$query = "SELECT * FROM pages WHERE name = $name";
$result = mysql_query("$query");
But i don't know how to display data. I want to get the string value from content in sql table row where name = $name and display it.
If you can, please help me
You may try and include this in your code:
$name = mysqli_real_escape_string($_GET['title']);
$query = "SELECT * FROM pages WHERE name = $name";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)){
echo $row['content'];
}
mysqli_free_result($result);
Here I have assumed $link as the handle to connect to the database.
N.B.: You may consider passing the $_GET values through mysqli_real_escape_string() to avoid sql injections which may prove fatal to the database and its tables. You also need to consider the usage of mysqli_* functions because mysql_* functions are deprecated and will be discontinued.
You have error in your sql, change
$query = "SELECT * FROM pages WHERE name = $name";
$result = mysql_query("$query");
to
$query = "SELECT * FROM pages WHERE name = '".$name."'"; // as name is char it should be enclosed in quotes
$result = mysql_query($query); // using quotes inside this will just display it without executing the query
You can fetch the results by this (if the result is only single record):
$row=mysql_fetch_array($result); // fetch the result as an array with subscript as the field name
echo $row['content']; // echo the value of the field content
If the query result contains multiple records then you have to do this inside a while loop like this:
while($row=mysql_fetch_array($result)) // fetch the result as an array with subscript as the field name
{
echo $row['content']; // echo the value of the field content
}
you have to do like this
$name = $_GET['title'];
$query = "SELECT * FROM pages WHERE name = '".$name."'";
$result = mysql_query($query);
//get values returned from query
$row=mysql_fetch_array($result);
//display required content
echo $row['content'];
Also mysql_* function are deprecated.You have to stop using this. Start using PDO or prepared statements or mysqli_* function
First of all the mysql_ is deprecated, use mysqli_
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result = mysqli_query($link, $query);
/* numeric array */
$row = mysqli_fetch_array($result, MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);
/* associative array */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
/* associative and numeric array */
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
printf ("%s (%s)\n", $row[0], $row["CountryCode"]);
/* free result set */
mysqli_free_result($result);
/* close connection */
mysqli_close($link);
?>
Source: http://www.php.net/manual/en/mysqli-result.fetch-array.php
$query = mysql_query("SELECT * FROM table WHERE name = $name");
$result = mysql_fetch_array($query);
//you'll get value in var
$var=$result['content'];
You can do this using Prepared Statements :
$query = "SELECT whatever1, whatever2 FROM pages WHERE name = ?";
$stmt = $connection->prepare($query);
$stmt->bind_param("s", $name);
$stmt->execute();
$stmt->bind_result($value_you_want, $value_you_want_as_well);
while($stmt->fetch()){
echo $value_you_want . $value_you_want_as_well;
}
$stmt->close();
Or you can do this using PDO :
$query = "SELECT whatever1, whatever2 FROM pages WHERE name = :name";
$stmt = $connection->prepare($query);
$stmt->bindParam(':name', $name, PDO::PARAM_STR, 20);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach ($result as $page) {
echo $page->whatever1 . $page->whatever2;
}
$stmt = null; // Set to null to destroy connection
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How do i “echo” a “Resource id #6” from a MySql response in PHP?
I am looking for the result out of a query, but it keeps giving me resource id #3.
The following is my code.
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
print_r($typeResult);
What step am I missing here?
You need to fetch the result. All you're doing is sending the query.
Be aware that if you are writing new code, you should use mysqli_ or PDO functions as your query is vulnerable to SQL injection and mysql_ functions are being deprecated. Hesitantly, below is a sample for mysql_fetch_assoc.
<?php
$sql = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row[sellingid];
}
mysql_free_result($result);
?>
Reference
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
$row = mysql_fetch_array($typeResult);
print_r($row);
More clear hint - use MySQLi class/functions, read this:
http://lt1.php.net/manual/en/mysqli-result.fetch-assoc.php
or if you like OOP approach more then
http://lt1.php.net/manual/en/mysqli-result.fetch-object.php
You are not actually fetching the results of your query. Below are two examples that use WHILE loops to fetch the results as rows. You can then grab the column values and work with them.
Incorrect and depreciated method, but working:
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
// for each row
while ($row = mysql_fetch_array($typeResult)) {
// grab the columns
$value = $row['column_name'];
}
I would recommend using MySQLi or PDO like to following (MySQLi):
$mysqli_connection = new mysqli("hostname", "username", "password", "database");
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$res = $mysqli_connection->query($type);
while($row = $res->fetch_array(MYSQLI_ASSOC)) {
$value = $row['column_name'];
}
$res->free();
$mysqli_connection->close();
Is there any way to store mysql result in php variable? thanks
$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=$conn->query($query);
then I want to print selected userid from query.
Of course there is. Check out mysql_query, and mysql_fetch_row if you use MySQL.
Example from PHP manual:
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
There are a couple of mysql functions you need to look into.
mysql_query("query string here") : returns a resource
mysql_fetch_array(resource obtained above) : fetches a row and return as an array with numerical and associative(with column name as key) indices. Typically, you need to iterate through the results till expression evaluates to false value. Like the below:
while ($row = mysql_fetch_array($query)){
print_r $row;
}
Consult the manual, the links to which are provided below, they have more options to specify the format in which the array is requested. Like, you could use mysql_fetch_assoc(..) to get the row in an associative array.
Links:
http://php.net/manual/en/function.mysql-query.php
http://php.net/manual/en/function.mysql-fetch-array.php
In your case,
$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=mysql_query($query);
if (!$result){
die("BAD!");
}
if (mysql_num_rows($result)==1){
$row = mysql_fetch_array($result);
echo "user Id: " . $row['userid'];
}
else{
echo "not found!";
}
$query="SELECT * FROM contacts";
$result=mysql_query($query);
I personally use prepared statements.
Why is it important?
Well it's important because of security. It's very easy to do an SQL injection on someone who use variables in the query.
Instead of using this code:
$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=$conn->query($query);
You should use this
$stmt = $this->db->query("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password); //You need the variables to do something as well.
$stmt->execute();
Learn more about prepared statements on:
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php MySQLI
http://php.net/manual/en/pdo.prepared-statements.php PDO
$query = "SELECT username, userid FROM user WHERE username = 'admin' ";
$result = $conn->query($query);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$arrayResult = mysql_fetch_array($result);
//Now you can access $arrayResult like this
$arrayResult['userid']; // output will be userid which will be in database
$arrayResult['username']; // output will be admin
//Note- userid and username will be column name of user table.