Here is my coding. Basically i want to set form limitation based on user defined in ($result2). Another thing is the date. Eg. Today can submit 3 form then tomorrow can submit another 3 form until the user makes the changes on $result2. The problem from this code it will ignore the date and keep let user submit the form without the limit. Hope you guys can help, thanks
$name = $_POST['name'];
$address = $_POST['address'];
$contact = $_POST['contact'];
$email = $_POST['email'];
$tbl_name="torder";
$sql="INSERT INTO $tbl_name
(name,address,contact,email,orderdate)
VALUES('$name','$address','$contact','$email',now())";
$tbl2_name="tblfree";
$query="SELECT * FROM tblfree";
$result2=mysql_query($query);
$row = mysql_fetch_array(
mysql_query("SELECT COUNT(*) AS 'submit' FROM torder"));
if ($row['submit'] > $result2) {
echo 'We have reached our Free-T limit';}
else {
$result=mysql_query($sql);
echo 'success';
}
The problem is that you're comparing a scalar value to a mysql_result, you can see where that is happening below
if ($row['submit'] > $result2)
Instead, you need to fetch the result of $result2 and compare it, so modify it to the following
$result2=mysql_query($query);
$row2 = mysql_fetch_array($result2);
$row = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS 'submit' FROM torder where orderdate = {$current}"));
if ($row['submit'] > $row2['value_you_want_to_compare']) {
echo 'We have reached our Free-T limit';}
else {
$result=mysql_query($sql);
echo 'success';
}
Also, your code is vulnerable to SQL Injection, to fix that, stop using mysql_* functions as they're deprecated and start using mysqli or PDO with prepared statements
$tbl2_name="tblfree";
$query="SELECT amount FROM tblfree where id=1";
$result2=mysql_fetch_array(mysql_query($query));
$row = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS submit FROM torder where orderdate = CURDATE()"));
if ($row ['submit'] >= $result2['amount']) {
echo 'We have reached our Free-T limit';
echo $result2['amount'];}
else {
$tbl_name="torder";
$sql="INSERT INTO $tbl_name
(name,address,contact,email,orderdate)VALUES('$name','$address','$contact','$email',CURDATE())";
$result=mysql_query($sql);
$sql="INSERT INTO $tbl_name (name,address,contact,email,orderdate)VALUES('$name','$address','$contact','$email','$orderdate')";
echo 'success';
}
Related
How to get value from select query without using while loop while we know that output is defiantly only one record
$sql = "SELECT id FROM MyGuests";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{
echo $row["id"];
}
Here if i know that there is only one record comes as a output then how to avoid while loop and directly get our id
just delete the while loop!
$sql = "SELECT id FROM MyGuests";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo $row["id"];
are you using mysql_* functions by any chance? please switch to PDO as soon as possible.
You can use MYSQl bind result if its a single row output
if( isset($con) && !empty($con) && $con!="" ) {
$knownStmt=mysqli_prepare($con, "SELECT id FROM MyGuests");
if( $knownStmt ) {
mysqli_stmt_execute($knownStmt);
mysqli_stmt_bind_result($knownStmt,$id);
mysqli_stmt_fetch($knownStmt);
mysqli_stmt_close($knownStmt);
}
}
Please try this. This is one of the best way. You can also pass the where condition also and bind the value this query. Please see below is the example for the same.
if( isset($con) && !empty($con) && $con!="" ) {
$knownStmt=mysqli_prepare($con, "SELECT name FROM MyGuests WHERE id=?");
if( $knownStmt ) {
mysqli_stmt_bind_param($knownStmt,"d",$UID);
mysqli_stmt_execute($knownStmt);
mysqli_stmt_bind_result($knownStmt,$Name);
mysqli_stmt_fetch($knownStmt);
mysqli_stmt_close($knownStmt);
}
}
I'm sure this will definitely help you.
Please note this works only for single row result.
You can use this code for your purpose.
$result = mysql_query("SELECT id FROM MyGuests");
$row=mysql_fetch_array($result);
echo $row["id"];
I am trying to create a guestbook that shows comments people have posted through an SQL query. I have successfully connected to the SQL database, but the query isn't showing anything. What is wrong here?
</form>
<h2>Current Posts</h2>
";
$sql = "SELECT * FROM 'guest_booklet' LIMIT 0, 30 ";
if ($numrows > 0) {
echo "$rows ['email']";
while ( $row = mysql_fetch_row($result) ){
$id = $row ['id'];
$name = $row['name'];
$email = $row['email'];
$message = $row['message'];
$message = n12br($message);
echo "<div>
$name - and email is $email <hr/>
$message
<div>";
}
}
mysql_close();
?>
</body>
</html>
1) Change
$sql = "SELECT * FROM 'guest_booklet' LIMIT 0, 30 ";
To
$sql = "SELECT * FROM `guest_booklet` LIMIT 0, 30 ";
=> Use Backtick instead of single quotes for enclosing table name.
2) You missed $result = mysql_query($sql);
3) You Missed $numrows = mysql_num_rows($result);.
4) Remove echo "$rows ['email']"; line. It's suspense from where it comes.
Mysql (Updated Code)
<?php
$sql = "SELECT * FROM `guest_booklet` LIMIT 0, 30 ";
$result = mysql_query($sql);
$numrows = mysql_num_rows($result);
if ($numrows > 0) {
while ( $row = mysql_fetch_row($result) ){
$id = $row ['id'];
$name = $row['name'];
$email = $row['email'];
$message = n12br($row['message']);
echo "<div>".$name." - and email is ".$email." <hr/>.".$message."<div>";
}
}
mysql_close();
?>
[Note: The mysql_* functions are deprecated, they have been removed from PHP 7, your code will stop working when you upgrade to that version. You should not write new code using them, use mysqli_* or PDO instead.]
Click To Know How can I prevent SQL-injection in PHP?
Mysqli (Updated Code)
<?php
//Connection
$servername = "YOUR-VALUES";
$dbname = "YOUR-VALUES";
$user = "YOUR-VALUES";
$password = "YOUR-VALUES";
$connection = mysqli_connect($servername,$user,$password,$dbname);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `guest_booklet` LIMIT 0, 30 ";
$result = mysqli_query($connection,$sql);
$numrows = mysqli_num_rows($result);
if ($numrows > 0) {
while ( $row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$id = $row ['id'];
$name = $row['name'];
$email = $row['email'];
$message = n12br($row['message']);
echo "<div>".$name." - and email is ".$email." <hr/>.".$message."<div>";
}
}
mysqli_close($connection);
?>
You are missing a lot of stuff here.
You are closing the PHP tag but not opening it: <?php
You are never actually executing the query, you are missing a call to $result = mysql_query($sql);
You are using $numRows but never actually setting its value: `$numRows = mysql_num_rows($result);
You are using $row = mysql_fetch_row(...) but latter you are reading the resulting row as an associative array instead of a numeric index. You have to use mysql_fetch_assoc instead.
You are never actually connecting to the DB and selecting a schema, I assume you do that somewhere else, but you close the connection at the end. So make sure you are actually connecting.
It seems like you copied this from somewhere else but didn't do it right.
Things that are wrong
The syntax is not within PHP tags so won't do anything
Using single quote marks around a table name is invalid, you need backticks
(or nothing at all)
The $sql statement is never actually run
I assume $numrows is never set, so it will never be over 0
$rows['email'] is not set so it wont echo
$result is never set, so
you won't be able to iterate through it's rows
Original (incorrect) answer
Because you have LIMIT 0, 30. You are telling MySql to give you 0 results starting at index 30.
Also you are using mysql_fetch_row on a query string not a result set, you need to first actually run the query.
-- And indeed i am wrong with my assumption, here is the right thing you need to do:
"; //What is this?
$sql = "SELECT * FROM 'guest_booklet' LIMIT 0, 30 ";
$result = mysql_query($sql); //you need to add this
first I have a login form in c# that asks the user to input his email and password then these are data are sent to the domain then I retrieve it in php so I wrote a sql query to get the logged in user id and this works fine till the
if(isset($_POST['y']))
inside of it there is an insert query this query works but doesn't insert the user id ! I tried to figure it out but I dont know whats the problem .
here's the code :
<?php
session_start();
$con = mysqli_connect("mysql7.000webhost.com","a1945567_host","12345678ab","a1945567_db");
$sql = "SELECT ID FROM user WHERE Email = '".$_GET["txt_UserName"]."'AND Password = '".sha1($_GET["txt_Password"])."'";
$result = $con->query($sql);
$
$row = mysqli_fetch_array($result,MYSQLI_NUM);
$_SESSION['ID'] = $row[0] ;
echo "SUCCESS";
echo $usrID = $row[0];
if(isset($_POST['y'])){
$sql = "INSERT INTO `question13_interaction` (uid,no_0,no_1) VALUES ('".$usrID."','".$_POST['y']."',0)";
$con->query($sql);
// mysqli_query($con,$sql);
}
else if(isset($_POST["z"])){
//$sumcount = "INSERT INTO question13_interaction (sumcount)";
//$result = mysqli_query($con,$sumcount);
$sql1 = "INSERT INTO question13_interaction(uid,no_1,no_0) VALUES('".$row[0]."','".$_POST["z"]."',0)";
mysqli_query($con,$sql1);
}
//}
/*else
{
echo "FAILED";
}*/
?>
you have an extra"$" in the code:
$result = $con->query($sql);
$
probably should just be :
$result = $con->query($sql);
also I don;t think you want the echo in this statement - it will probably not set it to the correct value for your query:
echo $usrID = $row[0];
should be
$usrID = $row[0];
Except for the redundant "$", there is another question. There should be a white space between single quote and "AND", or mysql cann't parse the query correctly
I want to check and compare the information on my input form with information that is stored in my database.
Basically. if trainer, sessionslot eventdate is the same dbtrainer, dbeventdate dbsessionslot ECHO "Booked";
Else insert into booking table
I know very little about programming, could really do with some help on this one.
This is snippet of the code i am using.
if(isset($_GET['add'])){
$trainee = $_POST['txttrainer'];
$trainer = $_POST['txttrainee'];
$sessionSlot = $_POST['txtsession'];
$eventdate = $month."/".$day."/".$year;
$query = mysql_query("SELECT * FROM BOOKING WHERE trainer='$trainer' AND SessionSlot='$sessionslot");
$sqlinsert = "insert into booking (Trainee,Trainer,sessionSlot,eventDate,dateAdded) values ('".$trainee."','".$trainer."','".$sessionSlot."','".$eventdate."',now())";
$resultinsert = mysql_query($sqlinsert);
$numrows = mysql_num_rows($query);
if($numrows == 1) {
echo "this timeslot is booked"
if($resultinsert){
echo "Booking Successful....";
}else{
echo "Booking Failed";
}
}
}
if(isset($_GET['add'])){
$trainee = $_POST['txttrainer'];
$trainer = $_POST['txttrainee'];
$sessionSlot = $_POST['txtsession'];
$eventdate = $month."/".$day."/".$year;
$query = mysql_query("SELECT * FROM BOOKING WHERE trainer='$trainer' AND SessionSlot='$sessionslot");
$sqlinsert = "insert into booking (Trainee,Trainer,sessionSlot,eventDate,dateAdded) values ('".$trainee."','".$trainer."','".$sessionSlot."','".$eventdate."',now())";
$numrows = mysql_num_rows($query);
if($numrows >0) {
echo "this timeslot is booked"
}else{
$resultinsert = mysql_query($sqlinsert);
if(mysql_error()==""){
echo 'time slot booked';
}else{
echo 'error';
}
}
}
Explanation:
if there are rows selected, the timeslot is booked, else execute the query. If there is no error with the query, then print out success.
If you call mysql_query, the query is executed. So you're executing the INSERT before you check whether the SELECT returned a row or not.
That means you should place the INSERT part inside an if($numrows != 1) condition.
Please be aware that using mysql_query is deprecated: http://ch1.php.net/manual/en/function.mysql-query.php and you should use MySQLi or PDO_MySQL. Your code is vulnerable to SQL injections.
Hello I can't get my script fully operational.
I have it calculating properly but now need a query for fuel type.
<?php
include 'mysql_connect.php';
$query = "SELECT * FROM fuel_price WHERE FuelType='Oil'" ;
$result = mysql_query($query);
$price= mysql_fetch_array($result);
if(isset($_POST['submit'])){
echo "The Price Today is ";
echo "£"; echo $_POST['qtylitres'] * $price ['Price'];
} else {
echo "Please select value";
}
?>
I need to to check fueltype selected on form and calculate total accordingly.
eg $query = "SELECT * FROM fuel_price WHERE FuelType='{$_POST['fueltype'];}'" ;
Please help anyone under pressure.
Thanks
include 'mysql_connect.php';
if(isset($_POST['submit'])){
if($_POST['inputEmail'] == ''){
echo 'Please enter an email address';
} else{
// show price
$fuelPriceQuery = sprintf("SELECT `Price` FROM fuel_price WHERE FuelType = '%s' LIMIT 1",
mysql_real_escape_string($_POST['fueltype']));
$fuelPriceResult = mysql_query($fuelPriceQuery);
$price = mysql_fetch_array($fuelPriceResult, MYSQLI_ASSOC);
echo 'The Price Today is £'.($_POST['qtylitres'] * $price['Price']);
// insert email
$addEmailQuery = sprintf("INSERT INTO `subscribe`(`Email`) VALUES('%s')",
mysql_real_escape_string($_POST['inputEmail']));
$addEmailResult = mysql_query($addEmailQuery);
if($addEmailResult){
echo 'You have successfully subscribed';
} else{
echo 'Sorry, we could not subscribe you at this time. Please try again.';
}
}
} else {
echo "Please select value";
}
A couple of things to note:
Always make sure to escape the user input by using mysql_real_escape_string, if you are not using prepared statements such as PDO, MySQLi, etc...
I added the LIMIT clause to the query so mysql_fetch_array will work, because if it returns more than one row, then you would have to handle it in a loop.
It is not necessary to use multiple echos, in fact it is better if you use as few as possible.
$fueltype = mysql_real_escape_string($_POST['fueltype']);
$query = "SELECT price
FROM fuel_price
WHERE FuelType= '$fueltype'
ORDER BY pricedate DESC
LIMIT 1 ";
Explanation
Always use either PDO or mysql_real_escape_string()
Don't do SELECT *, only select the fields you need.
Put the injected $var in single quotes, or mysql_real_escape_string() will not work!
If you only need one price, select only 1. Use limit 1 to get only 1 and order by ... DESC to get the latest.