Trouble when passing a php variable as an argument in mysql query - php

I'm trying to use a php variable as a search term when querying a mysql database, first I get the variables from the HTML form:
<?php
//Create variables
$vals = array($_POST["id_number"], $_POST["id_name"], $_POST["id_submitname"]);
$keys = array('idno_1', 'name_2', 'subname_3');
//combine keys to arrays
$var = array_combine($keys, $vals);
//santise variables
$variables = filter_var_array($var, FILTER_SANITIZE_STRING);
$idno = $variables['idno_1'];
$name = $variables['name_2'];
$subname = $variables['subname_3'];
After connecting to the database I run the query:
//Select entry from table and display
if (!$idno == '')
{
$sql = "SELECT * FROM `healthsafety` WHERE ID = '$idno'";
$result = mysqli_query($connection, $sql);
}
elseif (!$name == '')
{
$result = mysqli_query($connection, "SELECT * FROM `healthsafety` WHERE LOWER (nameinvolved) = LOWER ('$name')");
}
else
{
$result = mysqli_query($connection, "SELECT * FROM `healthsafety` WHERE LOWER (submitbyname) = LOWER ('$subname')");
}
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
It is not returning anything from the db, when I select * FROM without trying to use the variable as a search it displays all entries ok, am I making an error when passing the variable to the query? I've tried different combinations of quotes, back ticks and using other variables for the query. Any help would be greatly appreciated!

LOWER is a function and the arguments needs to be wrapped in parentheses.
Your query should look like:
$result = mysqli_query($connection, "SELECT * FROM `healthsafety`
WHERE LOWER(nameinvolved) = LOWER('$name')");
For easier debugging, I'd first print out the query:
$query = "SELECT * FROM `healthsafety`
WHERE LOWER(nameinvolved) = LOWER('$name')";
echo $result;
... and then run it manually using the MySQL Interactive shell or using web interfaces like phpMyAdmin. That could help you isolate the issue further and then figure out what's wrong.

First you needed to be sure that all data are correct. then Try this:
if (isset($idno) && !$idno == '')
{
$sql = "SELECT * FROM `healthsafety` WHERE ID = $idno";
$result = mysqli_query($connection, $sql);
}
else if (isset($name) && !$name == '')
{
$result = mysqli_query($connection, "SELECT * FROM `healthsafety` WHERE LOWER (nameinvolved) = LOWER ('$name')");
}
else
{
$result = mysqli_query($connection, "SELECT * FROM `healthsafety` WHERE LOWER (submitbyname) = LOWER ('$subname')");
}
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);

Related

Select query for getting a single value is not working

$sql = "SELECT temail FROM teacherusers WHERE tfullname='$teachername' limit 1";
$result = mysql_query($sql);
$value = mysql_fetch_object($result);
$teacheremail2 = $value->temail;
echo $teacheremail2;
echo $teacheremail2 returns nothing.
$teachername is valid and i have checked multiple times.
It should be a two-dimensional array , you need
$value[0]->temail
The result of mysql_fetch_object($result) is an object(stdClass).
The explanation of object(stdClass) ican be found at this link
$sql = "SELECT temail FROM teacherusers WHERE tfullname='$teachername' limit 1";
$result = mysql_query($sql);
while ($value = mysql_fetch_object($result))
{
$teacheremail2 = $value->temail;
echo $teacheremail2;
}
First off, you'll want to run the query directly against your database to ensure that the query returns some kind of result.
Secondly, if that works, you'll want to echo $value directly to check that you are getting results back on the webpage.
Then you can check if temail is a field of $value
$sql = "SELECT temail FROM teacherusers WHERE tfullname='$teachername' limit 1";
$result = mysql_query($sql);
while ($value = mysql_fetch_object($result))
{
$teacheremail2 = $value->temail;
echo $teacheremail2;
}
hope this help

PHP/MySQL: Passing values from one query to another in PHP multi queries

I have to execute 3 queries inside one PHP file. I have used mysqli_multi_query(). The first 2 queries are SELECT queries which return values for third query (INSERT). So far I have done this;
<?php
$host = "localhost";
$user = "smartbusarrival_grouplog";
$password = "group10#10";
$db = "smartbusarrival_sbaDB";
$u_id = 51;
$b_id = 1;
$t_id = 1;
$date = '2017-06-30';
$startHalt = "Kaduwela";
$endHalt = "Nugegoda";
$seats = array(42,43);
$con = mysqli_connect($host,$user,$password,$db);
$query = "CALL getHaltTag('$t_id','$startHalt');";
$query .= "CALL getHaltTag('$t_id','$endHalt');";
$query .= "INSERT INTO reservation (user_id,bus_id,trip_id,date,start,end) values ('$u_id','$b_id','$t_id','$date','$startTag','$endTag')";
if(mysqli_multi_query($con, $query)){
do{
if($result = mysqli_store_result($con)){
while ($row = mysqli_fetch_array($result)){
$startTag = $row[0];
$endTag = $row[1];
}
mysqli_free_result($result);
}
}
while (mysqli_next_result($con));
}
mysqli_close($con);
?>
First two queries work very well and give correct answers.
Code works just fine when inserting a new record. But the value of start and end are zero.
You can't use multi-query for this, because you're substituting the variables into the third query before you perform the fetch that sets them. Just do them as separate queries.
$query = "CALL getHaltTag('$t_id','$startHalt');";
$result = mysqli_query($con, $query);
$row = mysqli_fetch_row($result);
$startTag = $row[0];
$query = "CALL getHaltTag('$t_id','$endHalt');";
$result = mysqli_query($con, $query);
$row = mysqli_fetch_row($result);
$endTag = $row[0];
$query = "INSERT INTO reservation (user_id,bus_id,trip_id,date,start,end) values ('$u_id','$b_id','$t_id','$date','$startTag','$endTag')";
mysqli_query($con, $query);
In general, there are very few situations where multi-query is really needed, and it usually complicates the code.
And if you change getHaltTag from a stored procedure to a stored function, you don't need 3 separate queries. You could do it in a single query where you call the function:
$query = "INSERT INTO reservation (user_id,bus_id,trip_id,date,start,end)
values ('$u_id','$b_id','$t_id','$date',getHaltTag('$startHalt'),getHaltTag('$endHalt'))";

Need Some Help Regarding Fetching Data from Mysql using explode function

In the below script I want to fetch data from mysql using a explode function and also a variable within an explode function.
Here's how I want to get
<?php
include ('config.php');
$track = "1,2,3";
$i = 1
$trackcount = explode(",",$track);
$sql = "SELECT * FROM tracks WHERE id='$trackcount['$i']'";
$retval = mysql_query($sql, $conn);
while ($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "{$row['track_name']}";
}
mysql_free_result($retval);
?>
This is the code
$sql = "SELECT * FROM tracks WHERE id='$trackcount[$i]'";
I want sql to fetch data from tracks table where id = $trackcount[$i]
Whatever the value of $trackcount[$i] mysql should fetch but it shows a blank screen.
If I put this
$sql = "SELECT * FROM tracks WHERE id='$trackcount[1]'";
It works perfectly
save your $trackcount[$i] in one variable and then pass it in the query as given below
<?php
include ('config.php');
$track = "1,2,3";
$i = 1;
$trackcount = explode(",",$track);
$id=$trackcount[$i];
$sql = "SELECT * FROM tracks WHERE id='$id'";
$retval = mysql_query($sql, $conn);
while ($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "{$row['track_name']}";
}
mysql_free_result($retval);
?>
and one more thing check your previous code with echo of your query and see what is passing ok.
echo $sql = "SELECT * FROM tracks WHERE id='$trackcount['$i']'";//like this
problem is with your query
$sql = "SELECT * FROM tracks WHERE id='$trackcount['$i']'";//change
to
$sql = "SELECT * FROM tracks WHERE id='$trackcount[$i]'";
Generally you would want to use the IN operator with this type of query, so for you this would be:-
$sql="SELECT * FROM `tracks` WHERE `id` in (".$track.");";
or, if the $ids are in an array,
$sql="SELECT * FROM `tracks` WHERE `id` in (".implode( ',', $array ) .");";

can't find multiple values in SQL

I have a DB full of players and I am trying to create a page to register them into a specific tournament. The tournament director will search for players by username (which is only "firstname.lastname").
The problem I'm experiencing is that when I run loop to echo each $players[$x] it only gives the ID for the first matching DB record, and repeats the number once for each match. Rather than returning ID 7, 11, 26 it will return 7, 7, 7. Please can someone explain why?
I have written the following code in a .php file:
session_start();
if (isset($_POST['newsearch']) === true && empty($_POST['newsearch'] === false)){
require 'dbconnect.php';
$term = $_POST['newsearch'];
$terms = "%" . $term . "%";
$query = ("SELECT PlayerID FROM players WHERE Username LIKE '$terms'");
$run_query = mysqli_query($dbcon, $query);
$search = mysqli_fetch_assoc($run_query);
$players = array ();
do{
//Get data from players table
$PlayerID = $search['PlayerID'];
array_push ($players, $PlayerID);
}
while ($dbsearch = mysqli_fetch_assoc($run_query));}
You have more that one fetch for the same query, replace the code after $run_query = mysqli_query($dbcon, $query); with this code:
$players = array ();
while ($dbsearch = mysqli_fetch_assoc($run_query))
{
array_push($players, $dbsearch['PlayerID']);;
}
Your while loop is wrong
$query = ("SELECT PlayerID FROM players WHERE Username LIKE '$terms'");
$run_query = mysqli_query($dbcon, $query);
$search = mysqli_fetch_assoc($run_query);
$players = array ();
do{
//Get data from players table
$PlayerID = $search['PlayerID'];
array_push ($players, $PlayerID);
}
while ($search = mysqli_fetch_assoc($run_query));
}
Put $search instead of $dbsearch
$search = mysqli_fetch_assoc($run_query))
Note : your query is vulnerable to SQLI

sql query working in phpmyadmin but not via mysql_query in php

Well first of all I am French so I hope my question will be understandable ;-)
I know some people have already experienced problems with queries in php that worked in phpmyadmin. The thing is that each time (or so) these people had "echo" their queries and copy/paste in phpmyadmin, but as php does not always display spaces it was always the problem.
Actually my problem is different :
if I use the query
$sql = "SELECT * FROM jos_dtregister_invoice_sent";
$query = mysql_query($sql);
$result = mysql_fetch_array($query);
it returns all the rows in both phpmyadmin and my php code, but if I want to look in a different table (with same structure), it just works in phpmyadmin and not via my php code (only one row instead of all of them)
Here is the query not working:
$sql = "SELECT * FROM jos_dtregister_receipt_sent";
$query = mysql_query($sql);
$result = mysql_fetch_array($query);
Perhaps the answer is very simple but I admit this is kind of tricky for me...
Many thanks in advance!
Here is my complete code :
function sendReceipt($row) {
$to = getUserInformation($row,10);
$from = getEventAdminEmailFromEmail($row);
$subject = getEventTitle($row)." - Invoice #".$row["confirmNum"];
$message = $row["userFirstName"]." ".$row["userLastName"]." \n\n".getMessageToSendUser($row);
$headers = "From: ".$from."\r\n";
$sql1 = "SELECT * FROM `jos_dtregister_invoice_sent`";
$query1 = mysql_query($sql1);
echo 'Fetched rows number: '.mysql_num_rows($query1)."<br />";
while($row1 = mysql_fetch_array($query1)) {
echo "Invoice Sent: ".$row1["sent"]."<br />";
}
$sql2 = "SELECT * FROM `jos_dtregister_receipt_sent`";
$query2 = mysql_query($sql2);
echo 'Fetched rows number: '.mysql_num_rows($query2)."<br />";
while($row2 = mysql_fetch_array($query2)) {
echo "Receipt Sent: ".$row2["sent"]."<br />";
}
}
mysql_fetch_array() fetches only a row.The name suggests that it fetches a result row as an array
$sql = "SELECT * FROM jos_dtregister_receipt_sent";
$query = mysql_query($sql) or die(mysql_error());
$result = mysql_fetch_array($query);
Try to execute this. The mysql_error() line will spit out what exactly went wrong when trying to execute the SQL. Post it back here and we can help you a little more.
$sql = "SELECT * FROM jos_dtregister_receipt_sent";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
// $row will have your data
}
You need to loop over the results with mysql_fetch_array().
while ($result = mysql_fetch_array($query)) {
print_r($result);
}
Or if you want all your results in one big array ($results):
$results = array();
while ($row = mysql_fetch_array($query)) {
$results[] = $row;
}

Categories