This is my code:
$roll = rand(100,1000000);
$result = mysql_query("SELECT roll FROM users") or die(mysql_error());
if($row["roll"] == $roll) {
$roll = rand(100,1000000);
}
else
{
mysql_query("INSERT INTO users (roll) VALUES('$roll') ") or die(mysql_error());
}
echo "Data Inserted!";
My question is:
If the regenerated roll number is again equal to a roll number already existing in database, how it should again generate a new roll number and keep on checking it unless it gets a unique number, which i can finally insert in the database? Please help!
You don't have to fetch ALL the rolls each time. It's just a waste of resources. Just check if the roll exists in the database, and if it does, check a new one.
function doesRollExist($roll) {
$sql = "SELECT COUNT(*) FROM users WHERE roll = " . (int)$roll;
$result = mysql_query($sql);
if ($result) {
return ((int)mysql_result($result, 0)) != 0;
}
else {
trigger_error("Query failed: " . mysql_error(), E_USER_ERROR);
}
}
do {
$newRoll = mt_rand(100, 1000000);
}
while (doesRollExist($newRoll));
// Now $newRoll will be a random number that doesn't exist
// in the database.
you can achieve by this way
$flag=1;
while($flag==1)
{
$roll = rand(100,1000000);
$result = mysql_query("SELECT roll FROM users WHERE roll=$roll") or die(mysql_error());
$row = mysql_fetch_row($result);
if($row[0] == $roll)
{
$roll = rand(100,1000000);
}
else
{
$flag=0;
mysql_query("INSERT INTO users values($roll)") or die(mysql_error());
echo "Data Inserted!";
}
}
Try this one:
$count = 1;
while($count > 0) {
$roll = rand(100,1000000);
mysql_query('SELECT COUNT(1) FROM `users` WHERE roll=' . mysql_real_escape($roll)) or die('Can\'t query the DB server.');
$countRow = mysql_fetch_array($result);
$count = $countRow[0];
}
In real-life situations you should probably add better error checking - using trigger_error, or exceptions(that of course have to be caught). I would even recommend to log all the errors.
$roll = rand(100,1000000);
$result = mysql_query("SELECT roll FROM users") or die(mysql_error());
while($row["roll"] == $roll) {
$roll = rand(100,1000000);
}
mysql_query("INSERT INTO users (roll) VALUES('$roll') ") or
die(mysql_error());
echo "Data Inserted!";
Related
When Inserting data into SQL it inserts two into rows, and I don't know why.
most probably of the if statement I added after the results you can find it as my comment:
// id_no update
And I used the select query two times to fetch the id and make it an auto-increment thing.
my table:
<?PHP
$query = "SELECT id_no FROM db_name ORDER BY id_no DESC";
$result = mysqli_query($con,$query);
$row = mysqli_fetch_array($result);
$lastid = $row['id_no'];
if(empty($lastid))
{
$number = "SX000001";
}
else
{
$idd = str_replace("SX", "", $lastid);
$id = str_pad($idd + 1, 6, 0, STR_PAD_LEFT);
$number = 'SX'.$id;
}
?>
<?PHP
if(isset($_POST['add_id']))
{
$id_no = mysqli_real_escape_string($con,$_POST['id_no']);
$sql="INSERT INTO `db_name`(`id_no`) VALUES ('$id_no')";
$result=mysqli_query($con,$sql);
// id_no update
if(mysqli_query($con,$sql))
{
$query = "SELECT id_no FROM db_name ORDER BY id_no DESC";
$result = mysqli_query($con,$query);
$row = mysqli_fetch_array($result);
$lastid = $row['id_no'];
if(empty($lastid))
{
$number = "SX000001";
}
else
{
$idd = str_replace("SX", "", $lastid);
$id = str_pad($idd + 1, 6, 0, STR_PAD_LEFT);
$number = 'SX'.$id;
}
}
else
{
echo "Record Faileddd";
}
if($result)
{
$success="Post has been added successfully";
} else
{
$error="Something went wrong!";
}
$id_no = '';
}
?>
You should check if $result is truthy to see if the insertion succeded (without running another query):
$id_no = mysqli_real_escape_string($con,$_POST['id_no']);
$sql="INSERT INTO `db_name`(`id_no`) VALUES ('$id_no')";
$result=mysqli_query($con,$sql);
// id_no update
if($result)
{
...
}
so basically I am trying to create a little thing where it outputs stars, based on the database saved rating integer. The problem is it does not seem to put the number I from the database, in the variable. Here is the code I used:
<?php
$productID = 100;
$con = mysqli_connect("localhost", "root", "", "example");
function connect()
{
$con = mysqli_connect("localhost", "root", "", "example");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
return $con;
}
}
function getStars($con)
{
$productID = 100;
$sql = "SELECT rating
FROM reviews
-- JOIN stockitemstockgroups USING (StockItemID)
-- JOIN stockgroups USING (StockGroupID)
WHERE reviewID = '5'
";
$result = $con->query($sql);
if ($con && ($result->num_rows > 0)) {
// output data of each row
while ($row = $result->fetch_assoc()) {
echo $row["rating"];
}
} else {
echo "error";
}
}
$value = getStars($con);
echo $value;
for ($x = 1; $x <= $value; $x++) {
echo '<div class="rating"><span>★</span></div>';
}
?>
I'm having trouble finding a duplicate, though I'm sure this is one. You aren't returning anything from your function, so $value doesn't have a value.
function getStars($con)
{
$productID = 100;
$sql = "SELECT rating FROM reviews WHERE reviewID = 5";
$result = $con->query($sql);
if ($result && ($result->num_rows > 0)) {
// output data of first row
$row = $result->fetch_assoc();
return $row["rating"];
} else {
return false;
}
}
As a general rule, never echo from a function. Also, no need for a loop over what will presumably be a single result.
Hi i have two arrays built by using mysql_fetch_array() i want to use them both in one while loop :
$username =$_SESSION["username"];
$password =$_SESSION["password"];
$query1= "SELECT * FROM subs WHERE username='$username' AND password='$password' ";
$res1 = mysql_query($query1);
$row_cnt1 = mysql_num_rows($res1);
if($res1 === FALSE) {
die(mysql_error()); // TODO: better error handling
}
$row1 = mysql_fetch_array($res1);
if($row_cnt1 == 1){
$sid = $row1["id"];
}else{
die("there is more than one user with the same username and password");
}
$query2= "SELECT * FROM bookreservations ";
$res2 = mysql_query($query2);
$row_cnt2 = mysql_num_rows($res2);
if($res2 === FALSE) {
die(mysql_error()); // TODO: better error handling
}
$row2 = mysql_fetch_array($res2) ;
$query= "SELECT * FROM books";
$res = mysql_query($query);
$row_cnt = mysql_num_rows($res);
if($res === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while ($row = mysql_fetch_array($res)){
if($row2["sid"] == $sid && $row2["bid"] == $row["id"]){
continue;
}
$temp = $row["id"];
$temp1 = $row["title"];
echo "Title : ".$temp1."<br><br>";
$temp1 = $row["authors"];
echo "Authors : ".$temp1."<br><br>";
$temp1 = $row["copies"];
echo "Copies : ".$temp1."<br><br><br><br>";
echo "<div class=\"re\"><input type=\"radio\" value=\"reserve\" name=\"".$temp ."\">reserve</div> <br><br><br><br><br><br>" ;
}
I want to extract things from row array but i don't want them to have some values from row2 array so I have to use them both in one while loop ,THE SUMMARY row array is ok it jumps to the next row in each loop but row2 array is stuck it doesn't move to the next row what to do ?
Although I don't really understand your task well, I however, would recommend the following edits
My assumption: You are trying to fetch all rows from $res for each $res2.
Although inefficient technique, but I'll edit your code as below.
while($row2 = mysql_fetch_array($res2) ){
while ( $row = mysql_fetch_array($res) ){ //Both $row & $row2 will have equal incremented rows.
}
}//Outer loop
I'm inserting into my database id and hours, which is working successfully. However when i insert a new value for an id that has a previous value, the old val isn't replaced by the new, instead they're kept both. I'm trying to update the function with an if/else statement (commented part). But still the same result. The if/else statement must check first if hours (a column in the table) value is empty, if so then perform sql insert, else perform sql update. Any help please?
if (isset($_POST['submit'])) {
$hours = $_POST['Hours'];
$selectid = $_POST['SelectID'];
$sql1 = "INSERT INTO `editedworkhours` (`id`,`H`) VALUES('$selectid','$hours')";
$getResult = mysql_query($sql1);
if (mysql_affected_rows() > 0) {
} else {
}
$tempname = $row['Field'];
$sql2 = "UPDATE editedworkhours SET H ='" . $_GET["hours"] . "' WHERE IDNumber='" . $_GET["selectid"] . "'";
$result2 = mysqli_query($con, $sql2);
if ($con->query($sql2) === TRUE) {
} else {
}
}
echo $menu;
Try this
<?php
if(isset($_POST['submit']))
{
$addedhours = $_POST['AddedHours'];
$selectaf = $_POST['SelectAF'];
$sql1="SELECT * FROM editedworkhours WHERE AFNumber='$selectaf' and AddedWH ='$addedhours'";
$getResult = mysql_query($sql1);
$count = count($getResult);
if(!empty($count) || $count==1)
{
$tempname = $row['Field'];
$sql2 = "UPDATE editedworkhours SET AddedWH ='$addedhours' WHERE AFNumber='$selectaf'";
$result2 = mysql_query($sql2);
if (isset($result2))
{
//Data inserted
}
else
{
//Insert Failed
echo '<script>swal("Error", "Something went wrong error");</script>';
}
echo '<script>swal("Success", "Changes have been saved", "success");</script>';
}
else
{
$sql3 = "INSERT INTO editedworkhours (AFNumber,AddedWH) VALUES('$selectaf','$addedhours')";
$Result = mysql_query($sql3);
if(isset($Result))
{
echo 'Success';
}
else
{
echo 'Failed';
}
}
}
echo $menu;
What i try to do is check the user's Id by verifying in a cookie (called "identification").
thats my code:
if(!$noCookie) {
$sql = "SELECT * FROM `". TABLE_PREFIX ."_logged` WHERE `logged_cookie` = '". $usersCookie ."' LIMIT 1";
$query = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($query) <= 0) {
echo 'yes cookie';
$row = mysql_fetch_array($query) or die(mysql_error());
print_r($row);
while ($row=mysql_fetch_array($query)) {
echo $usersId = $row["logged_user_id"];
}
} else {
echo 'no cookie';
}
}
What happends is that if the user's cookie is the same one like in the table,
it will return the user's id.
so thats what im trying to do, the IF says "yes cookie", but inside the while it doesnt do anything!
and its not giving me an error.
Since there are no rows, there's nothing to be fetched.
if (mysql_num_rows($query) <= 0) {
Should this be > 0?
You only ran mysql_fetch_array when mysql_num_rows($query) evaluated to 0 or less; i.e. there are no rows.
Perhaps you meant:
if (mysql_num_rows($query) > 0) { // <-----
echo 'yes cookie';
$row = mysql_fetch_array($query) or die(mysql_error());
// ...
}
else {
echo 'no cookie';
}
Also note that you're running mysql_fetch_array in two different places, which is normally not right. Your while loop will not include the first result row, because you already did mysql_fetch_array once before the loop.
if(!$noCookie) {
$sql = "SELECT * FROM `". TABLE_PREFIX ."_logged` WHERE `logged_cookie` = '". $usersCookie ."' LIMIT 1";
$query = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($query) > 0) {
echo 'yes cookie';
$row = mysql_fetch_array($query) or die(mysql_error());
foreach ($row as $r)
echo $r["logged_user_id"];
} else {
echo 'no cookie';
}
}