SELECT COUNT * SQL PHP doesn't work - php

I have to search if a postal code is in my database, my table is called "test" there is only one table in my database with one column and one row, the column is named "codes", and there is an only row with the INT 63000, i have a form in my website where client enter a code, and it called a .php file which check if the value is missing or present in the database, i don't know PHP so it's hard for me... :( And my code don't work :(
SOLVED : THIS IS THE WORKING CODE :
<?php session_start(); ?>
<?php
if($_POST['code-postal'] === '') {
$hasError = true;
} else {
$variable = $_POST['code-postal'];
$code = intval($variable);
}
mysql_connect('xxxxxxxxx', 'xxxxxxxxxxxx', 'xxxxxxxxxxxx')
or die("I cannot connect to the database because: " . mysql_error());
mysql_select_db('xxxxxxxxxx');
$code = mysql_real_escape_string($code);
$sql = "SELECT COUNT(*) AS total_count FROM test WHERE codes='$code'";
$req = mysql_query($sql) or die('Erreur SQL !<br>'.$sql.'<br>'.mysql_error());
$data = mysql_fetch_assoc($req);
if($data['total_count'] == 1) {
$verif = true;
}
else {
$verif = false;
}
// on ferme la connexion à mysql
mysql_close();
?>

$sql = "SELECT COUNT(*) AS total_count FROM test WHERE codes='$code'";
$req = mysql_query($sql) or die('Erreur SQL !<br>'.$sql.'<br>'.mysql_error());
$data = mysql_fetch_assoc($req);
if($data['total_count'] == 1) {
$verif = true;
}
else {
$verif = false;
}
Here is the working code.
mysql_query would return result set. You will need to use mysql_fetch_assoc function to retrieve data from that.
I guess you would have more rows in table in future, because as you mentioned in table that you have only one table with one column and one row, then there is no need of database, you can directly compare values.

Related

How to update status in database if status is empty without submitting a form in php?

How to update a status from database if status is empty in using php? I have this condition in php. I have this if condition that decides if $getstatus is empty it will update from database to Avail. I tried refreshing the page after querying the database. But it will not update in database. Is there anyway to update this without using form submit in php?
<?php
session_start();
include "includes/connection.php";
// Display all parking slots
$sql = $connection->prepare('SELECT * FROM parkingslot where parkingslotid = 1');
$sql->execute(); // execute query
$result = $sql->get_result(); // fetch result
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$getstatus = $row["status"];
echo $getstatus;
}
}
if (empty($getstatus)) {
$sql = $connection->prepare("UPDATE parkingslot SET status = 'Avail' where parkingslotid = 1 ");
}
?>
Codes in connection for connecting to database
connection.php
<?php
$server = "localhost";
$username = "root";
$password = "";
// create connection
$connection = mysqli_connect($server,$username,$password);
// check connection
if(!$connection)
{
die("No connection found." . mysqli_connect_error());
}
else {
// select a database
$select_db = mysqli_select_db($connection,'smartparkingsystem');
if(!$select_db)
{
$sql = 'CREATE DATABASE sample';
// create database if no db found
if(mysqli_query($connection,$sql)) {
echo "Database Created";
}
else {
echo "Database not found" . mysqli_connect_error() . '\n';
}
}
else {
// Database already existed
// do nothing...
}
}
?>
If I understand your goal of: For row(s) whereparkingslotid=1 - Update status to 'Avail' but only if status is not currently set, this might help:
<?php
session_start();
include "includes/connection.php";
$connection->prepare("UPDATE `parkingslot` SET `status`=? WHERE `parkingslotid`=? AND (`status` IS NULL OR `status`=?)");
$connection->bind_param("sis", $status, $parkingslotid, $empty_str);
$status = 'Avail';
$parkingslotid = 1;
$empty_str = '';
$connection->execute();
echo $connection->affected_rows.' rows affected';
$connection->close();
?>
This saves a bit of processing by not checking with PHP first.
You can use this query:
"UPDATE parkingslot SET status = 'Avail' where status IS NULL OR status = '' "
Edited:
#lumonald gave the right anwser in the comment. You're not executing your second SQL statement.

Data Not inserting into table PHP

The data is not inserting into another table, here's the code below :
if (isset($_POST))
{
$job = $_POST['jobtitle'];
$dur = $_POST['duration'];
$deg = $_POST['requireddegree'];
$exp = $_POST['experiance'];
$sal = $_POST['salary'];
$mark = $_POST['marks'];
if ( !empty($job) && !empty($dur) && !empty($deg) && !empty($exp) && !empty($sal) && !empty($mark))
{
$dur = mysql_real_escape_string($dur);
$deg= mysql_real_escape_string($deg);
$exp = mysql_real_escape_string($exp);
$sal = mysql_real_escape_string($sal);
$mark = mysql_real_escape_string($mark);
$job = mysql_real_escape_string($job);
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('".$dur."','".$deg."','".$exp."','".$sal."','".$mark."','".$job."') ";
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
With this it gives me server error or there was an error in CGI script.But when I write the variables in this form '$dur' instead of '".$dur." then the else conditon runs after insert query and displays data is not inserted.
However, i have written the same logic while inserting data in my another table and it inserts successfully.But there I put '$dur'.
I can't find the problem.Will be glad for your suggestions :)
I can't seem to find any other error by seeing this code expect for
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('$dur','$deg','$exp','$sal','$mark','$job') ";
//Use ".$job." only for stuff like '".md5($_POST['password'])."' otherwise this creates problem some times.
// Adding this always helps
if(!mysqli_query($con,$query))
{
die('error'.mysqli_error($con));
}
// in $con = $con=mysqli_connect("localhost","root","");
else
{
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
I think by making these changes and making sure that your db name and other basic stuff are correct then you should be good to go otherwise, specify your exact error.

How to check if record is already exists before creating a new record?

I'm trying to implement a duplicate topic blocking system to a forum script. Since I'm extremely poor about PHP I though maybe you'd like to help me. Unfortunately, I'm not even sure if I'm trying to edit the right part of the script but here's the code:
// If it's a new topic
if ($fid)
{
$subject = pun_trim($_POST['req_subject']);
if ($pun_config['o_censoring'] == '1')
$censored_subject = pun_trim(censor_words($subject));
if ($subject == '')
$errors[] = $lang_post['No subject'];
else if ($pun_config['o_censoring'] == '1' && $censored_subject == '')
$errors[] = $lang_post['No subject after censoring'];
else if (pun_strlen($subject) > 70)
$errors[] = $lang_post['Too long subject'];
else if ($pun_config['p_subject_all_caps'] == '0' && is_all_uppercase($subject) && !$pun_user['is_admmod'])
$errors[] = $lang_post['All caps subject'];
}
So I'm trying to implement if $subject is exist in DB (SELECT * FROM topics WHERE subject), show an error in this format: $errors[] = $lang_post['Topic is already exist'];
Thank you.
There are several ways of getting the information that it is in the database or not(here i'm using PDO)
This is the common code:
$conn = new PDO('mysql:dbname=db_name', 'username', 'password')
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
fetch->(PDO::FETCH_NUM)
$sql = $conn->prepare("query_to_db");
$sql->execute();
$rows = $sql->fetch(PDO::FETCH_NUM);
if( $row > 0 ){
echo "the credentials exists";
}
else{
// there is nothing like this in the database
}
mysql error code 23000
try{
// connection code above mentioned
$sql = $conn->prepare("query_to_db");
$sql->execute();
}
catch(PDOException $e){
if($e->getCode() == 23000){
// the credentials exists
}
else{
// doesn't exists
}
}
rowCount()
$sql = $conn->prepare("query_to_db");
$sql->execute();
$count = $sql->rowCount();
if($rowCount > 0){
//exists in the db
}
else{
//it doesn't exists in the db
}
But the rowCount doesn't in mysql
The php doc says:
For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use DOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.
I personally prefer the fetch->(PDO::FETCH_NUM) as it is more precise than the other.

Member search function

Im trying to come up with MySQL logic for a search function I got on my page. Its a simple form where the user can choose to fill in search criteria. The criteria(s) is send as arguments to a function that generates the mysql logic. This is whats inside the PHP controller file:
case 'search':
if((empty($_POST['username'])) && (empty($_POST['firstname'])) && (empty($_POST['lastname']))
&& (empty($_POSt['agemin'])) && (empty($_POST['agemax'])) && (empty($_POST['country']))){
$members = get_all_username();
} else {
if(isset($_POST['username'])){
$otheruser = $_POST['username'];
} else { $otheruser = null; }
if(isset($_POST['agemin'])){
$ageMin = $_POST['agemin'];
} else { $ageMin = null; }
if(isset($_POST['agemax'])){
$ageMax = $_POST['agemax'];
} else { $ageMax = null; }
if(isset($_POST['country'])){
$country = $_POST['country'];
} else { $country = null; }
//if(isset($_POST['isonline']))
$members = search_members($otheruser, $ageMin, $ageMax, $country);
}
include('displaySearch.php');
break;
So if nothing is set a complete list of all the members is generated and displayed. This is the function that is called if any of the inputs is set:
function search_members($username, $ageMin, $ageMax, $country){
global $db;
$query = "SELECT username FROM profiles WHERE username = :username
AND age > :ageMin AND age < :ageMax AND country = :country";
$statement = $db->prepare($query);
$statement->bindValue(':username', $username); $statement->bindValue(':ageMin', $ageMin);
$statement->bindValue(':ageMax', $ageMax); $statement->bindValue(':country', $country);
$statement->execute();
if($statement->rowCount() >= 1){
return $statement->fetchAll();
} else {
return false;
}
}
The mysql logic is obviously wrong. I need a set of conditions (in the MySQL logic if possible) that checks the PHP variables for value and if there is none it should not be accounted for when querying the database. So if only the username is set in the form the other variables should not be included in the SQL logic.
I've looked up the MySQL IF() condition but Im still not able to come up with proper code that does what I need. If someone could point me in the right direction I would be able to do the rest myself. Any other approach for solving this kind of problem is also welcome.
If i understand your problem, then the simple way is to use if else to build sql query, for example
$sql = "SELECT username FROM profiles WHERE 1 "
if (!is_null($username)) {
$sql .= " AND username = :username ";
}
// All other checks

PHP Function within a function within a loop :S

Firstly, Thaks for taking a look at my question.
I have a function that works perfectly for me, and I want to call another function from within that function however I'm getting all kinds of issues.
Here are the functions then I'll explain what I'm needing and what I'm running into.
They are probably very messy, but I'm learning and thought I'd try get fancy then clean it up.
function GetStation($id){
$x_db_host1="localhost"; // Host name
$x_db_username1="xxxx"; // Mysql username
$x_db_password1="xxxx"; // Mysql password
$x_db_name1="xxxx"; // Database name
// Connect to server and select databse.
mysql_connect("$x_db_host1", "$x_db_username1", "$x_db_password1");
mysql_select_db("$x_db_name1");
// SQL Query Setup for Station Name
$sql="SELECT * FROM stations WHERE ID = $id LIMIT 1";
$result=mysql_query($sql);
while($rows=mysql_fetch_array($result)){
$retnm = $rows['CallSign'];
}
mysql_close();
echo $retnm;
} // Closes Function
// List Delegates Function!!!!!!!!!!!!!!!!!!!
function ListDelegates(){
$x_db_host1="xxx"; // Host name
$x_db_username1="xxx"; // Mysql username
$x_db_password1="xxxx"; // Mysql password
$x_db_name1="xxxx"; // Database name
// Connect to server and select databse.
mysql_connect("$x_db_host1", "$x_db_username1", "$x_db_password1");
mysql_select_db("$x_db_name1");
$q = "SELECT * FROM delegates";
$result = mysql_query($q);
/* Error occurred, return given name by default */
$num_rows = mysql_numrows($result);
if(!$result || ($num_rows < 0)){
echo "Error displaying info";
return;
}
if($num_rows == 0){
echo "There are no delegates to display";
return;
}
/* Display table contents */
echo "<table id=\"one-column-emphasis\" summary=\"Delegates\"><thead>";
echo "<thead><tr><th>ID</th><th>Name</th><th>Station</th><th>Spec Req</th><th>BBQ</th><th>DIN</th><th>SAT</th><th>SUN</th></tr>";
echo "</thead><tbody>";
for($i=0; $i<$num_rows; $i++){
$d_id = mysql_result($result,$i,"DID");
$d_name1 = mysql_result($result,$i,"DFName");
$d_name2 = mysql_result($result,$i,"DLName");
$d_name = $d_name1 . " " . $d_name2;
$d_spec1 = mysql_result($result,$i,"DSpecRe");
$StatNm = mysql_result($result,$i,"DStation");
$d_st_name = GetStation($StatNm);
if ($d_spec1=="0"){ $d_spec = "-"; }
else {$d_spec = "YES"; }
$d_bbq1 = mysql_result($result,$i,"Dbbq"); // BBQ
if ($d_bbq1=="0"){ $d_bbq = "-"; }
else {$d_bbq = "NO"; }
$d_din1 = mysql_result($result,$i,"Dconfdinner"); // Dinner
if ($d_din1=="0"){ $d_din = "-"; }
else {$d_din = "NO"; }
$d_sat1 = mysql_result($result,$i,"DConfSat"); // Saturday
if ($d_sat1=="0"){ $d_sat = "-"; }
else {$d_sat = "NO"; }
$d_sun1 = mysql_result($result,$i,"DConfSat"); // Sunday
if ($d_sun1=="0"){ $d_sun = "-"; }
else {$d_sun = "NO"; }
echo "<tr><td>$d_id</td><td><strong>$d_name</strong></td><td>$d_st_name</td><td>$d_spec</td><td>$d_bbq</td><td>$d_din</td><td>$d_sat</td><td>$d_sun</td></tr>";
}
echo "</tbody></table></br>";
}
So I output ListDelegates() in a page and it displays a nice table etc.
Within ListDelegates() i use the GetStation() function.
This is because the table ListDelegates() uses contains the station ID number not name so I want GetStation($id) to output the station name
The problem I'm having is it seems GetStation() is outputting all names in the first call of the function so the first row in the table and is not breaking it down into each row and just one at a time :S
Here's what I think (I'm probably wrong) ListDelegates() is not calling GetStation() for each row it's doing it once even though it's in the loop. ??
I have no idea if this should even work at all... I'm just learning researching then trying things.
Please help me so that I can output station name
At the end of GetStation, you need to change
echo $retnm;
to
return $retnm;
You are printing out the name from inside the function GetStation, when you are intending to store it in a variable. What ends up happening, is that the result of GetStation is effectively echo'ed on the screen outside of any table row. Content that is inside a table but not inside a table cell gets collected to the top of a table in a browser. If you want to see what I mean, just view source from your browser after loading the page.
You don't need to connect to the database in each and every function. Usually you do the database connection at the top of your code and use the handle (in PHP the handle is usually optional) throughout your code. I think your problem is because when you call the function each time it makes a new connection and loses the previous data in the query.
My dear first of all you should place your code of connection with local host and database globally. It should be defined only once. you are defining it in both function.
something like this, and as suggested, you should have connection to database established somewhere else
function ListDelegates(){
$x_db_host1="xxx"; // Host name
$x_db_username1="xxx"; // Mysql username
$x_db_password1="xxxx"; // Mysql password
$x_db_name1="xxxx"; // Database name
// Connect to server and select databse.
mysql_connect("$x_db_host1", "$x_db_username1", "$x_db_password1");
mysql_select_db("$x_db_name1");
$q = "SELECT * FROM delegates";
$result = mysql_query($q);
/* Error occurred, return given name by default */
$num_rows = mysql_numrows($result);
if(!$result || ($num_rows < 0)){
echo "Error displaying info";
return;
}
if($num_rows == 0){
echo "There are no delegates to display";
return;
}
/* Display table contents */
echo "<table id=\"one-column-emphasis\" summary=\"Delegates\"><thead>";
echo "<thead><tr><th>ID</th><th>Name</th><th>Station</th><th>Spec Req</th><th>BBQ</th><th>DIN</th><th>SAT</th><th>SUN</th></tr>";
echo "</thead><tbody>";
for($i=0; $i<$num_rows; $i++){
$d_id = mysql_result($result,$i,"DID");
$d_name1 = mysql_result($result,$i,"DFName");
$d_name2 = mysql_result($result,$i,"DLName");
$d_name = $d_name1 . " " . $d_name2;
$d_spec1 = mysql_result($result,$i,"DSpecRe");
$StatNm = mysql_result($result,$i,"DStation");
$d_bbq1 = mysql_result($result,$i,"Dbbq"); // BBQ
$d_din1 = mysql_result($result,$i,"Dconfdinner"); // Dinner
$d_sat1 = mysql_result($result,$i,"DConfSat"); // Saturday
$d_sun1 = mysql_result($result,$i,"DConfSat"); // Sunday
//$d_st_name = GetStation($StatNm);
$sql="SELECT * FROM stations WHERE ID = $StatNm LIMIT 1";
while($rows=mysql_fetch_array($result)){
$d_st_name = $rows['CallSign'];
}
if ($d_spec1=="0"){ $d_spec = "-"; }
else {$d_spec = "YES"; }
if ($d_bbq1=="0"){ $d_bbq = "-"; }
else {$d_bbq = "NO"; }
if ($d_din1=="0"){ $d_din = "-"; }
else {$d_din = "NO"; }
if ($d_sat1=="0"){ $d_sat = "-"; }
else {$d_sat = "NO"; }
if ($d_sun1=="0"){ $d_sun = "-"; }
else {$d_sun = "NO"; }
echo "<tr><td>$d_id</td><td><strong>$d_name</strong></td><td>$d_st_name</td><td>$d_spec</td><td>$d_bbq</td><td>$d_din</td><td>$d_sat</td><td>$d_sun</td></tr>";
}
echo "</tbody></table></br>";
}

Categories