postgresql select query with variables - php

I am trying to make a postgresql select query work with php, but can't get past the syntax.
I have a variable and a query that returns the surname of any match.
$name = 'Smith';
$query = 'SELECT surname FROM emploee WHERE name= '.$name.';';
$a = pg_query(connect(),$query );
while($row = pg_fetch_array($a)){ echo "Match"; }
For those who wonder why do I have to declare Smith as a variable, $name is not always equals to Smith. The value of $name is taken correctly from another query. However, this is not working. I read in an article that I should use pg_query_params() but couldn't get that to work neither.
Your help would be highly appreciated

Try this :
$query = "SELECT surname FROM emploee WHERE name= '" . $name . "';";
And the best way without binding :
$query = sprintf("SELECT surname FROM emploee WHERE name = '%s'", pg_escape_string($name));
And if you want to use binding :
$result = pg_query_params(connect(), 'SELECT surname FROM emploee WHERE name = $1', array($name));
As you get a result from other query ' Smith', there is a white space.
To remove white space from $name, you can do : $name = trim($name);

These are the two methods that worked, suggested by Bang and Frank Heikens respectively. Since they only commented, I am posting it as an answer for those who might come up the same situation. However, I would strongly advise them to read the comments too. I learned a couple of stuff on the way, you might as well.
Bang's suggestions->
$a = trim($name);
$query = "SELECT surname FROM employee WHERE name= '" . $a . "';";
$result = pg_query(connect(), $query);
while($row = pg_fetch_array($result)){ echo "Match"; }
Frank Heikens suggestions ->
$n = trim($name);
$s = trim($surname);
$params = array ($n, $s);
$result = pg_query_params(connect(), 'SELECT office FROM emploee WHERE name = $1 and surname = $2', $params);
while($row = pg_fetch_array($result)){ $k = $row['path']." ".$row['office']; echo $k; }
In both cases I have to use trim (not sure if this will be your case too). I added a third field office to demonstrate how can I take several arguments.
If anyone has other critics, suggestions or solutions, be my guest. I will try everyone of them and let you know.

With this code above: you can print "match" for each record matched with query
$a = trim($name);
$query = "SELECT surname FROM employee WHERE name= '" . $a . "';";
$result = pg_query(connect(), $query);
while($row = pg_fetch_array($result)){ echo "Match"; }
But certainly you need to print the values returned:
just make it echo $row['columnName']
Full details here:https://w3resource.com/PostgreSQL/select.php

Related

How to fix invisible value for php variable inside input field

I'm trying to display the users nickname into a html form input text field. It was working, but now quit showing up randomly. There is data in the database for the user. The fields are just blank and show nothing. I have plenty other fields working, but this does not and idk why. Feel free to edit the title I did not know how to word it.
When I try to implode the $nickname
$string_nickname = implode(',', $nickname);
I get the error
Warning: implode(): Invalid arguments passed in
C:\xampp\htdocs\Client-Projects\Crossfire\CoinSubmission.php on line
26
So, I tried parsing it to just a string since it's not an array, like..
$string_nickname = $nickname['nickname'];
But when I do this the field in the form is just completely blank and it gives no error.
Here is the input field where I insert nickname.
<label>NICKNAME:</label>
<input type="text" name="nickname" id="nickname" value="<?php echo $string_nickname; ?>" readonly>
and where I select and set nickname.
$result = mysqli_query($con,"SELECT adminlogin.nickname FROM adminlogin INNER JOIN coinsub ON coinsub.profileid=adminlogin.profileid") or die(mysqli_error($con));
$nickname = mysqli_fetch_assoc($result);
$string_nickname = implode(',', $nickname);
Please let me know if you need anymore info.
$string_nickname = '';
if(!empty($nickname)){
$string_nickname = implode(',', $nickname);
}
Do it with object orientated mysqli
$arr = array();
while ($row = $result->fetch_assoc()) {
$arr[] = $row['nickname'];
}
$string_nickname = implode(',', $arr);
You are fetching one value, I think you need more than one. Just create a new array, push to it and you are done. Even if you have one value in the database, this works The above array contains all the nicknames we get from the database. Once you implode them, they are like
nickname1, nickname2, nickname3, nicknamen
So your whole code becomes something like this
$result = $con->query("SELECT adminlogin.nickname FROM adminlogin INNER JOIN coinsub ON coinsub.profileid=adminlogin.profileid") or die(mysqli_error($con));
$arr = array();
while ($row = $result->fetch_assoc()) {
$arr[] = $row['nickname'];
}
$string_nickname = implode(',', $arr);
If you want to implode try this :
$string_nickname = implode(', ', (array)$nickname);
For select mysqli try this :
$selectquery = $con->prepare("SELECT adminlogin.nickname FROM adminlogin
LEFT JOIN coinsub ON coinsub.profileid=adminlogin.profileid");
$selectquery->execute();
$result = $selectquery->get_result();
$user = $result->fetch_assoc();
$nickname = $user['nickname'];
You can also use while statement as follow :
while($user=$result->fetch_assoc()){
echo $user['nickname'];
}

Get rid of the last comma when echoing a row?

// This gets all the users that are active
// The limit is completely random, it is set to 2 for this example
$sql = <<<SQL
SELECT *
FROM `accounts`
WHERE active = 1
LIMIT 2
SQL;
if(!$getaccounts = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
while ($row = $getaccounts->fetch_assoc()) {
$getid = $row["id"].',';
$getid = substr($getid, 0, -1);
$getusername = $row["username"];
$getpassword = $row["password"];
echo $getid;
echo $getusername."<br>";
echo $getpassword."<br>";
}
I know this hasn't been prepared but I am not using it for anything other than personal use.
I cannot understand why this is not getting rid of the last comma?
The output may be something like "32,14,"
And I want to get rid of the last comma by using the "substr" function.
But the output that that I get from $getid is "3214" (It gets rid of all the commas instead of just the last one.
I need it to output "32,14" but it's not working?
Could someone please tell me where I am going wrong?
If I do rtrim, it does the same thing and gets rid of all the commas! I am going to update something in the database using the ids, and that is why I need to get rid of the last comma
And I know this code is not secure, I am not using it for anything other than personal use and I was hoping someone could help me figure this out, I have been attempting it for days, it seems really simple and I bet I am missing something really stupid!
You have a XY Problem.
You want to concat all the id's into a comma-seperated string.
Here's a much easier solution by adding the items to an array and then implode().
<?php
// rest of your code
$ids = Array();
while ($row = $getaccounts->fetch_assoc()) {
$ids[] = $row["id"];
$getusername = $row["username"];
$getpassword = $row["password"];
echo $getusername."<br>";
echo $getpassword."<br>";
}
echo "ids: " . implode(",",$ids);
You should write code like..
$getid = "";
while ($row = $getaccounts->fetch_assoc()) {
$getid .= $row["id"].',';
}
$getid = rtrim($getid,',');
$q = " UPDATE accounts SET active = '0' WHERE id IN ($getid) ";

How to get array difference in php using arrays with two elements

So, I have two queries which will pull out data from the database. However, I need to use these data to get the array difference by using php. I want to send both employeeName and designation into an array and then get the difference. The below code I have used does not work as expected. Any solution for this matter ?
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
include_once 'config.php';
$sql1 = "SELECT employeeName, designation FROM t2o_mappings WHERE type = '". $_GET['type'] ."' AND employeeCompany = '".$_GET['employeeCompany']."'"; //System Data;
$sql2 = "SELECT employeeName, designation FROM mappings_view WHERE uNo = '" . $_GET['uNo'] . "' AND uCompany = '" . $_GET['uCompany'] . "' AND type = '". $_GET['type'] ."' AND employeeCompany = '".$_GET['employeeCompany']."'"; //App Data;
//WHERE uNo = '".$_GET['uNo']."' AND uCompany = '".$_GET['uCompany']."'
$result1 = sqlsrv_query($conn, $sql1);
$result2 = sqlsrv_query($conn, $sql2);
$row1 = [];
$row2 = [];
while ($rs1 = sqlsrv_fetch_array($result1, SQLSRV_FETCH_ASSOC)) {
$row1[] = $rs1['employeeName, designation'];
}
while ($rs2 = sqlsrv_fetch_array($result2, SQLSRV_FETCH_ASSOC)) {
$row2[] = $rs2['employeeName, designation'];
}
print_r($row1);
print_r($row2);
$HaveSysNoApp = array_diff($row1, $row2); //Have in System, Not in App
$HaveAppNoSys = array_diff($row2, $row1); //Have in App, Not in System
echo 'HaveSysNoApp';
print_r($HaveSysNoApp);
echo '$HaveAppNoSys';
print_r($HaveAppNoSys);
?>
You have a syntax problem here
$row1[] = $rs1['employeeName, designation'];
The right way would be :
$row1[] = [
$rs1['employeeName'],
$rs1['designation']
];
But array_diff() throws the notice "array to string conversion" because it can only deals with one dimension. The PHP array_diff() documentation contains this note :
Note:
Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In other words: when the string representation is the same.
Since you have multidimensional arrays to compare, you could use the array_filter() function.
For example :
$HaveSysNoApp = array_filter($row1, function ($item) use ($row2) {
return !in_array($item, $row2);
});
You could do it directly in database with this query (the opposite check would be similar):
SELECT system.employeeName, system.designation
FROM t2o_mappings AS system
WHERE system.type = ?
AND system.employeeCompany = ?
AND NOT EXISTS (
SELECT NULL
FROM mappings_view AS app
WHERE app.employeeName = system.employeeName
AND app.designation = system.designation
AND app.type = system.type
AND app.uNo = ?
AND app.uCompany = ?
)
These question marks make it parametrized query, wich prevents SQL injection (parameter values are not part of the query, so they can't change its meaning). You would call it with additional parameter array (order must match):
$params = [
$_GET['type'],
$_GET['employeeCompany'],
$_GET['uNo'],
$_GET['uCompany']
];
$haveSysNoAppResult = sqlsrv_query($conn, $sql, $params);

Explode array from mysql and assign to variables PHP

OK so in the database I have a column that contains data like this
:Novice:Intermediate:Advanced
( some columns have more than the 3 listed above )
What I'm trying to do is explode at the : and then assign the exploded values to variables
At most there are 4 bits of data separated by : so a max of 4 variables
Here is the code I have so far
$query = mysql_query("SELECT * FROM venues",$dbc);
$result = mysql_fetch_assoc($query);
do{
$eventtype = explode(':',$result['def_sessions']);
list($var1, $var2, $var3, $var4) = $eventtype;
//print_r(explode(":",$result['def_sessions']));
echo $var1.'<br>'.$var2.'<br>'.$var3.'<br>'.$var4;
}while($result = mysql_fetch_assoc($query));
It works ( to an extent )
For example record ID 13 has this in the column
:Novice:Novice/Intermediate:Intermediate/Advanced:Advanced:
The output however does NOT display the final
Advanced
it only displays
Novice
Novice/Intermediate
Intermediate/Advanced
Anyone help me please I am pulling hair out badly here .
I have also tried adding another $var5 but that doesnt help
I forgot to add $var5 to the list()
$query = mysql_query("SELECT * FROM venues WHERE id ='30'",$dbc);
$result = mysql_fetch_assoc($query);
do{
$eventtype = explode(':',$result['def_sessions']);
list($var1, $var2, $var3, $var4,$var5) = $eventtype;
//print_r(explode(":",$result['def_sessions']));
echo $var1.'<br>'.$var2.'<br>'.$var3.'<br>'.$var4.'<br>'.$var5;
}while($result = mysql_fetch_assoc($query));
Working fine now :)
do it like this
$query = mysql_query("SELECT * FROM venues",$dbc);
$result = mysql_fetch_assoc($query);
$i=0;
while($result = mysql_fetch_assoc($query)){
$var1[$i]=$row['Novice'];
$var2[$i]=$row['Intermediate'];
$var3[$i]=$row['Advanced '];
echo $var1[$i].'<br>'.$var2[$i].'<br>'.$var3[$i].'<br>';
$i++;
}
Your problem it´s how you are trying to get the values from the table and explode.
I use something like this:
$query = mysql_query("SELECT * FROM venues",$dbc);
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($result)) {
$def_sessions = row(number of yor row);
$eventtype = explode(":", def_sessions);
$val0 = $eventtype[0];
$val1 = $eventtype[1];
...
}

online server wont show string values

i have this code, where i get an array and make it a string, on my localhost show the values correctly (1,2...) but on my online server shows (,,) no numbers, just the commas. Does someone know what this issue may be?
Heres my code
<?php
error_reporting(E_ALL);
CONECTION
$sql = "select id from table where id=1";
$result = mysql_query( $sql);
$myArray= array() ; //Here you must declare it as array
while($row = mysql_fetch_array($result)){
$popurl = $row['id '];
$myArray[] = $popurl;
}
$string = "" . implode(", ", $myArray) . "" ;
echo $string;
?>
Please need help
It's a simple typo problem:
$row['id '] is not defined. Correct it to $row['id'] and you should be fine.

Categories