Placing a PHP variable in a MySQL query - php

I'm having issues placing a PHP variable in MySQL string,
<?php
$con=mysqli_connect("***","***","***","***");
function getItem($itemNo)
{
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM products WHERE product_id = '$itemNo'");
echo $itemNo;
echo "<br>";
while($row = mysqli_fetch_array($result))
{
echo $row['product_id'] . " " . $row['product_name'];
echo "<br>";
}
}
getItem(1001);
mysqli_close($con);
?>
The page shows my echo of the $itemNo, but thats all. If I just do select * from products, it gives my entire table like it should, so I know the database is working,
so I've narrowed it down to the placement of the variable.
EDIT:
product_id column is an int and also the primary key.

You can try a prepared statement to make using variables in your queries easier.
$stmt = $con->prepare("SELECT * FROM products WHERE product_id=?");
$stmt->bind_param($itemNo);
$stmt->execute();
$stmt->close();

$result = mysqli_query($con,"SELECT * FROM products WHERE product_id = " .$itemNo );

Related

MySQL Result Prints More Than One

In my database I have a one-to-many table relationship where one parent can have many kids. The primary key is the parents email. I query to get the kids
$results1 = mysqli_query($con,"
SELECT directory.email
, dirKids.kname
, dirKids.kbirthday
FROM directory
JOIN dirKids
ON '$row[email]' = dirKids.parent
");
Then I loop through and echo the value to my html page
while($row1 = mysqli_fetch_array($results1)) {
if (!empty($row1["kname"])) {
echo "<tr><td>". $row1["kname"] ."</td><td>".
$row1["kbirthday"]."</td></tr>";
}
}
The problem I am having is that only one parent has kids in my database, but it will print the kids name and birthday 10 times because there are 10 people in my database. How can I get it to only print the child's name and birthday once?
My full code is listed below:
<?php
$con = mysqli_connect("localhost", "username", "password", "db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$results = mysqli_query($con,"SELECT directory.id, directory.fname, directory.lname, directory.address, directory.bdname, directory.birthday, directory.cell, directory.email, directory.sFName, directory.sBirthday, directory.sCell, directory.sEmail FROM directory ORDER BY lname") or die ("couldn't fetch query");
echo "<div class='accordion' id='accordion'>";
// output data of each row
while($row = mysqli_fetch_array($results)) {
$results1 = mysqli_query($con,"SELECT directory.email, dirKids.kname, dirKids.kbirthday FROM directory JOIN dirKids ON '$row[email]' = dirKids.parent");
echo "</table></div>";
if ($row['sFName'] == "" || $row['sFName'] == "undefined") {
echo "<div class='card'><div class='card-header'
id='headingOne'><h5 class='mb-0'><button class='btn btn-link'
type='button' data-toggle='collapse' data-target='#collapse".
$row["id"] ."' aria-expanded='true' aria-controls='collapse".
$row["id"] . "'><h5>".$row["fname"] ."<span id='lnameText'>".
$row["lname"] ."</span></h5></button></h5></div><div
id='collapse". $row["id"] . "' class='collapse'
aria-labelledby='headingOne' data-parent='#accordion'><div
class='card-body'><table id='myUL' class='table'><tr></tr><tr>
<td><h5>Address</h5></td><td>". $row["address"] ."</td></tr>
<tr><td><h5>Birthday</h5></td><td>".$row["birthday"]."</td>
</tr><tr><td><h5>Cell</h5></td><td>". $row["cell"]."</td></tr>
<tr><td><h5>Email</h5></td><td>". $row["email"] ."</td></tr>
</table></div>";
echo "<div class='col-md-6'><h3>Children</h3><table class='table'><tr><th><h5>Name</h5></th><th><h5>Birthday</h5></th>";
while($row1 = mysqli_fetch_array($results1)) {
if (!empty($row1["kname"])) {
echo "<tr><td>". $row1["kname"] ."</td><td>". $row1["kbirthday"]."</td></tr>";
}
}
echo "</table></div></div>";
?>
Since the data needed for the second while loop comes exclusively from the kids table, just build your SELECT statement for that, forget the join and the WHERE statement looks for only the parents email.
The below code goes inside the primary while loop and replaces the
$results1 = mysqli_query($con,"SELECT directory.email, dirKids.kname, dirKids.kbirthday FROM directory JOIN dirKids ON '$row[email]' = dirKids.parent");
with
//Build the select statement
$sql = "SELECT kname, kbirthday FROM dirKids WHERE parent = '" .$row[email] . "'";
//now run the query
$results1 = mysqli_query($con,$sql);
//uncomment the below to see the results
//var_dump(mysqli_fetch_array($results1));
Your query should look like this;
$select = mysqli_query($db, "SELECT * FROM parents_database WHERE parent_name = '$parent_name'");
while ($row = mysqli_fetch_array($select, MYSQLI_ASSOC)) {
// echo kids here..
}
Not sure what do you need. Since you posted 2 different queries.
But 1st one has wrong approach, hope you need to fix that one.
I think you've meant something like:
SELECT directory.email
, dirKids.kname
, dirKids.kbirthday
FROM directory
JOIN dirKids
ON directory.email = dirKids.parent
WHERE directory.email = '$row[email]'

exclude null data from mysql select

Having trouble excluding data that is null, I just want to pull the rows that have discord_id data. Here is the code I have:
<?php
$con=mysqli_connect("localhost","site","password","table");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM core_members");
while($row = mysqli_fetch_array($result))
{
echo $row['name'] . " " . $row['discord_id'];
echo "<br />";
}
mysqli_close($con);
?>
You have to use MySQL: IS NOT NULL like below:-
$result = mysqli_query($con,"SELECT * FROM `core_members` WHERE `discord_id` IS NOT NULL");
Add the following where clause to your code:-
where discord_id is not null
Full Select Statement:
SELECT * FROM core_members where discord_id is not null;
Add it as condition to the WHERE clause:
SELECT * FROM core_members where discord_id is not null
Just add an is not null condition:
$result =
mysqli_query($con, "SELECT * FROM core_members WHERE discord_id IS NOT NULL");

I want to use two where conditions in php to get data from mysql

My problem is this:
<?php
// Connect to database server
mysql_connect("localhost", "root", "abcabc") or die (mysql_error ());
// Select database
mysql_select_db('iite') or die(mysql_error());
// Get data from the database depending on the value of the id in the URL
$strSQL = "SELECT * FROM table1 WHERE id=" . $_GET["id"];
$rs = mysql_query($strSQL);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
// Write the data of the person
echo'<h1>'. $row['title'].'</h1>';
echo'<h1>'. $row['price'].'</h1>';
}
// Close the database connection
mysql_close();
?>
I want to show related posts, for this I need to insert this:
$sql = "SELECT * FROM table1 where title like '%keyword%' limit 5";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["price"]. " " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
so how can I insert the related post part near
$strSQL = "SELECT * FROM table1 WHERE id=" . $_GET["id"];
and how to echo?
Thanks
You can use OR or AND for combining different where conditions(according to requirement) in query :
Ex;
$strSQL = "SELECT * FROM table1 WHERE id=" . $_GET["id"] ." OR title like '%keyword%' limit 5";
$strSQL = mysql_query(SELECT * FROM table1 WHERE id=" . $_GET["id"] ." OR title like '%keyword%' limit 5) or die(mysql_error());
$row_strSQL = mysql_fetch_assoc($strSQL );
$totalRows_strSQL = mysql_num_rows($strSQL );
if ($result->totalRows_strSQL > 0) {
// output data of each row
while($row_strSQL= $result->fetch_assoc()) {
echo "id: " . $row_strSQL["id"]. " - Name: " . $row_strSQL["price"]. " " . $row_strSQL["title"]. "<br>";
}
} else {
echo "0 results";
}
You don't need two seperate queries for that at all. Just use the OR operator in ur where clause like Where id=" . $_GET['id']." or title like '%keyword%'

PHP mysql search with Variables

I'm trying to query a database using a variable to detect the chosen column along with the search term.
For simplicity I removed the DB connection error handling code. The problem code is:
$find = mysqli_real_escape_string($dbc, test_input($_POST["find"]));
$field = $_POST["field"];
$data = mysqli_query($dbc, "SELECT * FROM ticket WHERE '$field' = '$find'");
//Results
while($result = mysqli_fetch_array($data)) {
echo "Result 1" . $result['number'];
echo "<br>";
echo "<br>";
echo "Result 2" . $result['description'];
echo "<br>";
echo "<br>";
echo "Result 3" . $result['contact'];
echo "<br>";
echo "<br>";
echo "Result 4" . $result['assignee'];
echo "<br>";
echo "<br>";
echo "Result 5" . $result['priority'];
echo "<br>";
echo "<br>";
}
$anymatches = mysqli_num_rows($data);
if ($anymatches == 0) {
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
I enter a term in a textbox ($find) and choose what Im searching for from a dropdown menu ($field) e.g. I select assignee.
Even though I know its in the database, I still returns the "Sorry, but we can not find an entry to match your query".
However, if I change the $field variable within the MYSQL query to an actual column name. Example:
$data = mysqli_query($dbc, "SELECT * FROM ticket WHERE assignee = '$find'");
it returns with the correct data. I even echo'd the $field variable during execution to make sure its holding the correct selection, and it does. Any ideas?
Thanks
The problem is you're surrounding the field name with quotes (') instead of backticks.
$data = mysqli_query($dbc, "SELECT * FROM ticket WHERE '$field' = '$find'");
to
$data = mysqli_query($dbc, "SELECT * FROM ticket WHERE `$field` = '$find'");
or
$data = mysqli_query($dbc, "SELECT * FROM ticket WHERE $field = '$find'");
Your current code will essentially be trying to find rows where one string matches another string, which will never be true.
Make query like
$data = mysqli_query($dbc, "
SELECT * FROM ticket
WHERE {$field} = '$find'
");

PHP echo date and number from query

Hi I have trying to learn php by writing little web app for showing me sales data. I have got a query which i now works as i have tested it but i want it to echo the datematched and the number of rows/results found with that date. This is what I have so far
<?php
$con=mysqli_connect("host","user","password","database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM matched WHERE datematched IN (
SELECT datematched FROM matched GROUP BY datematched HAVING count(*) > 1");
while($row = mysqli_fetch_array($result))
{
echo "['";
echo "" . $date['datematched'] . "', ";
echo "" . $num_rows . "],";
}
mysqli_close($con);
?>
I know i am doing something wrong here. ryan
EDIT:
<?php
$con=mysqli_connect("host","user","password","database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM matched WHERE datematched IN (
SELECT datematched FROM matched GROUP BY datematched HAVING count(*) > 1");
echo "['";
echo " 16/08/2013 ', ";
echo "12345}],";
mysqli_close($con);
?>
Okay i have just checked my echo and they work i put in some data so all i need is to find a way of getting the information of the datematched that has been found and then the number of rows that has been found with that. Thanks Ryan
first of all you need to make an adjustment to your query, so that it has the number of rows your expecting.
$result = mysqli_query($con,"SELECT datematched, COUNT(*) as num_rows "
. "FROM matched GROUP BY datematched HAVING num_rows > 0");
then you can display the data as follows
while($row = mysqli_fetch_array($result))
{
echo $row['datematched'] . ",";
echo $row['num_rows'];
}
if your sql query is perfect then you should write like this wayt
while($row = mysqli_fetch_array($result))
{
echo "['";
echo "" . $row['datematched'] . "', ";
echo "" . $row['num_rows'] . "', ";
}
please set your column as you got in your mysql query.
<?php
$query=mysqli_query($con,"SELECT datematched FROM matched GROUP BY datematched");
$num=mysqli_num_rows($query);
if($num>1)
{
$result = mysqli_query($con,"SELECT * FROM matched");
$num_rows=mysqli_num_rows($result);
while($row = mysqli_fetch_array($result))
{
echo '['; echo $row['datematched']; echo $num_rows; echo ']';
}
}

Categories