Based on my codes, i need to restrict the insertion of the data by 3, i mean is like after the insertion of 3 data row, it will be restricted from inserting in data. Is that possible? For more information, is like the borrow inserting 3 times, then it cannot be inserted anymore. Is there anyway to do so? I am still learning php by the way, thank you.
if(isset($_POST['selector']))
$id=$_POST['selector'];
else
$id = '';
$member_id = $_POST['member_id'];
$due_date = $_POST['due_date'];
$isbn = $_POST['due_date'];
if ($id == '' ){
//header("location: borrow.php");
if(isset($_POST['isbn'])){
$isbn = $_POST['isbn'];
$query = mysql_query("select book_id from book WHERE isbn = '$isbn'")or die(mysql_error());
$count = mysql_num_rows($query);
if($count > 0){
$row = mysql_fetch_array($query);
$bookid = $row['book_id'];
$date = date('Y-m-d');
}
mysql_query("insert into borrow (member_id,book_id,date_borrow,due_date) values ('$member_id','$bookid','$date','$due_date')")or die(mysql_error());
}
else{
header("location: borrow.php");
}
}else{
mysql_query("insert into borrow (member_id,date_borrow,due_date) values ('$member_id',NOW(),'$due_date')")or die(mysql_error());
$query = mysql_query("select * from borrow order by borrow_id DESC")or die(mysql_error());
$row = mysql_fetch_array($query);
$borrow_id = $row['borrow_id'];
}else{
mysql_query("insert into borrow (member_id,date_borrow,due_date) values ('$member_id',NOW(),'$due_date')")or die(mysql_error());
$query = mysql_query("select * from borrow order by borrow_id DESC")or die(mysql_error());
$row = mysql_fetch_array($query);
$borrow_id = $row['borrow_id'];
$N = count($id);
for($i=0; $i < $N; $i++)
{
mysql_query("insert borrowdetails (book_id,borrow_id,borrow_status)
values('$id[$i]','$borrow_id','pending')")or die(mysql_error());
}
header("location: borrow.php");
}
You just have to count number of user row before to make a new insert :
$query = mysql_query("SELECT COUNT(*) AS count FROM borrow WHERE member_id = '".$member_id."'");
$row = mysql_fetch_assoc($query);
if ( $row['count'] >= 3 )
echo('Max insert');
Also, check this : Why shouldn't I use mysql_* functions in PHP?
I'm not sure I understand you correctly.
You can restrict the number of rows returned by SELECT query using the LIMIT clause.
Make sure you either put an ORDER BY clause in there or determine that you don't care 'which' 3 rows will get inserted.
See here:
http://dev.mysql.com/doc/refman/5.0/en/select.html
Related
I have a page that is taking a kind of long time to load, and I'm almost sure that this is caused by too many sql requests (AKA caused by my bad SQL skills). Is there anyway to join these 3 queries into one?
What I want to do with this query is to try to select a specific id from cardapios and, if there is anything there (if $num_rows > 0) the only thing I want to do is select that id. If there is nothing there, then I want to insert something and then select the id of that.
$query = "SELECT id FROM cardapios WHERE nome='$nome'";
$sql = mysqli_query($con,$query);
$num_rows = mysqli_num_rows($sql);
if ($num_rows > 0){
while ($row = mysqli_fetch_array($sql)){
$_SESSION['id_cardapio'] = $row['id'];
$num_rows = 0;
}}else{
$query = "INSERT INTO cardapios (nome, kcal, semana)
VALUES('$nome', '$kcal', '$semana')" or die(mysqli_error($con));
$sql = mysqli_query($con,$query);
$query = "SELECT id FROM cardapios WHERE nome='$nome' ";
$sql = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($sql)){
$_SESSION['id_cardapio'] = $row['id'];
}
}
I am trying to put all of this into one query but getting nowhere. Is there anyway to use just one query for doing all of this?
Thanks in advance!
You can replace the last query by getting the mysqli_insert_id($con); as you already have the insert id available after the insert
$query = "SELECT id FROM cardapios WHERE nome='$nome'";
$sql = mysqli_query($con,$query);
$num_rows = mysqli_num_rows($sql);
if ($num_rows > 0){
while ($row = mysqli_fetch_array($sql)){
$_SESSION['id_cardapio'] = $row['id'];
$num_rows = 0;
}
}else{
$query = "INSERT INTO cardapios (nome, kcal, semana)
VALUES('$nome', '$kcal', '$semana')" or die(mysqli_error($con));
$sql = mysqli_query($con,$query);
if ( $sql !== false) { // did insert work
$_SESSION['id_cardapio'] = mysqli_insert_id($con);
} else {
// insert did nto work??
}
}
I have this query. However, it does not work properly. The echo returns always a 1, but there are 3 rows in the db
<?php
include "db_connect.inc.php";
$sql = "SELECT COUNT(id) FROM profiles";
$res = mysqli_query($con, $sql);
$num = mysqli_num_rows($res);
if ($num == 0)
echo "0";
echo $num;
mysqli_close($con);
?>
You're doing an aggregate query, which means you'll ALWAYS get one row of results - one row containing the count() value you requested. Even if that count() is 0, you'll STILL get one row of results.
If you want to check the value of the count, you have to fetch that row and check the field's value, e.g.
$sql = "SELECT COUNT(id) AS cnt FROM profiles";
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
$row = mysqli_fetch_assoc($result);
if ($row['cnt'] == 0) { die("No profiles"); }
Your query returns 1 row with value 3
To see what you do expect you need something like:
<?php
include "db_connect.inc.php";
$sql = "SELECT COUNT(id) myCount FROM profiles";
$res = mysqli_query($con, $sql);
if ($row = mysqli_fetch_array($res, MYSQLI_ASSOC) ) {
echo $row['myCount'];
} else {
echo "0";
}
mysqli_close($con);
?>
I've created a script to run on my database at five minute intervals as a cron job. It's not a well written piece of code, but it's done quickly and should do the job for now.
I'm executing a WHILE loop to execute multiple if statements which in turn have multiple SQL statements within them. Problem is, it's only iterating the WHILE loop once and then stops and i'm not entirely sure why. Code is as below:
<?php
require_once('config.php');
$hashtags = mysql_query("SELECT id, hashtag FROM hashtags WHERE enabled = '1'") or die(mysql_error());
while($row = mysql_fetch_array($hashtags))
{
$hashtag_id = $row['id'];
$hashtag = $row['hashtag'];
//Get id and latest_tweet_id from report log
$latest_report_tweet_id_query = mysql_query("SELECT id, latest_tweet_id FROM reports_log WHERE name = 'post_count' AND hashtag_id = '".$hashtag_id."' LIMIT 1") or die(mysql_error());
if (mysql_num_rows($latest_report_tweet_id_query) == 0) {
$new_report_tweet_id_query = mysql_fetch_array(mysql_query("SELECT tweet_id FROM tweet_tags WHERE tag = '".$hashtag."' ORDER by tweet_id desc LIMIT 1")) or die(mysql_error());
$new_report_tweet_id = $new_report_tweet_id_query['tweet_id'];
$post_count_query = mysql_fetch_array(mysql_query("SELECT count(tweet_id) as tweet_count FROM tweet_tags WHERE tag = '".$hashtag."' AND tweet_id <= '".$new_report_tweet_id."'")) or die(mysql_error());
$post_count = $post_count_query['tweet_count'];
if(mysql_query("INSERT INTO post_count_reports (timestamp, hashtag_id, post_count, latest_tweet_id) VALUES ('".date("Y-m-d H:i:s")."', '".$hashtag_id."', '".$post_count."', '".$new_report_tweet_id."')"))
{
//Get just created id of the report
$report_id_query = mysql_fetch_array(mysql_query("SELECT id FROM post_count_reports WHERE hashtag_id = '".$hashtag_id."' AND latest_tweet_id = '".$new_report_tweet_id."'")) or die(mysql_error());
$report_id = $report_id_query['id'];
if(mysql_query("INSERT INTO reports_log (timestamp, hashtag_id, name, latest_tweet_id, latest_report_id) VALUES ('".date('Y-m-d H:i:s')."', '".$hashtag_id."', 'post_count', '".$new_report_tweet_id."', '".$report_id."')"))
{
echo "Successfully created report! NEW";
}
else {
echo "Failed updating report log! NEW";
}
}
else
{
echo "Failed making report! NEW";
}
}
else {
//Set the latest report id
$latest_report_tweet_id_array = mysql_fetch_array($latest_report_tweet_id_query);
$latest_report_log_id = $latest_report_tweet_id_array['id'];
$latest_report_tweet_id = $latest_report_tweet_id_array['latest_tweet_id'];
//Query to get the latest tweet_id in the database
$new_report_tweet_id_query = mysql_fetch_array(mysql_query("SELECT tweet_id FROM tweet_tags WHERE tag = '".$hashtag."' ORDER by tweet_id desc LIMIT 1")) or die(mysql_error());
$new_report_tweet_id = $new_report_tweet_id_query['tweet_id'];
//Query to get the new post count from database
$new_post_count_query = mysql_fetch_array(mysql_query("SELECT count(tweet_id) as tweet_count FROM tweet_tags WHERE tag = '".$hashtag."' AND tweet_id > '".$latest_report_tweet_id."' AND tweet_id <= '".$new_report_tweet_id."'")) or die(mysql_error());
$new_post_count = $new_post_count_query['tweet_count'];
$old_post_count_query = mysql_fetch_array(mysql_query("SELECT id, post_count FROM post_count_reports ORDER by timestamp desc LIMIT 1")) or die(mysql_error());
$old_post_count = $old_post_count_query['post_count'];
$post_count = $old_post_count + $new_post_count;
if(mysql_query("INSERT INTO post_count_reports (timestamp, hashtag_id, post_count, latest_tweet_id) VALUES ('".date('Y-m-d H:i:s')."', '".$hashtag_id."', '".$post_count."', '".$new_report_tweet_id."')"))
{
//Get just created id of the report
$report_id_query = mysql_fetch_array(mysql_query("SELECT id FROM post_count_reports WHERE hashtag_id = '".$hashtag_id."' AND latest_tweet_id = '".$new_report_tweet_id."' ORDER by timestamp desc LIMIT 1")) or die(mysql_error());
$report_id = $report_id_query['id'];
if(mysql_query("UPDATE reports_log SET id = '".$latest_report_log_id."', timestamp = '".date('Y-m-d H:i:s')."', latest_tweet_id = '".$new_report_tweet_id."', latest_report_id = '".$report_id."' WHERE name = 'post_count'"))
{
echo "Successfully created report!";
}
else {
echo "Failed updating report log!";
}
}
else
{
echo "Failed making report!";
}
}
}
?>
Massive error on my part, turns out whilst there were three hashtags in the hashtags table there were only rows with one of the hashtags in the tweet_tags table. Wasted a few hours on this one.
Moral of the story, always log and check for errors!
I want to update the database of the sort order column to increase its value by one if the the new value inserted into the database clashes with the value that is already in the database. May I know how should I go about doing it? Please help! Thanks!
Below is my code (I am not sure whether am I on the right track):
$result = mysql_query("SELECT sortorder FROM information ORDER BY id ASC;");
if($result >= 1 ){
$i=1;
while ($initialorder = mysql_fetch_assoc($result))
{
$initialorder = $initialorder["sortorder"];
if ($sortorder == $initialorder ){
$result6 = mysql_query("SELECT * FROM information
WHERE `sortorder` = '$sortorder'");
$row6 = mysql_fetch_array($result6);
$removethis1 = $row6['id'];
$result7 = mysql_query("UPDATE information
SET `sortorder`= ((SELECT `sortorder`
FROM (SELECT MAX(`sortorder`) AS
'$initialorder' FROM information) AS '$initialorder') + 1)
WHERE id='$removethis1'");
}
$query = "INSERT INTO `information`
(`id`,`page`,`description`,`status`,`sortorder`,`keyword`,`date_added`)
VALUES
('$id','$title','$description','$status',
'$sortorder','$keyword','$date_added')";
$result = mysql_query($query, $conn);
header('Location: index.php?status=1&title='.$title);
$i++; }
}
You can do this:
INSERT INTO ON `information`
...
DUPLICATE KEY UPDATE
sortorder = '".$sortorder + 1." '
$query = "SELECT * FROM `table`";
$results = mysql_query($query, $connection);
If 'table' has no rows. whats the easiest way to check for this.?
Jeremy Ruten's answer above is good and executes quickly; on the other hand, it only gives you the number of rows and nothing else (if you want the result data, you have to query the database again). What I use:
// only ask for the columns that interest you (SELECT * can slow down the query)
$query = "SELECT some_column, some_other_column, yet_another_column FROM `table`";
$results = mysql_query($query, $connection);
$numResults = mysql_num_rows($results);
if ($numResults > 0) {
// there are some results, retrieve them normally (e.g. with mysql_fetch_assoc())
} else {
// no data from query, react accordingly
}
You could use mysql_num_rows($results) to check if 0 rows were returned, or use this faster alternative:
$query = "SELECT COUNT(*) AS total FROM table";
$results = mysql_query($query, $connection);
$values = mysql_fetch_assoc($results);
$num_rows = $values['total'];
Alternatively you can simply check if the result of mysql_fetch_assoc is false.
$query = "SELECT * FROM `table`";
$results = mysql_query($query, $connection);
$Row = mysql_fetch_assoc($results);
if ($Row == false)
{
$Msg = 'Table is empty';
}
One thing i noticed that was missed was the fact that the query might not succeed, so you do need to check if the $results variable is set. I'll use the answer given by yjerem as an example.
$query = "SELECT COUNT(*) AS total FROM table";
$results = mysql_query($query, $connection);
if ($results) { // or use isset($results)
$values = mysql_fetch_assoc($results);
$num_rows = $values['total'];
}
If you loop through the results, you can have a counter and check that.
$x = 1;
$query = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_assoc($query))
{
$x++;
}
if($x == 1)
{
//No rows
}