I have table named books, this table will store the data of each book . each book has 5 pages only and each page has different details which belong to the same book. the name of the book stored in a column named "jalad" and the pages stored in a column named "sanad"
I want PHP allows to me inserted a new book after totally completing the insertion of the first book which has five-page and in case I entered less than 5 pages then will stop me to insert a new book before completing the first one. Any idea, please. I used this code but it does not work perfectly. Please any help.
table here :
The code:
<?php
// connect to the database
// $serverName = "SALARY_SERVER\SALARY_SERVER";
//$database = "roatb";
$serverName = "LENOVO";
$database = "tt";
$connectionInfo = array( "Database"=>$database );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn )
{
echo "Connection established.\n";
}
else
{
echo "Connection could not be established.\n";
die( print_r( sqlsrv_errors(), true));
}
$jalad1 = $_POST['jalad'];
$sanad2 = $_POST['sanad'];
$sql = "SELECT count(Sanad) as countnumber FROM books where Jalad='$jalad1' ";
$stmt = sqlsrv_query( $conn, $sql );
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
$rowc= $row['countnumber'];
echo $rowc;
if ($rowc <=5) {
$sql = "INSERT INTO books (Jalad,Sanad)
VALUES ('$jalad1','$sanad2' )";
// echo $sql;
if (sqlsrv_query($conn, $sql)) {
echo "your data saved";
}
else {echo "error";}
}
else {
echo"you have to complete the page of the current book";
}
}
?>
You need to select 'jalad' of the last uploaded book. you can do that however you want, but let's say you store the column value in a variable named $jalad_last
you just need to make your if statement like this
if ($rowc == 0 || $rowc < 5 && $jalad1 == $jalad_last) {
YOUR INSERT CODE HERE
} elseif ($rowc == 5) {
echo 'this book is already completed';
} else {
echo 'you have to complete...';
}
Related
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.
I have used someone else's code that uses the ipaddress way. However, I would like to use a code that checks for the current userid and the id number.
$ipaddress = md5($_SERVER['REMOTE_ADDR']); // here I am taking IP as UniqueID but you can have user_id from Database or SESSION
/* Database connection settings */
$con = mysqli_connect('localhost','root','','database');
if (mysqli_connect_errno()) {
echo "<p>Connection failed:".mysqli_connect_error()."</p>\n";
} /* end of the connection */
if (isset($_POST['rate']) && !empty($_POST['rate'])) {
$rate = mysqli_real_escape_string($con, $_POST['rate']);
// check if user has already rated
$sql = "SELECT `id` FROM `tbl_rating` WHERE `user_id`='" . $ipaddress . "'";
$result = mysqli_query( $con, $sql);
$row = mysqli_fetch_assoc();//$result->fetch_assoc();
if (mysqli_num_rows($result) > 0) {
//$result->num_rows > 0) {
echo $row['id'];
} else {
$sql = "INSERT INTO `tbl_rating` ( `rate`, `user_id`) VALUES ('" . $rate . "', '" . $ipaddress . "'); ";
if (mysqli_query($con, $sql)) {
echo "0";
}
}
}
//$conn->close();
In your database table, set the user_id column as UNIQUE KEY. That way, if a user tries to cast a second vote, then the database will deny the INSERT query and you can just display a message when affected rows = 0.
Alternatively, (and better from a UX perspective) you can preemptively do a SELECT query for the logged in user before loading the page content:
$allow_rating = "false"; // default value
if (!$conn = new mysqli("localhost", "root","","database")) {
echo "Database Connection Error: " , $conn->connect_error; // never show to public
} elseif (!$stmt = $conn->prepare("SELECT rate FROM tbl_rating WHERE user_id=? LIMIT 1")) {
echo "Prepare Syntax Error: " , $conn->error; // never show to public
} else {
if (!$stmt->bind_param("s", $ipaddress) || !$stmt->execute() || !$stmt->store_result()) {
echo "Statement Error: " , $stmt->error; // never show to public
} elseif (!$stmt->num_rows) {
$allow_rating = "true"; // only when everything works and user hasn't voted yet
}
$stmt->close();
}
echo "Rating Permission: $allow_rating";
And if they already have a row in the table, then don't even give them the chance to submit again.
I'm building a php site where i want the user to create his company.
The script is checking if the user has any companies registered already and then it should display if he does or doesn't.
If he doesnt have a registered company, he should see a form where he can register.
If he choose to register a company the script will check for any company with the same name or insert the row.
My only problem is that when there's already a company with that name the echo doesnt display.
I have written inside the code where the problem is.
<?php
$con=mysqli_connect("mysql","USER","PASS","DB");
if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
$result_get_companies = mysqli_query($con,"SELECT * FROM companies WHERE userid='". $login_session ."' ORDER BY companyid ASC") or die(mysqli_error());
if (mysqli_num_rows($result_get_companies) >= 1) {
while($row_companies = mysqli_fetch_array( $result_get_companies )) {
$result_get_company_owner = mysqli_query($con,"SELECT username FROM users WHERE userid='". $login_session ."'") or die(mysqli_error());
$company_owner = mysqli_fetch_assoc($result_get_company_owner);
echo 'THIS WORKS';
}
} else {
if (isset($_POST['create_first_company']) && !empty($_POST['company_name'])) {
$company_name_unsafe = mysqli_real_escape_string($con, $_POST['company_name']);
$company_name = preg_replace("/[^a-zA-Z0-9\s]/","",$company_name_unsafe );
$check_companies = "SELECT companyid FROM companies WHERE company_name='". $company_name ."'";
$what_to_do_companies = mysqli_query($con,$check_companies);
if (mysqli_num_rows($what_to_do_companies) != 0) {
echo 'THIS DOESNT WORK
It does register that is should go here
because it does not insert new row.
and when the value is = 0 it does go
to else ELSE below and insert row.';
} else {
$result_create_company = mysqli_query($con,"INSERT INTO companies (companyname)
VALUES ('". $login_session ."')")
or die(mysqli_error());
echo 'THIS WORKS';
}
} else {
echo 'THIS WORKS!';
}
}
?>
Ok so I wrote some code to find records on a test database, it works if there is a record and does display the data, if there is no record it still says that it found stuff. It should say it did not. It even finds stuff that is not in the database but obviously has no data to display, its annoying.
I need a new pair of eyes.
I think the error is here:
$sql = "SELECT * FROM Kittenzz
WHERE KittenID='".$_POST['KittenID']."';";
$result = mysql_query($sql, $connection);
But just in case here is the full code minus the login credentials to the db.
<?php
if(isset($_POST['Find']))
{
$connection = mysql_connect("Login Info Deleted");
// Check connection
if (!$connection)
{
echo "Connection failed: " . mysql_connect_error();
}
else
{ //else 1
//select a database
$dbName="Katz";
$db_selected = mysql_select_db($dbName, $connection);
//confirm connection to database
if (!$db_selected)
{
die ('Can\'t use $dbName : ' . mysql_error());
}
else
{ //else 2
if ($_POST[KittenID]=='')
{
$OutputMessage = 'Must add a Kitten-ID';
}
else
{//exception else
$sql = "SELECT * FROM Kittenzz
WHERE KittenID='".$_POST['KittenID']."';";
$result = mysql_query($sql, $connection);
while($row = mysql_fetch_array($result))
{
$Name = $row['Name'];
$KittenID = $row['KittenID'];
$KittenAge = $row['KittenAge'];
$Email = $row['Email'];
$Comments = $row['Comments'];
$Gender = $row['Gender'];
$Passive = $row['Passive'];
$Playful = $row['Playful'];
$Activity = $row['Activity'];
}
if ($result)
{
$OutputMessage = 'Record Found';
//echo "<p>Record found<p>";
}
else
{
$OutputMessage = 'RECORD NOT FOUND';
}
}//exception else
}//else 2 end
}//else 1 end
mysql_close($connection);
}
?>
if ($result)
{
$OutputMessage = 'Record Found';
}
There is your mistake, that means if the query executed successfully (even with 0 records) you are saying records found. You should only say that if the number of records returned are more than 0.
if (mysql_num_rows($result)>0)
{
$OutputMessage = 'Record Found';
}
But the bigger problem with your code can be solved by this reading
How can I prevent SQL injection in PHP?
This may happen, because if $_POST['KittenID'] is empty, the sql query would look like : SELECT * FROM Kittenzz WHERE KittenID=""; you have to change the above if statement to:
if (!isset($_POST[KittenID]) || empty($_POST[KittenID]) || $_POST[KittenID]=='')
{
$OutputMessage = 'Must add a Kitten-ID';
}
This question already has answers here:
Get number of rows in SQL-Server with PHP
(2 answers)
Closed 9 years ago.
I know there have been lots of questions about this but I need some specific help, I'm new to sql and php, so sorry for bad coding and poor indenting. What I am trying to do is count the number of rows to a specific column then when I find out how many have this id from this column then I would like it to send this number back to the php page. ATM I am using a like query I don't want this effected.
My layout is 3 pages the index the part choices and the part location, the user inputs a part number into the index page which is then searched against the database which then displays the parts that match or are like the users input on the part choices page. then you click on the part you want and then it takes you to the locations page and showing the closest locations for this part.
What I am trying to do is when the user puts in the part number a query runs and searches the database counting the number of rows that have or are like the input, then outputs the parts like it usually does, but what i want to happen is if there is only one row with that part number i want it to say row = 1 so i can then run an if statement using this value. i have looked into different code and cant quiet find what I'm looking for these are the examples I have found and have tryied to modify for what I need. but i have had no luck.
$query = "SELECT (column) FROM table WHERE column = value";
2.$results = mysql_query($query);
3.$rows = mysql_num_rows($results);
4.echo $rows ;
seperate code below
<?php
$serverName = "serverName\instanceName";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT FirstName, LastName FROM SomeTable";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
echo $row['LastName'].", ".$row['FirstName']."<br />";
}
sqlsrv_free_stmt( $stmt);
?>
i would like the code or query to be within the php that i have, any ideas would be great or examples sorry about poor english many thanks
my code for my page is below:
<!DOCTYPE html>
<head>
<meta name="viewport" content="width=device-width, user-scalable=false;">
<script type="text/javascript">
function submit()
{
document.getElementById("start").click(); // Simulates button click
document.submitForm.submit(); // Submits the form without the button
}
</script>
</head>
<body>
<?php
try {
$serverName = "188.64.188.89";
$connectionInfo = array( "Database"=>"tdStoreLocator", "UID"=>"odbcAdmin", "PWD"=>"Midnight1Midnight1");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false )
{
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT TOP 10 [company]
,[partnum]
,[description]
FROM [tdStoreLocator].[odbcadmin].[Part]
WHERE Part.partnum LIKE ? or Part.description LIKE ?";
/* Set parameter values. */
$params = array( "%" . str_replace(" ","%",$_POST["part"] ). "%", "%" . str_replace(" ","%",$_POST["part"] ) . "%");
$i = 0;
$x = true;
/*echo print_r($params, true);*/
$stmt = sqlsrv_query( $conn, $sql, $params );
if( $stmt === false)
{
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
if($x == true)
{
echo"<form id=\"submitForm\" action=\"locations.php\" method=\"post\">";
echo"<input type=\"hidden\" name=\"part\" id=\"3\" value=\"".$row['partnum']."\">";
echo"<input type=\"hidden\" name=\"lon1\" id=\"1\" value=\"".$_POST["lon1"]."\">";
echo"<input type=\"hidden\" name=\"lat1\" id=\"2\" value=\"".$_POST["lat1"]."\">";
echo"<button id=\"start\" type=\"submit\">";
echo "<div style=\"font-family:verdana;font-weight:bold;color:#3083FF;font-size:20px;width:100%;text-align:center;margin:0; padding:0;\">";
echo $row['partnum']."<br/>";
echo "</div>";
echo"<img style=\"width:50%;\"; src=\"productimages/".$row['partnum'].".jpg\" alt=\"Save icon\" onError=\"this.src='productimages/noimage.jpg'\"/>";
echo "<div style=\"font-family:verdana;color:#3083FF;font-size:20px;width:100%;text-align:center;margin:0; padding:0;\">";
echo $row['description'];
echo "</div>";
echo"</button>";
echo"</form>";
}
$i++;
}
sqlsrv_free_stmt( $stmt);
}
catch (Exception $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
if($i < 1)
{
echo "<div style=\"font-family:verdana;font-weight:bold;color:#3083FF;font-size:20px;width:100%;text-align:center;\">";
echo "No results found, Please check your spelling of the part number or description.";
echo "</div>";
}
if($i == 1 ) {
echo"<img onload=\"setTimeout(submit(),00001);\" src=\"index.jpg\" onError=\"this.src='productimages/noimage.jpg'\"/>";
}
?>
</body>
</html>
Instead you can use count in query.
$query = "SELECT count(column) FROM table WHERE column = value";
following step count search value in mysql table.
$query = "SELECT * FROM table WHERE fieldName = fieldvalue";
$results = mysql_query($query);
$rows = mysql_num_rows($results);
echo $rows ;