<? require ("tracker.php");
?>
<center>
<?php
include 'dbc.php';
?>
<title>J~Net Level Up</title>
<?php session_start();
$id = $_SESSION['user_id'];
// Connects to your Database
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("messages") or die(mysql_error());
$data = mysql_query("UPDATE `users` SET `balance` = `balance` - 1000 WHERE `users`.`id` =$id")
or die(mysql_error());
echo "<table border cellpadding=3>";
while($info = mysql_fetch_array( $data ))
{
echo "<tr>";
echo "<th>User:</th> <td>".$info['user_name'] . "</td> ";
echo "<th>Balance:</th> <td>".$info['balance'] . " </td></tr>";
}
echo "</table>";
// echo "Balance Is ".$_SESSION['balance'];
echo $row['user_name'] . " " . $row['balance'];
?>
<META HTTP-EQUIV=REFRESH CONTENT="0; URL=010101levup.php">
as you can see in above code it doesnt check if balance is available before it executes and balance goes into minus, is there a simple way it can have a if statement to make sure balance is available first before it executes the sql statement?
please help with this minor glitch what i need is a pro to edit the above code not tell me what lines needs to be added as before when this happens its untested and when i test it it fails so i need it to make sure balance is in there and if yes it goes to that refresh line (at bottom of code block),
and if there is insufficient funds it should return an error and not goto last line of code.
Please help if you can i can supply any sql you may need for this to test your end if required!
Add some extra logic to the where clause:
$update = 1000;
UPDATE users
SET balance = balance - $update
WHERE (users.id = $id) AND
(balance >= $update)
The update will still run, but only actually change the record if the balance is high enough to begin with.
Related
I want to make a link to delete a record from database using dynamic links with php however i couldn't figure it out
this is my code :
<?php
$query = "SELECT * FROM posts ";
$result = mysqli_query($connect, $query);
?>
<table>
<tr style="background: #afafaf;">
<th>Id</th>
<th>Title</th>
<th>Action</th>
</tr>
<?php
while($rows = mysqli_fetch_assoc($result)){
echo "<tr>";
echo "<td class=\"center\">".$rows['id']."</td>";
echo "<td>".$rows['title']."</td>";
echo "<td> delete</td>";
echo "</tr>";
}
?>
</table>
the output link would be like .../delete.php?id=X
can anyone help me write the code for delete.php ?
Have the below code in your page. This first checks if $_GET['id'] is set. It will only run if it is, that way you don't get Undefined Index error.
<?php
if (isset($_GET['id'])) {
$deleteId = htmlspecialchars($_GET['id'], ENT_QUOTES);
$delete = "DELETE FROM `posts` WHERE `id` = " . $deleteId;
}
?>
I also used htmlspecialchars to sanitize the user input. You could run some validation using ctype_digit to ensure that the input is actually an integer.
I suggest using prepared statement in MySQLi to prevent SQL injection.
Edit 1
Example with ctype_digit. This checks if the id is set and if it is a number, technically you could just use ctype_digit because if id is empty then ctype will return false as var_dump(ctype_digit("")); will return false, with that logic in mind, the value must be set for ctype_digit to work and it must be an integer.
<?php
if (ctype_digit($_GET['id'])) {
$deleteId = htmlspecialchars($_GET['id'], ENT_QUOTES);
$delete = "DELETE FROM `posts` WHERE `id` = " . $deleteId;
}
?>
That would be something like this:
$deleteId = $_GET['id'];
$sql = "DELETE FROM posts WHERE id = ".$deleteId;
Remember to escape your variables before sending them off to the MySQL server.
i have a cart displayed and the user has to select the date of delivery from the calendar widget and click on Confirm button. on submit, the order cart should be populated along with the entered date of delivery.
the code i used is:
<?php
echo "<form action='' name='form1' >";
//some disaply codes here
echo "Choose the Date of delivery<input type='date' name='date'>";
echo "<input type='submit' class='btn btn-default' name='final_submission' value ='Confirm Order'>";
echo "</form>";
?>
the code for insertion is:
<?php
if (isset($_POST['final_submission'])){
error_reporting(E_ALL);
ini_set('display_errors', 1);
$IP="my localhost";
$USER="my user name";
$conn=mysqli_connect($IP,$USER,"","my database name");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$date = stripslashes($_POST['date']);
$result=mysqli_query($conn, $query);
$query="select * from cart";
while($row = mysqli_fetch_array($result)) {
$us_id=$row['user_id'];
$pr_id=$row['prod_id'];
$qtty=$row['quantity'];
$query_insert = "insert into orders(user_id, prod_id, quantity, dt_del) values('.$us_id.',
'.$pr_id.', '.$qtty.','.$date.')";
$res_ins=mysqli_query($conn,$query_insert);
}
}
?>
the orders table s not getting populated. I cant put my finger on the error. plz point it out
EDIT: the orders table is getting poplulated, but the del date field is coming blank...Please let me know how to pass the date variable correctly, as clearly that is the issue
I am not sure what you are trying to attempt to be honest. Your code blocks lacks a lot of stuff. For instance:
$query="select * from cart";
while($row = mysqli_fetch_array($result)) {
What results? Where do you define them? Are that results from the query you specified there, cause surely you aint executing it. Thus the result will be 0 and will not be executed.
Also the problem is with this query it will go through every row of the cart, this means also you ll grab carts that aint belonging to your costumer, specify.
So your code should be something like
$query="select * from cart";
$result = mysqli_query($conn,$query);
while($row=mysqli_fetch_array($result)){
// yadi yadi yadi .. code code code
edit
Let me try to rework this out for you with propper indenting.
if (isset($_POST['final_submission'])){ // check if the button is correct
// error_reporting(E_ALL); <-- canceling this out for now
// ini_set('display_errors', 1); <-- canceling this out for now
$IP="my localhost";
$USER="my user name";
$conn=mysqli_connect($IP,$USER,"","my database name");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$date = stripslashes($_POST['date']);
if (empty($date) || $date == ''){
echo 'the date is not set, please check if parameter is filled in';
} else { // if it wont pass this point, you wont get an enormous output of unidentified indexes
$query="select * from cart";
$result=mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result)) {
$us_id=$row['user_id'];
$pr_id=$row['prod_id'];
$qtty=$row['quantity'];
$date = stripslashes($_POST['date']); // just to play it safe define it again
if (empty($date) || $date == ''){
echo 'something went wrong with the date';
}else{
$query_insert = "insert into orders(user_id, prod_id, quantity, dt_del) values('.$us_id.','.$pr_id.', '.$qtty.','.$date.')";
$res_ins=mysqli_query($conn,$query_insert);
}
}
}
}
How about this? This is at the top of my codes but i think this is helpless. Every time the third order comes in the calculation is all wrong.
<?php
include("dbconnection.php");
if ($_SESSION["loggedin"] != "true")
header("Location:memberlogin.php");
$cust_id = $_SESSION["cust_id"];
Selecting all from the database
$result = mysql_query("select customer.*, product.*, order_details.* from customer, product, order_details where customer.cust_id=$cust_id and product.pro_id=product.pro_id and order_details.order_details_id = order_details.order_details_id")or die(mysql_error());
$row = mysql_fetch_assoc($result);
?>
<?php
$x=1;
$bill_total=5.00;
$order_stotal=$row["order_stotal"];
$result = mysql_query("select product.*,order_details.* from product,order_details
where order_details.pro_id= product.pro_id ");
while($row=mysql_fetch_assoc($result))
{
?>
I need it to echo all the possible subtotal. I think i just need to edit this or something i'm not quite sure
<?php
$x++;
$bill_total +=$order_stotal;
}
?>
RM  
<?php
echo number_format($bill_total,2);
?>
Then this one here is the function of the button
<?php
if(isset($_POST["submitbtn"]))
{
$bill_id=rand(1000,9999);
$bill_date=date("Y-m-d");
$bill_state=$_POST["bill_state"];
$bill_city=$_POST["bill_city"];
$bill_add=$_POST["bill_add"];
$bill_post=$_POST["bill_post"];
mysql_query("insert into bill
(cust_id, bill_date, bill_total, bill_state, bill_city, bill_add,
bill_post)
values('$cust_id','$bill_date',
'$bill_total', '$bill_state', '$bill_city','$bill_add','$bill_post')")or die(mysql_error());
}
?>
$bill_total +=$row['order_stotal'];
This should work for combining all the values from that line in the rows retrieved by the database.
(You also need to remove the reference to $row['order_stotal'] from before the query, unless you're using a different query from another part of the script to set it.)
I'm working on a project to further learn php and how it can be used to interface with a mysql database. The project is a forum, with the page in question displaying all the topics in a category. I'd like to know if I am handling my calls efficiently, and if not, how can I structure my queries so they are more efficient? I know its a small point with a website that isn't used outside of testing, but I'd like to get a handle on this early.
<?php
$cid = $_GET['cid'];
$tid = $_GET['tid'];
// starting breadcrumb stuff
$catname = mysql_query("SELECT cat_name FROM categories WHERE id = '".$cid."'");
$rcatname = mysql_fetch_array( $catname );
$topicname = mysql_query("SELECT topic_title FROM topics WHERE id = '".$tid."'");
$rtopicname = mysql_fetch_array( $topicname );
echo "<p style='padding-left:15px;'><a href='/'> Home </a> » <a href='index.php'> Categories </a> » <a href='categories.php?cid=".$cid."'> ".$rcatname['cat_name']."</a> » <a href='#'> ".$rtopicname['topic_title']. "</a></p>";
//end breadcrumb
$sql = "SELECT * FROM topics WHERE cat_id='".$cid."' AND id='".$tid."' LIMIT 1";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) == 1) {
echo "<input type='submit' value='Reply' onClick=\"window.location = 'reply.php?cid=".$cid."&tid=".$tid."'\" />";
echo "<table>";
if ($_SESSION['user_id']) { echo "<thead><tr><th>Author</th><th>Topic » ".$rtopicname['topic_title']."</th></thead><hr />";
} else {
echo "<tr><td colspan='2'><p>Please log in to add your reply.</p><hr /></td></tr>";
}
echo "<tbody>";
while ($row = mysql_fetch_assoc($res)) {
$sql2 = "SELECT * FROM posts WHERE cat_id='".$cid."' AND topic_id='".$tid."'";
$res2 = mysql_query($sql2) or die(mysql_error());
while ($row2 = mysql_fetch_assoc($res2)) {
echo "<tr><td width='200' valign='top'>by ".$row2['post_creator']." <hr /> Posted on:<br />".$row2['post_date']."<hr /></td><td valign='top'>".$row2['post_content']."</td></tr>";
}
$old_views = $row['topic_views'];
$new_views = $old_views + 1;
$sql3 = "UPDATE topics SET topic_views='".$new_views."' WHERE cat_id='".$cid."' AND id='".$tid."' LIMIT 1";
$res3 = mysql_query($sql3) or die(mysql_error());
echo "</tbody></table>";
}
} else {
echo "<p>This topic does not exist.</p>";
}
?>
Thanks guys!
Looks like a classic (n+1) query mistake that could die a latent death. You get a key using one round trip, then you loop over the results to get n values based on it. If the first result set is large you'll have a lot of network round trips.
You could bring it all back in one go with a JOIN and save yourself a lot of network latency.
The statements themselves are fairly simple so there's not much you can do to optimize them further that I know of. However, if you create some business objects and cache the data into them on a single call and then access data from the business objects then it could be faster.
In other words, 1 SQL call for 1,000 rows is going to be much faster than 1,000 calls for a single row.
Here are some of extra things I would do when I write a code like above:
Never use * in SELECT statement when you know the columns you are going to use.
Always use or die(mysql_error()) when executing the query.
Unset the result sets once the result sets has served its purpose.
Use mysql_real_escape_string() to escape the injections when using some substitutions in your queries.
i get this error line on this php file . can someone locate where is the error ?
-------------You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1----------
i have this page for votes to users but if i vote in one user this vote goes to all users . how can i make this code when voting this vote goes only to its user .
--
// Connects to your Database
mysql_connect("localhost", "dbusername", "dbpassword") or die(mysql_error());
mysql_select_db("mydatabase") or die(mysql_error());
//We only run this code if the user has just clicked a voting link
if ( $mode=="vote")
{
//If the user has already voted on the particular thing, we do not allow them to vote again
//$cookie = "Mysite$id";
if(isset($_COOKIE[$cookie]))
{
Echo "Sorry You have already ranked that site <p>";
}
//Otherwise, we set a cooking telling us they have now voted
else
{
$month = 2592000 + time();
setcookie('Mysite'.$id, 'Voted', $month);
//Then we update the voting information by adding 1 to the total votes and adding their vote (1,2,3,etc) to the total rating
mysql_query ("UPDATE userads SET total = total+$voted, votes = votes+1 WHERE id = $id");
}
}
if ( $mode2=="vote")
{
//If the user has already voted on the particular thing, we do not allow them to vote again
//$cookie = "Mysite$id";
if(isset($_COOKIE[$cookie]))
{
Echo "Sorry You have already ranked that site <p>";
}
//Otherwise, we set a cooking telling us they have now voted
else
{
$month = 2592000 + time();
setcookie('Mysite'.$id, 'Voted', $month);
//Then we update the voting information by adding 1 to the total votes and adding their vote (1,2,3,etc) to the total rating
mysql_query ("UPDATE userads SET total = total+$voted, nvotes = nvotes+1 WHERE id = $id");
}
}
//Puts SQL Data into an array
$data = mysql_query("SELECT * FROM userads WHERE id = $id ") or die(mysql_error());
//Now we loop through all the data
while($ratings = mysql_fetch_array( $data ))
?>
<link href="style.css" type="text/css" rel="stylesheet" />
{
<?php
echo '<div id="voting_14" class="voting voting_template_votess-up-down">';
echo "<strong class='positive_votes'>";
$current = $ratings[votes];
echo "<span>+" . round($current,0) . "</span>";
echo " <input class='vote_positive' type='submit'>";
echo '</strong>';
echo "<strong class='negative_votes'>";
$current2 = $ratings[nvotes];
echo " <input class='vote_negative' type='submit'>";
echo "<span>-". round($current2,0) ."</span>";
echo '</strong>';
echo '</div>';
}
---the end
i have sql table userads with : id , name , username , total, votes , nvotes.
Correct your code to following,
setcookie('Mysite'.$id, 'Voted', $month); // ERROR 1
and
while($ratings = mysql_fetch_array( $data ))
{ // ERROR 2
?>
I copy pasted your code in a file and ran:
php -l your_script.php
Yields:
Parse error: syntax error, unexpected '}' in your_script.php on line 78
So, that last bracket } at the very end is causing a parse error. Either that or you didn't post the matching if/while/etc. in your post and the problem is elsewhere.
You have a syntax error. Probably your configuration doesn't display errors and you get a blank screen.
You are missing quotes here:
setcookie(Mysite.$id, Voted, $month);
It should be:
setcookie('Mysite'.$id, 'Voted', $month);
Apparently something is wrong with your query. You can check your SQL query with a simple:
$sql = "SELECT * FROM userads WHERE id = $id ";
echo $sql;
My first guess is, that $id is not set properly.