I am trying to display results of a mysql query and some html if the first mysql queries coulmn returns false or is set to false. I've tried a few things but I can't seem to get it to work properly, I will show code below. Any help is much appreciated. In the code I want to only display site message if the user's acknowledgement is false otherwise don't display anything.
function siteWideMessage()
{
global $dbh;
$siteMessage = "";
$sUserInfo = $dbh->prepare("
SELECT acknowledgement
FROM user
WHERE uid = :uid
");
$sUserInfo->bindValue(":uid", $_SESSION["uid"]);
if ($sUserInfo->execute()) {
$res = $sUserInfo->fetch();
if ($res["acknowledgement"] = false) {
$stmt = $dbh->query("
SELECT message
FROM SiteWideMessages
ORDER BY idSiteWideMessages DESC
LIMIT 1
");
while ($row = $stmt->fetch()) {
$siteMessage .= "
<div class='siteMessage'>
<span>" . $row["message"] . "</span>
<br><br>
<span style='font-weight:normal;'>I acknowledge that I have read this important site message</span>
<br>
<input type='submit' name='submit' value='I Agree'></input>
</div>";
}
}
$sUserInfo->closeCursor();
}
if (isset($_POST["submit"])) {
$stmt = $dbh->prepare("
UPDATE user
SET `acknowledgement` = 'true'
WHERE uid = :uid
");
$stmt->bindValue(":uid", $_SESSION["uid"]);
if($stmt->execute()) {
$stmt->closeCursor();
}
}
return $siteMessage; }
UPDATE:
I managed to get it working the way I want it to I just had to do as the following.
if ($res["acknowledgement"] == 'false')
Thanks for everyone's help!
You are missing an = in your if statement. It should be:
...
if ($res["acknowledgement"] === false) {
...
Related
I would like to ask, what will be the best way to code using SQL and PHP, on how to check if the input in a textfield matches with a value in an SQL column?
I only have three values in the table. my targets are:
retrieve (POST) the value of the input
check the whole column to see if any matches the "promo code" typed
the "tinyint" used value will turn to 1
echo or affect other database tables if conditions are met
pseudocode will be alright, I would just like the proper procedure.
UPDATE: I tried the solution from #Bitwise Creative, im not getting an echo to appear, which part did i do wrong? also, i got my db where the table is located using a variable.
<form method="get">
<input type="text" name="lux_code" placeholder="ENTER PROMO CODE" style="text-align:center;">
<input type="submit" class="full_width btn color-white mwc-orange-background-color" name="redeem" value="REDEEM">
</form>
<?php
$routePath = "../";
require_once($routePath . "_config/db.php");
$dbConfig = new config_db();
$db = $dbConfig->init();
if (isset($_POST['redeem']) && $_POST['redeem'] == 'REDEEM'){
if (isset($_POST['lux_code']) && $_POST['lux_code']) {
// Short-cutting the DB code for demonstration...
$rows = $db->query('SELECT * FROM promocode_3 WHERE coupon_code = ? AND used = ?', array($_POST['lux_code'], 0));
if (!$rows) {
// Code not found (however you want to handle that...)
echo 'Code not found.';
} else {
// Code found and marked as used in DB
$db->query('UPDATE promocode_3 SET used = ? WHERE coupon_code = ?', array(1, $_POST['lux_code']));
// Additional handling...
echo 'Code accepted!';
}
}
}
?>
Assuming coupon_code has a unique index... Something like:
<?php
if (isset($_POST['code']) && $_POST['code']) {
// Short-cutting the DB code for demonstration...
$rows = $db->query('SELECT * FROM coupons WHERE coupon_code = ? AND used = ?', array($_POST['code'], 0));
if (!$rows) {
// Code not found (however you want to handle that...)
echo 'Code not found.';
} else {
// Code found and marked as used in DB
$db->query('UPDATE coupons SET used = ? WHERE coupon_code = ?', array(1, $_POST['code']));
// Additional handling...
echo 'Code accepted!';
}
}
You can do like this-
$couponcode = $_POST['coupon'];
$sql = "update table_name set used = 1 where coupon_code = $couponcode && used = 0";
The best way is to retrieve all your unused coupon codes and then iterate over the collection and check if the posted value is a match.
I would write a function in my functions.php file as so:
function getCoupons() {
global $db;
try {
$stmt = $db->prepare("SELECT * FROM coupons WHERE `used` = 0");
$stmt->execute();
return $stmt->fetchall();
} catch (Exception $e) {
echo $e->getMessage();
}
}
I would then call the function and store the results into an array in my test.php file like so:
$coupons = getCoupons();
I would also need the posted value, I'll retrieve it like so:
$couponCode = $_POST['coupon'];
I would then iterate over the result set to check for a match in the same file:
$match = false;
foreach($coupons as $coupon){
if($coupon['coupon_code'] == $couponCode){ //check to see if posted value matches
$match = true;
$stmt2 = $db->prepare("UPDATE coupons SET used =
'1' WHERE p3id = :id");
$stmt2->execute(array(
':id'=>$coupon['id']
));
break;
}
}
if($match){
echo 'Coupon code exists!';
} else {
echo 'No Coupon code exists!';
}
I have a query that should look for an entry. If it's not in the database then enter in the data. Otherwise it returns back the data and they can update any fields. If there is an entry it will be only one. This works great if the entry is in the table. But I've tried checking for empty rows, doing row_count, etc and doesn't seem to work. Right now I just have this in the code(sanitized to remove company table information):
$query1 = " SELECT Number, Notes, Qty1, Qty2 FROM test.notes ";
$query1 .= " WHERE Number = '$searchnumber' ";
$result1 = $conn1->query($query1);
$conn1 = null;
if($result1==null)
{
echo "Result is null</p>\n";
return 0;
}
else
{
echo "Result is not null</p>\n";
return $result1;
}
If I take out the if check what I seem to get back is if it's found it returns the values correctly. If it's not found the result seems to be the query string itself. The check doesn't work. Probably because it returns back the query string if it's not found.
I know it's something simple but just haven't found it.
// if available in database
$query="SELECT Number, Notes, Qty1, Qty2 FROM test.notes WHERE Number='".$searchnumber."'";
$qnt = $conn1->query($query);
$coun = count($qnt->fetchAll());
if($coun > 0){
// available
echo "Result is available</p>\n";
}else{
//not available
echo "Result is not available</p>\n";
}
i Think you need something like this.
if this is not working fine, try another aproach
$queryi = $conn1->prepare("SELECT Number, Notes, Qty1, Qty2 FROM test.notes WHERE Number='".$searchnumber."' ");
$queryi->execute();
$qn= $queryi->fetchAll(PDO::FETCH_ASSOC);
foreach ($qn as $row => $data) {
$in_use = $data['Number'];
//echo $in_use ;
}
// evaluate
if($in_use == NULL){
//not avilable
}else{
// available
}
I suggest doing something like this:
Establish your query
$query1 = " SELECT Number, Notes, Qty1, Qty2 FROM test.notes ";
$query1 .= " WHERE Number = '$searchnumber' ";
See if there's a result for the query, and no error
if ($res = $conn1->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
/* Issue the real SELECT statement and work with the results */
$sql = "SELECT name FROM fruit WHERE calories > 100";
foreach ($conn->query($sql) as $row) {
print "Name: " . $row['NAME'] . "\n";
}
}
/* No rows matched -- do something else */
else {
print "No rows matched the query.";
}
}
After some trial and error I got this to work:
$result1 = $conn1->query($query1);
$count = $result1->fetchColumn();
if($count == "")
{
// echo "Result is null</p>\n";
return "0";
}
else
{
// echo "Result is not null</p>\n";
$result1 = $conn1->query($query1);
return $result1;
}
I had to change the setup to include:
$conn1->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, TRUE);
Probably not a clean way but it works for now. Thanks for all the help.
I'm currently having some difficulty with determining if any rows match a specific user id. The code runs fine, but the if statement (if($notifs !== false) always returns true and hence "No notifications found" never displays. How do I write the statement to only check for "receive_id" that match the current session id?
$user_id = $_SESSION['userID'];
if(isset($_POST["view"]))
{
$stmt = $user_notif->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$user_id));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt = $user_notif->runQuery("SELECT * FROM notif_follow WHERE receive_id= ? ORDER BY id DESC LIMIT 5");
$stmt->bindValue(1,$user_id);
$stmt->execute();
$notifs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$notification = '';
if($notifs !== false)
{
foreach($notifs as $notif)
{
$send_id = $notif['send_id'];
$query2 = $user_notif->runQuery("SELECT id FROM following WHERE user1_id=:uid1 AND user2_id=:uid2");
$query2->execute(array(":uid1"=>$user_id,":uid2"=>$send_id));
$query2result = $query2->fetch(PDO::FETCH_ASSOC);
if($query2result !== false){
$follow .= '<button class="button">Remove Channel</button>';
}
else{
$follow .= '<button class="button">Add Channel</button>';
}
$notification .= '
<li>
<div class="notifbox">
<strong style="color: #4b8ed3;">'.$notif["send_name"].'</strong><p style="color: #fff;"> has added you.</p>
'.$follow.'
 <button class="button">View Channel</button>
</div>
</li>
<div class="sectionheader3"></div>
';
}
}
else
{
$notification .= '<li><h2 style="color: #4b8ed3; padding: 10px;">No Notifications Found<h2></li>';
}
fetchAll only returns false if the query failed, but it's not failing. The result is an array. Your best to check if count($notifs) > 0 and also if $notifs === false for the possibility of the query failing.
http://php.net/manual/en/pdostatement.fetchall.php says:
An empty array is returned if there are zero results to fetch, or FALSE on failure.
A query that matches zero rows is not a failure. It's a success at giving you the information that there are zero matching rows.
So you shouldn't compare with $notifs !== false, which compares exactly to the boolean false. You might like to compare with:
if (!$notifs)
This will also test for the empty array.
Try
if ($stmt->RowCount() > 0) {
$notifs = $stmt->fetchAll(PDO::FETCH_ASSOC);
//code here
}
Instead of
$notifs = $stmt->fetchAll(PDO::FETCH_ASSOC);
if($notifs !== false) {
//code here
}
My question to you is how do I get the code below to echo its entirety? I have multiples of these that I need to echo using while and I have toyed with it but have yet to figure out what to do. The answers I have seen, I have tried but they just don't work on my code. I need to have all this code here in one bunch but I am having an issue inserting the "like button" section. The issue starts at
$likes = (empty($_POST['like'])) ? : $_POST['like'] ;
and here's the full code
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo '
<div class="wrapper">
<div class="submissions">
<div class="logo-logo"><h2>Questions.</h2>
<div class="checkboxes">'.$row['formtype'].'
</div>
</div>
<div class="top-submit">
“'. $row["actual_quote"] . '”
</div>
<div class="poster">- '. $row["poster"].'
<div class = "like">- '.
$likes = (empty($_POST['like'])) ? : $_POST['like'] ;
$dislikes = (empty($_POST['dislike'])) ? : $_POST['dislike'] ;
$ip = $_SERVER['REMOTE_ADDR'];
if(isset($_POST['like'])){
$likes1 = $likes+1;
$voted1 = $voted+1;
$query2 = $db->prepare("INSERT INTO voters (voted, ip) VALUES ( :voted, :ip)");
$query2->bindParam(':voted', $voted1, PDO::PARAM_STR);
$query2->bindParam(':ip', $ip, PDO::PARAM_STR);
$query2->execute();
header("Location: like.php?");
$update1 = $db->prepare("INSERT INTO votes (likes) VALUES ( :likes)");
$update1->bindParam(':likes', $likes1, PDO::PARAM_STR);
$update1->execute();
}
if(isset($_POST['dislike'])){
$dislikes1 = $dislikes+1;
$voted1 = $voted+1;
$query2 = $db->prepare("INSERT INTO voters (voted, ip) VALUES ( :voted, :ip)");
$query2->bindParam(':voted', $voted1, PDO::PARAM_STR);
$query2->bindParam(':ip', $ip, PDO::PARAM_STR);
$query2->execute();
header("Location: like.php?");
$update1 = $db->prepare("INSERT INTO votes (dislikes) VALUES ( :dislikes)");
$update1->bindParam(':dislikes', $dislikes1, PDO::PARAM_STR);
$update1->execute();
}
$stmt = $db->query("SELECT * FROM voters");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$row3 = $stmt->fetch();
echo "Likes: $likes <br /> Dislikes: $dislikes<br />";
if(isset($row3['voted'])){
if(isset($row3['ip'])){
echo "You have already voted for this.";
}
} else {
echo "<form action = '' method = 'post'> <input type = 'submit' name = 'like' value = 'like'> <input type = 'submit' name = 'dislike' value = 'dislike'></form>";
}'
</div>
<!-- use select to get the items to stay on the page-->
</div>
</div>
</div>
';
}
There may be a very simple solution but I have searched everywhere for it. I have tried using a . at the end but it doesn't like that. Any suggestions?
EDIT I have changed one portion, the whole code starting at $likes and ending after else{} has been put as this:
<div class = "like">';
include("like.php");
echo'</div>
You don't. You stop your echo, do your other code, and start echoing again.
echo 'foo';
bar();
echo 'baz';
You shouldn't use echo in this way.
Try to keep your HTML in variable and concatenate all needed additional HTML using dot after checking all necessary conditions.
$output = '<div>blahblah</div>';
if ($somedatafromDB == true) {
$output .= '<p>true!!</p>';
} else {
$output .= '<p>false :/</p>';
}
// and finally
echo $output;
An issue might also be the ternary operator:
Your code is currently
$likes = (empty($_POST['like'])) ? : $_POST['like'] ;
Try to change it to
$likes = (empty($_POST['like'])) ? 0 : $_POST['like'];
You need to specify what you would like to return if the $_POST['like'] is empty.
The ternary operator (x?y:z) returns y if x is true, else it returns z. In your case y is missing which might cause an error during execution.
A good practice is ini_set("display_errors", "on"); at the beginning of the script for debugging purposes.
I highly appreciate that you try to help me.
My problem is this script:
<?php include("inc/incfiles/header.inc.php"); ?>
<?php
$list_user_info = $_GET['q'];
if ($list_user_info != "") {
$get_user_info = mysql_query("SELECT * FROM users WHERE username='$list_user_info'");
$get_user_list = mysql_fetch_assoc($get_user_info);
$user_list = $get_user_list['username'];
$user_profile = "profile.php?user=".$user_list;
$profilepic_info = $get_user_list['profile_pic'];
if ($profilepic_info == "") {
$profilepic_info = "./img/avatar.png";
}
else {
$profilepic_info = "./userdata/profile_pics/".$profilepic_info;
}
if ($user_list != "") {
?>
<br>
<h2>Search</h2>
<hr color="#FF8000"></hr>
<div class="SearchList">
<br><br>
<div style="float: left;">
<img src="<?php echo $profilepic_info; ?>" height="50" width="50">
</div>
<?php echo "<h1>".$user_list."</h1>"; ?>
</div>
<?php
}
else {
echo "<br><h3>User was not found</h3>";
}
}
else {
echo "<br><h3>You must specify a search query</h3>";
}
?>
I am creating a search script that takes the mysql databse information and shows the result associated to the search query. My script is the above, but keep in mind the sql connection is established in an extern scipt.
The problem is that i want the script to first check if the user is found with the search query in the username row, and then get the entre information from that user and display it. If the user is not found with the username query, it should try and compare the search query with the name row, and then with the last name row. If no result is displayed it should then return an else statement with an error, e.g. "No user wsas found"
Yours sincerely,
Victor Achton
Do the query as Muhammet Arslan ... but just counting the rows would be faster ...
if(mysql_num_rows($get_user_info)){
//not found
}
you should add a "Limit 1" at the end if you are just interested in one result (or none).
But read about prepared statements
pdo.prepared-statements.php
This is how it should be done in 2013!
Something like this but you don't need 3 queries for this. you can always use OR in mysql statements
$handle1 = mysql_query("SELECT * FROM users WHERE username = $username"); // Username
if (($row = mysql_fetch_assoc($handle1) !== false) {
// username is found
} else {
$handle2 = mysql_query("SELECT * FROM users WHERE name = $name"); // name
if (($row = mysql_fetch_assoc($handle2) !== false) {
// name is found
} else {
$handle3 = mysql_query("SELECT * FROM users WHERE lastname = $lastname"); // Last name
if (($row = mysql_fetch_assoc($handle3) !== false) {
// last name is found
} else {
// nothing found
}
}
}
Already you did ,but you can improve it by using "AND" or "OR" on ur sql statement.
$get_user_info = mysql_query("SELECT * FROM users WHERE username='$list_user_info' or name = '$list_user_info' or last_name = '$list_user_info'");
$get_user_list = mysql_fetch_assoc($get_user_info);
if(empty($get_user_list))
{
echo "No User was found";
}
and you should control $list_user_info or u can hacked.
Here some adapted copy pasting from php.net
Connect
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
fetch data
$stmt = $dbh->prepare("SELECT * FROM users where name LIKE '%?%'");
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
the rest is your programing ...
And do some reading it's very dangerous to use copied code without understanding !