Using data from sql table within condition in PHP - php

I am very new to coding.
I am trying to select data from a table in SQL then use this data as part of a condition in a PHP If statement. The code I am using appears below. The echo $row["endsequence"]; line shows the correct value has been retrieved from the database, but the record isn't being updated as I need it to be in the final part of code. Any help much appreciated.
<?php
$result = filter_var($_GET['result'], FILTER_SANITIZE_STRING);
$action = filter_var($_GET['action'], FILTER_SANITIZE_STRING);
$pupilid = filter_var($_GET['pupilid'], FILTER_SANITIZE_NUMBER_INT);
$pathwayid = filter_var($_GET['pathwayid'], FILTER_SANITIZE_NUMBER_INT);
$stageid = filter_var($_GET['stageid'], FILTER_SANITIZE_NUMBER_INT);
$resourceid = filter_var($_GET['resourceid'], FILTER_SANITIZE_NUMBER_INT);
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "planit";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql = "SELECT endsequence FROM resources WHERE id= " . $resourceid;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["endsequence"];
}
} else {
echo "0 results";
}
if ($result == 'fail' && $action == 'tryagain' && $row['endsequence'] == "2") {
$sql1 = "UPDATE pupils SET activeresourceid = (SELECT nextresourceid FROM resources WHERE id=$resourceid) WHERE id=$pupilid";
}
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
if ($conn->query($sql1) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
mysqli_close($conn);
?>

Related

Accessing two tables within same statement?

I'm trying to create an upvote system where, after checking to see if you're logged in and after getting your userid, it checks if the table has your userid with the postid already in it and if it does then it means it was already upvoted. I just want to know what's wrong in my code, this is being used for learning, I don't need any complex thing.
Code:
if (isset($_GET['upvote'])) {
if ($_SESSION["loggedin"] == true) {
$upvoteid = $_GET["upvote"];
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id FROM users WHERE username=".$_SESSION["loggedinusername"];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$userid = $row["id"];
}
$sql2 = "SELECT userid, postid FROM upvotedposts WHERE userid='".$userid."' AND postid='".$upvoteid."'";
$result2 = $conn->query($sql);
if (!$result2->numrows > 0) {
$sql = "UPDATE posts SET upvotes = upvotes + 1 WHERE id = ".$upvoteid;
if ($conn->query($sql) === TRUE) {
echo "Sucessfully upvoted";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
} else {
echo "Failed;
}
$conn->close();
}
}
When I do click the upvote button, it simply does nothing. The issue here is that as far as I know it looks like it would work but I may be forgetting something that I am unaware of or incorrectly using something.
You are missing a closing "
echo "Failed;
should be:
echo "Failed";

php echo result from mysql and datetime selection

MySQL database Start = "2017-03-29 01:30:00"
The problem is:
I print the $SQL and search the record in MySQL database, it can search the record. However, I need to debug and test if there is no result, it will be expected to echo "No". But, it always to echo "Yes" no matter I can get the record in MySQL or not.
How can I fixed it.
Main purpose: Get the record if there are and Echo "No" if there don't have record
<?php
$serverName = "localhost";
$username = "root";
$password = "";
$dbName = "fyp";
$tbName = "events";
$String_start = '2017-03-29 01:28:00';
$String_end = '2017-03-29 01:32:00';
$conn = new mysqli($serverName, $username, $password, $dbName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//$staffID = $_SESSION['userID'];
$staff_ID = '15207800';
$sql = "SELECT *
FROM `$tbName`
WHERE `start` BETWEEN ('$String_start') AND ('$String_end')";
echo $sql;
$result=mysqli_query($conn,$sql);
if($result)
{
echo "Yes";
}
else{
echo "no";
}
?>
Mysql query only return fails if there is an issue, for successful execution it returns TRUE even if there is no record. You can achieve with follwing way
<?php
$serverName = "localhost";
$username = "root";
$password = "";
$dbName = "fyp";
$tbName = "events";
$String_start = '2017-03-29 01:28:00';
$String_end = '2017-03-29 01:32:00';
$conn = new mysqli($serverName, $username, $password, $dbName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//$staffID = $_SESSION['userID'];
$staff_ID = '15207800';
$sql = "SELECT *
FROM `$tbName`
WHERE `start` BETWEEN ('$String_start') AND ('$String_end')";
echo $sql;
$result=mysqli_query($conn,$sql);
$num_rows = mysqli_num_rows($result);
if($num_rows > 0)
{
echo "Yes";
}
else{
echo "no";
}
?>
Use mysqli_num_rows that will return total results returned by the query. If total > 0 then results found else no results.
To fetch rows from MySQL result set, use mysqli_fetch_assoc
$result = mysqli_query($conn,$sql);
// $result contains result set and will return `TRUE` if query was successfully executed
// and will return `FALSE` only in case of error
$total = mysqli_num_rows($result);
if($total > 0)
{
echo "Yes";
// Fetch rows from mysql result set
while($row=mysqli_fetch_assoc($result))
{
print_r($row);
}
}
else
{
echo "no";
}

"Can't use function return value in write context" when using mysqli_num_rows()

I've been working on adding users to my database and I tried to do something to check if login is already occupied. If it's not, PHP should add the user to database, else give alert that login is already used. Here's my code:
<?php
$servername = 'localhost';
$username = 'wiktor';
$password = 'wiktor';
$database = 'something';
$login = $_POST['login'];
$passwd = $_POST['pass'];
$name = $_POST['name'];
$surname = $_POST['sur'];
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Error " . $conn->connect_error);
} else {
echo "Connect success <br>";
}
$check = "select login from users where login = '$login'";
$test = $conn->query($check);
if(mysqli_num_rows($test) = 0){
$sql = "insert into users
values (null,'$login','$passwd','$name','$surname')";
if ($conn->query($sql) === TRUE) {
echo "Success";
} else {
echo "Error " . $sql . "<br>" . $conn->error;
}
} else {
echo "The login is already in use!";
}
$conn->close();
?>
I'm getting "Can't use function return value in write context" on line
if(mysqli_num_rows($test) = 0)
which checks if there are any records with that login.
I used something similar before and it worked perfectly so what could be the problem now?
Write this
if(mysqli_num_rows($test) == 0)
Instead of,
if(mysqli_num_rows($test) = 0)

database updating using php

well i just made a form in HTML witch accepts user inputs and a mysql database to store them, now in the php file everything goes well no errors but the problem is the data never displays in the database, here is the php file:
<?php
if(isset($_POST["submitacc"])){
$servernm = "localhost";
$serverusrnm = "root";
$serverpass = "2003";
$db = "blue";
$conn = new mysqli($servernm, $serverusrnm, $serverpass, $db);
if($conn ->connect_error){
die("connection failed".$conn->connect_error);
}
$fnm = $_POST["fnm"];
$lnm = $_POST["lnm"];
$mail = $_POST["mail"];
$pass = $_POST["pass"];
$age = $_POST["age"];
$gender = $_POST["gender"];
if(isset($_POST["gender"])&&$_POST["gender"]=="male"){
$gender = "male";
}else {
$gender = "female";
}
$mysql="update createacc set fnm = '$fnm', lnm = '$lnm', mail = '$mail', passwod = '$pass', age = '$age', gender = '$gender' ";
if($conn->query($mysql)== true){
echo "record updated";
}else {
echo "error updating record".$conn->error;
}
$conn->close();
}
?>
Use mysqli_query() instead of query(). Also use WHERE clause in your $mysql variable. The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated!
Example:
if(mysqli_query($conn , $mysql)){
echo "Records were updated successfully.";
} else {
echo "ERROR: Could not able to execute $mysql. " . mysqli_error($conn);
}

Query MySQL table based on form post

I'm working on a web form that allows the user to conduct a zip code search. My intent is to use the form post to search a MySQL table for the matching zip code then return content from an associated field in the same row.
I can get as far as... form submits and directs user to the intended form_post.php page. If I enter <?php echo $_POST["zipcode"]; ?> on the page it returns the content submitted by the user.
I followed the PHP/MySQLi examples from these pages:
http://www.w3schools.com
/php/php_mysql_connect.asp
/php/php_mysql_select.asp
/php/php_if_else.asp
I am able to connect to the database and return the 2 selected values from the table. This is my example so far:
<?php
$servername = "localhost";
$username = "db_username";
$password = "db_password";
$dbname = "db_name";
if (isset($_POST['zipcode'])) {
$zipcode = $_POST['zipcode'];
}
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT zip_code, area FROM zipcode_table WHERE zip_code = $zipcode";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Result: " . $row["zip_code"]. " " . $row["area"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
After the query returns the associated values I would like to determine if the returned value from 'area' is one of 3 values then forward the user to the appropriate url.
I was working on an if/else statement as follows then got stuck.
if($result == "A") {
header("Location: http://example.com/page-1/");
}
elseif($result == "B") {
header("Location: http://example.com/page-2/");
}
elseif($result == "C") {
header("Location: http://example.com/page-3/");
} else {
header("Location: http://example.com/");
exit();
}
Any recommendations are appreciated.
you are using $result in if but, you not assign it area region.So, first relpace this:
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Result: " . $row["zip_code"]. " " . $row["area"]. "<br>";
}
} else {
echo "0 results";
}
with this:
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Result: " . $row["zip_code"]. " " . $row["area"]. "<br>";
$result = $row["area"];
break;
}
} else {
echo "0 results";
$result = "";
}
then replace query:
$sql = "SELECT zip_code, area FROM zipcode_table WHERE zip_code = $zipcode";
with this:
$sql = "SELECT zip_code, area FROM zipcode_table WHERE zip_code = '$zipcode'";
then your problem will be solved.

Categories