Ive been trying to crack this for 2 hours, but something is wrong. I am very much used to doing things without mysqli but read that there is a recommended shift towards it from regular mysql commands. Hence am stuck with following:
<?php
$mysqli = new mysqli('localhost', 'admin', 'test123', 'kadmindb');
if ($result = $mysqli->query("SELECT * FROM records WHERE '$queryType' = '$keyword'")) {
while ($row = $result->fetch_object()) {
echo "<h2>Result:</h2><br>";
echo "ID: " . $row->id . "<br>";
echo "Name: " . $row->cust_name . "<br>";
echo "Invoice No: " . $row->invoice_num . "<br>";
echo "Date: " . $row->date_recorded . "<br>";
}
}
?>
This code is shown in the page where the result of the query should be displayed but nothing is displayed. I checked that both keyword and queryType variables are set and they contain the correct values. Any help would be greatly appreciated. All am trying to do is: select statement to retrieve all the details based on invoice_num submitted.
EDIT: from help I received, I was able to get this working:
$query = "SELECT * FROM records WHERE ".$queryType. " LIKE '%$keyword%' ";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_object()) {
echo "<h2>Result:</h2><br><hr/> ";
echo "ID: " . $row->id . "<br>";
echo "Name: " . $row->cust_name . "<br>";
echo "Invoice No: " . $row->invoice_num . "<br>";
echo "Date: " . $row->date_recorded . "<br>";
echo "<hr/>";
}
}
Are you sure there's data to select? This code will only output data if there actually is.
Make sure that $queryType and $keyword are set and have sane values that will yield a result.
Use var_dump($queryType) and var_dump($keyword) immediately before the query. Now check your output. Are they both strings? Run this query directly in PHPMyAdmin and check how many rows you get.
If you can't do that try echo'ing the number of rows returned along with the query values:
if ($result = $mysqli->query("SELECT * FROM records WHERE $queryType = '$keyword'"))
{
while ($row = $result->fetch_object())
{
echo "<h1>Query WHERE '$queryType' = '$keyword' yielded {$result->num_rows} rows!</h1>";
echo "<h2>Result:</h2><br>";
...
Note, you should not have single quotes around the column ($queryType), if you insist you should use backtick quotes (`) but it's unnecessary really - if you're that pedantic you should be using prepared statements.
Also be sure to filter them for any potentially dangerous values that could allow for sql injections. See: mysqli::real_escape_string
Assuming that $queryType is the name of a column in your records table, then I believe the problem is your WHERE clause.
Rather than:
$mysqli->query("SELECT * FROM records WHERE '$queryType' = '$keyword'")
You should have:
$mysqli->query("SELECT * FROM records WHERE {$queryType} = '{$keyword}'")
Note that I've removed the single quotes around $queryType and have used complex (curly) syntax
Also, in the future you might want to try using an else block to trap errors:
$mysqli = new mysqli('localhost', 'admin', 'test123', 'kadmindb');
if ($result = $mysqli->query("SELECT * FROM records WHERE {$queryType} = '{$keyword}'")) {
while ($row = $result->fetch_object()) {
echo "<h2>Result:</h2><br>";
echo "ID: " . $row->id . "<br>";
echo "Name: " . $row->cust_name . "<br>";
echo "Invoice No: " . $row->invoice_num . "<br>";
echo "Date: " . $row->date_recorded . "<br>";
}
}
else
{
echo "Error: " . $mysqli->error;
}
Related
I have an MySQL data base that has a cell in a record called balance. The db shows it is stored as a decimal(16,2). When I try to display the vale of the record with echo $row["balance"]; In PHP, it display nothing at all. Can you please point me in the right direction. Thanks you.
$sql = "SELECT id, email, username FROM ppb_users WHERE id = '$USERIDX' ";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
//// output data of each row
while($row = $result->fetch_assoc())
{
echo "<br> id: " . $row["id"] . "<br> email: " . $row["email"] . "<br> username: " . $row["username"] . "<br> Ballance: " . $row["balance"] ."<br>";
$UserEmail = $row["email"];
$balancex = $row["balance"];
}
}
else
{
echo " 0 results <br><br>";
}
$conn->close();
Sorry folks, it would seem I had one of those moments in where when it is over and you realize what you did, how small you feel. I did not add balance to the SQL se3lect line. Uggg! Soryy.
I am trying the approach of 'adding a log just before the php query'; in effort to achieve the ability to print a 'time stamp' when my mySQL database has been updated.
my queries look like this.
require_once('include/connect.php');
$q = $_GET['q'];
//echo $q;
//$plan=substr($q,0,4);
//$spec=substr($q,4);
list($plan, $ptype, $spec) = explode('_', $q);
//echo $plan . ", " . $spec;
//$query="SELECT vphp.tbl_provider_types.`TYPE` from coolDB.tbl_provider_types where vphp.tbl_provider_types.".$q." = 'Y';";
$query= "SELECT tbl_sourcespecheader.specID, coolDB.tbl_sourcespecheader.Specialty_Header from vphp.tbl_provider_types left join coolDB.tbl_sourcespecheader on coolDB.tbl_provider_types.ID = coolDB.tbl_sourcespecheader.TypeID where coolDB.tbl_provider_types.ID = " . $spec . " and coolDB.tbl_sourcespecheader." . $plan . " = 'Y';";
$result = mysqli_query($connection, $query);
//Populate result in HTML which will be returned via AJAX
echo "<h4>Please select from these " . $ptype . " specialties:</h4>";
echo "<select id='type' multiple='' name='specialty'><option selected="selected" value="nospec"></option>";
while($row = mysqli_fetch_array($result))
{
echo "<option value='" . $row['specID'] . "'><a href='#' id='" . $row['specID'] . "' onclick='getSelected(this.id);return false' style='text-decoration: none'>" . $row['Specialty_Header'] . "</a></option>";
}
echo "</select>";
//Close database connection
mysqli_close($connection);
Better use triggers. You need to create log table to be able to insert all data you needed. Below is the example.
DELIMITER $$
CREATE TRIGGER before_employee_update
BEFORE UPDATE ON employees
FOR EACH ROW
BEGIN
INSERT INTO employees_audit
SET action = 'update',
employeeNumber = OLD.employeeNumber,
lastname = OLD.lastname,
changedat = NOW();
END$$
DELIMITER ;
If you are using phpMyadmin. Go to that and find the trigger menu. There you can create triggers.
So my 1st target is to convert expecting data from mySQL as JSON before use XML.
Things i trying to solve- Connect two tables from database for specific user and display it on screen.
Everything is in one PHP file:
<?php
include 'db.php';
session_start();
ob_start();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM users
INNER JOIN user_quiz ON users.user_uid = user_quiz.user_uid
WHERE users.user_uid = '".$_SESSION['u_uid'] ."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$outp = array();
$outp = $result->fetch_all(MYSQLI_ASSOC);
// for check if record exist
echo "<br> id: ". $row["id"]. " - Name: ". $row["user_first"]. " " . $row["user_last"] . " id:" . $row["user_uid"] . " Selected qustion " . $row["q_topic"] . " ". $row["q_id"] . "<br>";
}
} else {
echo "0 results";
}
$myJSON = json_encode($outp);
echo $myJSON;
?>
So now where is a issue.. When i do SQL like that:
SQL:
$sql = "SELECT * FROM users";
PHP is convert data as JSON data... but when i trying to do that for specific user i have empty []... That's why i use echo to see if i have output or i have error but... i have displays value... Had no idea what's going on... need advice.
EDIT: SOLVED. Thanks to the guys in the comments who recommended turning PHP error messages on, showed me exactly where things were going wrong. For those that are curious, it was as simple as this: two function calls had "mysql_" instead of "mysqli_". Also thanks to the user that pointed out that prepared SQL queries must use ->execute() instead of mysqli_query().
I'm working on a community bulletin board. I've gotten it to a point where the page for posting a listing works and submits it to the database, but when I try to search for the listings I'm having some trouble with the SQL query. Here's the code that I have:
<?php
if(isset($_GET['submit'])){
$location = $_GET['location'];
echo "Looking for listings in: " . $location;
echo "<br />";
require_once('mysqli_connect.php');
$query = "
SELECT email_address
, phone_number
, date
, listing_content
FROM listings
WHERE location='?'
";
echo $query;
$stmt = mysqli_prepare($dbc, $query);
mysqli_stmt_bind_param($stmt, "s", $location);
$results = mysqli_query($stmt);
$numListings = mysql_num_rows($results);
echo $numListings . " listing(s) found";
echo "<hr>";
if ($numListings == 0){
echo "Feel free to press the button above to post the first listing in " .
$location;
} else {
while($row = mysql_fetch_array($results)){
echo "Location: " . $location;
echo "<br />";
echo "Date: " . $row[date];
echo "<br />";
echo "Email address: " . $row[email_address];
echo "<br />";
if($row[phone_number] != NULL){
echo "Phone number: " . $row[phone_number];
echo "<br />";
}
echo $row[listing_content];
echo "<br />";
echo "<hr>";
}
}
mysqli_stmt_close($stmt);
mysqli_close($dbc);
}
?>
And this is the output I'm getting, where everything below the button "Make new post" is generated by the PHP:
It looks like it's crashing, at some point after the line echo $query; because it prints that out but it doesn't print some of the other statements after that. Either it's crashing or the SQL query is somehow messing up without crashing it or throwing an error.
This is what the database looks like:
I am trying to access firstname by it self. I have the code below put together:
<?php
$sql = "SELECT firstname, lastname FROM guests WHERE option = $option";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "You Are " . $row["firstname"]. " " . $row["lastname"]. "<br>";
?>
It gives me You are Bob Testing. I need to convert them to self variable so I can use them anywhere. Like $row["firstname"] = $firstname; so then I could echo $firstname; But it won't work if I use $row["firstname"] = $firstname;
I think the issue is somewhere in how I form the result $result = mysqli_query($conn, $sql); Can I say something else here so then I could just use say $row["firstname"] = $firstname; and use like echo $firstname;? Thanks.
Firstly, if this is your actual code, it's missing a few closing braces.
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "You Are " . $row["firstname"]. " " . $row["lastname"]. "<br>";
} // this one was missing
} // as was this one
Now, assign a variable "to" the row(s) and not the other way around.
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$first = $row["firstname"];
$last = $row["lastname"];
}
echo "You are " . $first . " " . $last . "<br>";
}
However the above will only echo a single row, therefore you will need to place the echo "inside" the while loop in order to echo all the rows in your table:
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$first = $row["firstname"];
$last = $row["lastname"];
echo "You are " . $first . " " . $last . "<br>";
}
}
Something about this though WHERE option = $option";
If $option is a string, it will need to be quoted:
WHERE option = '$option'";
otherwise, MySQL will see that as a syntax error. Check for errors on your query:
http://php.net/manual/en/mysqli.error.php
It will also be prone to an SQL injection, therefore it is best you use a prepared statement.
https://en.wikipedia.org/wiki/Prepared_statement
Seeing you may be new to working with MySQL, it's best to learn about protecting yourself against SQL injection. Here is a good article about it on Stack:
How can I prevent SQL injection in PHP?