pg_fetch_assoc returning 1 after values - postgresql

I am beginner in PHP, i am working with session and pg functions. So i want to return user's first name and last name from database(basically user's details) and display it to different page using session. and it is returning using pg_fetch_assoc() but the problem is like it is showing 1 after every value like (firstname 1), (lastname 1). How can i fix it. is there any other way to return values from database and display it and also use these values as conditions.
Thanks
Below is my code:
$login = trim($_POST['login']);
$pass = trim($_POST['pass']);
$result = pg_execute($conn, "login_query", array($login, hash(HASH_ALGO, $pass)));
$records = pg_num_rows($result);
if($records == 1){
$_SESSION['user_id'] = $login;
$row = pg_fetch_assoc($result);
$_SESSION['first_name'] = $row['first_name'];
$_SESSION['last_name'] = $row['last_name'];
$_SESSION['last_access'] = $row['last_access'];
$_SESSION['user_type'] = $row['user_type'];
//$_SESSION['details'] = $row;
pg_execute($conn, "update_query", array($login));
/* $_SESSION['output'] = $output();*/
$_SESSION['output'] = "Welcome back " . pg_fetch_result($result,0,"first_name") . pg_fetch_result($result,0,"last_name").'</br>';
$_SESSION['output'] .= "Our records show that your </br>" . "email address is " . pg_fetch_result($result,0,"email_address") . "</br>";
$_SESSION['output'] .= "and you last accessed our system: " . pg_fetch_result($result,0,"last_access") . "</br>";
header('location: ./user-dashboard.php');
}
here is var_dump($row); value:
array(9) { ["user_id"]=> string(20) "jdoe " ["password"]=> string(32) "179ad45c6ce2cb97cf1029e212046e81" ["user_type"]=> string(2) "c " ["email_address"]=> string(256) "jdoe#gmail.com " ["first_name"]=> string(128) "John " ["last_name"]=> string(128) "Doe " ["birth_date"]=> string(10) "1998-02-05" ["enrol_date"]=> string(10) "2017-01-01" ["last_access"]=> string(10) "2017-10-18" }
database

pg_fetch_assoc returns values OK. you can see it in result of var_dump($row); - see the ["last_name"]=> string(128) "Doe " - it has extra space - yes, but not 1. So another bit of code adds 1 after $row["last_name"] value.

<h1 class="floating-box" ><?php echo print_r($_SESSION['first_name'],True); ?></h1>
<h1 class="floating-box" ><?php echo print_r($_SESSION['last_name']); ?></h1>
<h1 class="floating-box" ><?php echo print_r($_SESSION['last_access']); ?></h1>
Sorry, i forgot to add true in print_r() function. Thanks for your help. #Vao Tsun

Related

Sql-injection error

I am trying to do SQL-injection attack on a local website on my localhost. I am trying to get all the products from product table using the wildcard ';-- but there seems to be some problem with the query. It's giving me this error
'Warning: mysqli_fetch_assoc() expects parameter 1 to be
mysqli_result, boolean given in C:\wamp64\www\tplus\products.php on
line 151'
Here is my PHP code
<?php
//$search_value = mysqli_real_escape_string($conn,$_GET['search']);
$search_value = $_GET['search'];
$result = mysqli_query($conn,"SELECT * FROM products where p_name LIKE '%".$search_value."%'");
while ($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>";
echo $row['p_name'];
echo "</td>";
echo "<td>";
echo $row['p_price'];
echo "</td>";
echo "<td>";
echo $row['p_brand'];
echo "</td>";
echo "<td>";
echo $row['p_info'];
echo "</td>";
echo "</tr>";
}
?>
Try this
if (!$result) {
die(echo 'MySQL Error: ' . mysqli_error())
}
You need to check if
"SELECT * FROM products where p_name LIKE '%".$search_value."%'"
is a valid SQL statement.
The indication is that it is not - hence the error.
Perhaps output that string and check where the SQL statement is incorrect.

Read multiple entries with a Where clause

I tried to build a User search function but i ran into a problem a while ago. My function, which looks like this:
"Select id, username FROM users WHERE username LIKE '%search%'"
Is showing me only the user Janamaris ( userlist is a bit lower )
but as you see jns.drws has also a j in his username ( J = $search ).
So my Problem now i want to show all users with a J in his/her username
So how can i get all users with WHERE?
My Signed Users are [id, username]
Tolkosino
47, Janamaris
48, TheCrazyMan
49, jns.drws
Beispiel einer Foreach Schleife bzw. While Schleife Posten?
English: Can someone post an example of a foreach e.g. while loop?
The sql is fine and will get all rows you need:
"Select id, username FROM users WHERE username LIKE '%search%'"
If you have problems with upper/lower case then read this:
https://stackoverflow.com/a/2876820/4916265
Example with while
if($result = $mysqli->query($sql)){
if(is_object($result)){
while($row = $result->fetch_assoc()){
echo "<div id=\"content-b\">";
echo "<p class=\"usrsrch\">User ID : " . $row['id'] . "";
echo "<br>";
echo "<p class=\"usrsrch\">Username : . $row['username'] . "";
echo "</div>";
}
} else {
echo 'nix gefunden';
}
}

vBulletin 3.8: How to display array values in templates

My problem in here (probably) is that $db->fetch_array won't show all the results from the db. I don't know what happens but I just get 1 of the 3 results, I tried many things even I changed the query a bit. Do you have any ideas why I can't get all the results in here?
It's for vBulletin 3.8 btw.
Thanks people.
if ($_REQUEST['do'] == 'showthis') {
$rel = $db->query_first("
SELECT *
FROM " . TABLE_PREFIX . "anexampletable
WHERE fromuserid OR touserid = " . $vbulletin->userinfo['userid'] . "
AND confirmstatus =1
");
if ($rel) {
$queryrel = $db->query_read("
SELECT *
FROM " . TABLE_PREFIX . "anexampletable
WHERE fromuserid OR touserid = " . $vbulletin->userinfo['userid'] . "
AND confirmstatus =1
");
while ($queryre = $db->fetch_array($queryrel)) {
if ($queryre['reltype'] == '1') {
$ty = " is something else ";
} else if ($queryre['reltype'] == '2') {
$ty = " is something ";
} else if ($queryre['reltype'] == '3') {
$ty = " is something else ";
} else if ($queryre['reltype'] == '4') {
$ty = " is something ";
} else if ($queryre['reltype'] == '5') {
$ty = " is something ";
} else if ($queryre['reltype'] == '6') {
$ty = " is something ";
} else if ($queryre['reltype'] == '7') {
$ty = " is something ";
} else if ($queryre['reltype'] == '8') {
$ty = " is something ";
} else if ($queryre['reltype'] == '9') {
$ty = " is something ";
} else if ($queryre['reltype'] == '10') {
$ty = " is something ";
} else if ($queryre['reltype'] == '11') {
$ty = " is something else ";
} else if ($queryre['reltype'] == '12') {
$ty = " is something else ";
} else if ($queryre['reltype'] == '13') {
$ty = " is something ";
} else if ($queryre['reltype'] == '14') {
$ty = " is something ";
} else {
$ty = " is default ";
}
$sender = $queryre['fromusername'];
$receiver = $queryre['tousername'];
$showit = $sender . $ty . $receiver;
}
eval('print_output("' . fetch_template('relationships') . '");');
}
}
Your query is saying:
WHERE `fromuserid` has any value
OR (touserid = $vbulletin->userinfo['userid']).
If you want the rows where either fromuserid matches the userid or touserid matches the userid, try this:
$queryrel = $db->query_read("
SELECT * FROM " . TABLE_PREFIX . "anexampletable
WHERE (fromuserid = " . $vbulletin->userinfo['userid'] . ")
OR (touserid = " . $vbulletin->userinfo['userid'] . ")
AND confirmstatus =1
");
Update:
It's hard to determine the problem without knowing the data you're working with. I've created a test that outputs the data your code is working with, you'll be able to see what the individual parts of your query are returning and then can determine where the problem lies.
Modify your file temporarily by placing this code just before the code in your example (you'll need to use the correct table name). Then edit your question and paste the output at the bottom.
echo "vBulletin User ID = " . $vbulletin->userinfo['userid'];
$test_query1 = $db->query_read("
SELECT * FROM " . TABLE_PREFIX . "anexampletable
WHERE (fromuserid = " . $vbulletin->userinfo['userid'] . ")
");
$t1_count = 0;
echo "Test From User ID Results<br />";
while ($test1_output = $db->fetch_array($test_query1)) {
$t1_count++;
echo "Test From User Result " . $t1_count . "<br />";
echo "From User ID = " . $test1_output['fromuserid'] . "<br />";
echo "To User ID = " . $test1_output['touserid'] . "<br />";
echo "Confirm Status = " . $test1_output['confirmstatus'] . "<br />";
echo "Relationship Status = " . $test1_output['reltype'] . "<br />";
}
$test_query2 = $db->query_read("
SELECT * FROM " . TABLE_PREFIX . "anexampletable
WHERE (touserid = " . $vbulletin->userinfo['userid'] . ")
");
$t2_count = 0;
echo "<br /><br />Test To User ID Results<br />";
while ($test2_output = $db->fetch_array($test_query2)) {
$t2_count++;
echo "Test To User Result " . $t2_count . "<br />";
echo "From User ID = " . $test2_output['fromuserid'] . "<br />";
echo "To User ID = " . $test2_output['touserid'] . "<br />";
echo "Confirm Status = " . $test2_output['confirmstatus'] . "<br />";
echo "Relationship Status = " . $test2_output['reltype'] . "<br />";
}
exit();
Final Code?
It appears that there were two problems:
1) The query needed to be modified:
Original:
fromuserid OR touserid = " . $vbulletin->userinfo['userid'] . "
Updated:
(fromuserid = " . $vbulletin->userinfo['userid'] . "
OR
touserid = " . $vbulletin->userinfo['userid'] . ")
Updated 07/05/2012
2) You can't loop through arrays in vb3 templates, so we'll concatenate strings.
The $showit variable being output for use in the template is a string. It's being overwritten by each successive pass through the while loop so that only the last result is sent to the template. Instead of using $showit = xxx;, use $showit .= xxx; with .=.
I've updated the last 15 lines or so of the code below.
You can look at how the forum page is generated to learn more.
Open the upload\forumdisplay.php file. The while loop that creates the list of threads starts here:
upload\forumdisplay.php(962)
while ($thread = $db->fetch_array($threads))
The output for each thread is generated using the "threadbit" template and added to the $threadbit string here:
upload\forumdisplay.php(1000)
eval('$threadbit .= "' . fetch_template('threadbit') . '";');
The "FORUMDISPLAY" template is output at the end:
upload\forumdisplay.php(1056)
eval('print_output("' . fetch_template('FORUMDISPLAY') . '");');
If you look at the FORUMDISPLAY template, you'll find that the $threadbit string is used about 1/5 from the beginning.
Try the code below and see how it works, I replaced the series of else if statements with a switch() statement. It's more efficient.
if ($_REQUEST['do'] == 'showthis') {
// Make standalone query, easy to output query string and run it directly for testing
$rel_sql = "SELECT * FROM " . TABLE_PREFIX . "anexampletable
WHERE (fromuserid = " . $vbulletin->userinfo['userid'] . "
OR touserid = " . $vbulletin->userinfo['userid'] . ")
AND confirmstatus =1";
$queryrel = $db->query_read($rel_sql);
if ($db->num_rows($queryrel))
{
while ($queryre = $db->fetch_array($queryrel))
{
switch ($queryre['reltype'])
{
case 1:
$ty = " do something 1 ";
break;
case 2:
$ty = " do something 2 ";
break;
case 3:
$ty = " do something 3 ";
break;
// Add as many cases as needed
.......
case xxx:
$ty = " do something xxx ";
break;
.......
default:
$ty = " is default ";
}
$sender = $queryre['fromusername'];
$receiver = $queryre['tousername'];
// UPDATED FROM HERE DOWN on 07/05/2012
// Add to $showit with ".=" rather than overwriting it with "=".
// Method One
// If the output is simple, try this.
// I added a line break after each entry.
$showit .= $sender . $ty . $receiver . "<br />";
OR
// Method Two
// If the output is complex.
// Create a separate template and store the output in $showit
// Remember to add the new template to the $actiontemplates array.
eval('$showit .= "' . fetch_template('showit') . '";');
}
eval('print_output("' . fetch_template('relationships') . '");');
}
}

Access Form values in my Symfony executeAction backend

So one of my pages consists of a quiz form that has several questions of type multiple choice, the choices are specified as radio buttons. I have been scanning the Symfony documentation to find out how to access form field values inputted by the user. Thing is, this isn;t a doctrine or propel based form, and neither do I require the values to be stored in the database, hence executing a $form->save() makes little sense to me. But I do require access to specific values of my form in my backend once the user hits submit.
Most of Symfony documentation that i have run into doesn't necessarily explain how this can be done. I would assume it would be something to the effect of :
$request->getParameter( 'radio_choices_id selected value ').
Thanks to all who read this and Cheers to the ones who respond to it :)
Parijat
Hm, it is very simple if I understand your question right)
For widget:
$this->widgetSchema['name'] = new sfWidgetFormChoice(array('choices' => array('ch_1', 'ch_2')));
Ok,in action:
$this->form = new FaqContactForm();
if ($request->isMethod('post')) {
$this->form->bind($request->getParameter($this->form->getName()));
if ($this->form->isValid()) {
$your_val=$this->form->getValue('name');
//or
$your_val=$this->form['name']->getValue());
}
}
In backend in protected function processForm(sfWebRequest $request, sfForm $form)
you have
$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
if ($form->isValid())
{
$notice = $form->getObject()->isNew() ? 'The item was created successfully.' : 'The item was updated successfully.';
try {
$product = $form->save();
} catch (Doctrine_Validator_Exception $e) {
$errorStack = $form->getObject()->getErrorStack();
$message = get_class($form->getObject()) . ' has ' . count($errorStack) . " field" . (count($errorStack) > 1 ? 's' : null) . " with validation errors: ";
foreach ($errorStack as $field => $errors) {
$message .= "$field (" . implode(", ", $errors) . "), ";
}
$message = trim($message, ', ');
$this->getUser()->setFlash('error', $message);
return sfView::SUCCESS;
}
Before $product = $form->save(); try
$your_val=$form->getValue('name');
//or
$your_val=$form['name']->getValue());

Redisplaying a form with fields filled in

I need a bit of help with redisplaying a form.
Basically, currently a user will fill out my contact form, the form and it's contents are passed to my verification page, and if the recaptcha was entered correctly it goes to a Thank You page.
When the recaptcha is entered INCORRECTLY, I want to redisplay the contact form with the fields already filled out. How do I do this? (As you'll see below, it currently goes to google on incorrect captcha)
Here is my verification code. Any help would be great:
<?php require('sbsquared.class.php'); ?>
<?php
require_once('recaptchalib.php');
$privatekey = "myprivatekey";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
header("Location: http://www.google.com"); <--- this is the bit that I want to redisplay the form with fields already filled out.
} else {
$sb = New SBSquared;
$name = $_POST['FullName'];
$post_keys = array_keys($_POST);
$my_db_string = "<table>";
$ip_address = $_SERVER['REMOTE_ADDR'];
foreach($post_keys as $field)
{
if($_POST[$field] != "" && $field != "submit_y" && $field != "submit_x" && $field != "submit_x")
{
$my_db_string .= "<tr><td><b>".$field.":</b></td><td>";
if($field == "Email")
{
$my_db_string .= ''.$_POST['Email'].'';
}
else
{
$my_db_string .= $_POST[$field];
}
$my_db_string .= "</td></tr>";
}
}
$my_db_string .= "<tr><td><b>IP ADDRESS LOGGED: </b></td><td>".$ip_address."</td></tr>";
$my_db_string .= "</table>";
if(get_magic_quotes_gpc() != 1)
{
$my_db_string = addslashes($my_db_string);
$name = addslashes($name);
}
$conn = $sb->openConnection();
$dts = time();
$sql = "INSERT INTO `contact_queries` VALUES ('', '$name', '$my_db_string', 'n/a', 0, $dts)";
$result = mysql_query($sql, $conn) or die(mysql_error());
$content = '<div id="main_middle">';
$content .= '<span class="title">'.$sb->dt('Contact').'</span>
<p>'.$sb->dt('Thank you for your enquiry. We will contact you shortly.').'</p>
</div>';
// admin auto email.
$dts = date("d.m.y h:ia", time());
$admin_content = "New contact query at $dts";
$admin_content .= "\n\n--\n\n \r\n\r\n";
mail("email address", 'NOTIFICATION: new query', $admin_content, 'From: email address');
$FILE=fopen("./log/auto-contact.txt","a");
fwrite($FILE, $admin_content);
fclose($FILE);
echo pageHeader($sb);
echo pageContent($sb, $content);
echo pageFooter($sb);
}
?>
You probably already answered this for yourself, but if not you can set ReCaptcha to validate prior to submitting the form, much the same as HTML5 validation. It just won't let the user submit until the Captcha is correct. Now, I don't know if it will refresh the captcha if it is incorrect but most of the time I see people putting it into an iFrame so it doesn't refresh the page when refreshing the captcha.
As an alternative, you can use sessions to keep the data filled in.