I'm trying to check whether major, grade and university in candidates table, are empty, if so then insert in university...Else...
Is my syntax appropriate?
$sqlCheck1 = "SELECT `Major`, `Grade`, `University` FROM Candidates WHERE ID='".$_GET["cid"]."'";
$result5 = mysqli_query($con,$sqlCheck1);
while($row5 = mysqli_fetch_array($result5)) {
$major = $row5['Major'];
$grade = $row5['Grade'];
$university = $row5['University'];
if (mysqli_num_rows($result5) == 0)
{
$sql5 = "INSERT INTO `university` (`major`, `degree`, `univ`, `afnumber`) VALUES ('$major','$grade','$university','".$_GET["af"]."')";
if (mysqli_query($con,$sql5) === TRUE) {
} else {
echo "Error: " . $sql5 . "<br>" . mysqli_error($con);
}
}
else
{
Use the follwing code
$sqlCheck1 = "SELECT `Major`, `Grade`, `University` FROM Candidates WHERE ID='".$_GET["cid"]."'";
$result5 = mysqli_query($con,$sqlCheck1);
if (mysqli_num_rows($result5) == 0)
{
$sql5 = "INSERT INTO `university` (`major`, `degree`, `univ`, `afnumber`) VALUES ('$major','$grade','$university','".$_GET["af"]."')";
if (mysqli_query($con,$sql5) === TRUE) {
} else {
echo "Error: " . $sql5 . "<br>" . mysqli_error($con);
}
}
else
{
well you are saying that if major, grade and university are empty than insert those empty values in university but the question here is why you want to enter those values if they are empty, even if you want to do so along with inserting afnumber using "$_GET["af"]" variable than you can use following code..
$sqlCheck1 = "SELECT `Major`, `Grade`, `University` FROM Candidates WHERE ID='".$_GET["cid"]."'";
$result5 = mysqli_query($con,$sqlCheck1);
if (mysqli_num_rows($result5) == 0)
{
$sql5 = "INSERT INTO `university` (`afnumber`) VALUES ('".$_GET["af"]."')";
if (mysqli_query($con,$sql5) === TRUE) {
} else {
echo "Error: " . $sql5 . "<br>" . mysqli_error($con);
}
}
its quite short and fulfill the purpose but make sure you have checked null in database for major, grade and univ fields in university table .
Related
I have a phpscript which takes values (Manually entered) and inserts into the column in the database. Now I want to know how would I be adding new values to the existing values for the same card number entered.
if(isset($_POST['insert-btn'])){
#$cardnumber=$_POST['cardnumber'];
#$amount=$_POST['amount'];
if($cardnumber=="" || $amount==""){
echo '<script type="text/javascript">alert("Insert values in all fields")</script>';
}
else{
$query = "insert into Client_Details values('$cardnumber',$amount/2)";
$query_run=mysqli_query($con,$query);
if($query_run){
echo '<script type="text/javascript">alert("Values inserted successfully")</script>';
}
else{
echo '<script type="text/javascript">alert("Values not inserted successfully")</script>';
}
}
}
?>
For example , I have
card number: _________
Sale value: __________
Now for the same card number the sale value entered every different time should be added. If anybody can help me with that. It would be helpful.
Before you insert data into DB, check whether a record for the card number already exists in the DB.
If it exists, use UPDATE query else use INSERT query.
Try the below code:
<?php
if (isset($_POST['insert-btn']))
{
#$cardnumber = $_POST['cardnumber'];
#$amount = $_POST['amount'];
if ($cardnumber == "" || $amount == "")
{
echo '<script type="text/javascript">alert("Insert values in all fields")</script>';
}
else
{
$newQuery = mysqli_query($con, "SELECT * FROM Client_Details WHERE cardnumber='" . $cardnumber . "'");
if (mysqli_num_rows($newQuery) > 0)
{
$query = "UPDATE Client_Details SET amount = amount + '" . $amount . "' WHERE cardnumber = '" . $cardnumber . "'";
}
else
{
$query = "INSERT into Client_Details values('$cardnumber',$amount/2)";
}
$query_run = mysqli_query($con, $query);
if ($query_run)
{
echo '<script type="text/javascript">alert("Values inserted successfully")</script>';
}
else
{
echo '<script type="text/javascript">alert("Values not inserted successfully")</script>';
}
}
}
*Modify the table name and column names accordingly
<?php
include('session.php');
?>
<?php
$conn = new mysqli("127.0.0.1","root","","foo");
if ($conn->connect_errno) {
echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}
$sew = $_SESSION['login_user'];
$a = $_GET["en"];
$l = 1;
$d = -1;
if($a == 1)
{
$sqlw = " INSERT into dlkeuser VALUES('$a','$sew')" ;
if ($conn->query($sqlw) === FALSE)
{
echo "you have already disliked the song";
}
else
{
//query1
$sql = " DELETE FROM lkeuser WHERE userid = '$sew' AND songid = '$a' ";
//query2
$sql = "UPDATE liking
SET count = count - 1 ";
if ($conn->query($sql) === TRUE) {
echo "you disliked the song";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
In this php code snippet, query1 is not working whereas query 2 is fine.
I am trying to insert (songid, userid) in dlkeuser(dislike) table against user i/p($_GET["en"]) and delete the record(songid,userid) from lkeuser(like) table if it exists. (songid,userid) pair is the composite primary key here. count is the net like/dislike of a song.
let's try this,
it will work
<?php
include('session.php');
?>
<?php
$conn = new mysqli("127.0.0.1","root","","foo");
if ($conn->connect_errno) {
echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}
$sew = $_SESSION['login_user'];
$a = $_GET["en"];
$l = 1;
$d = -1;
if($a == 1)
{
$sqlw = " INSERT into dlkeuser VALUES('$a','$sew')";
if ($conn->query($sqlw) === FALSE)
{
echo "you have already disliked the song";
}
else
{
//query1
$sql = " DELETE FROM lkeuser WHERE userid = '$sew' AND songid = '$a' " ;
//query2
$sql1 = "UPDATE liking
SET count = count - 1 ";
if ($conn->query($sql) === TRUE) {
echo "deleted the song";
}
if ($conn->query($sql1) === TRUE) {
echo "you disliked the song";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
You need to execute query1, before reuse your $sql variable.
//query1
$sql = " DELETE FROM lkeuser WHERE userid = '$sew' AND songid = '$a' " ;
$conn->query($sql);
//query2
$sql = "UPDATE liking
SET count = count - 1 ";
if ($conn->query($sql) === TRUE) {
You are not executing your query1 anywhere. Just the following code won't execute your query
$sql = " DELETE FROM lkeuser WHERE userid = '$sew' AND songid = '$a' " ;
You need another line like the following (as you did for query2)
if ($conn->query($sql) === TRUE) {
echo "you liked the song";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
This executes the query and also checks for errors.
Below is code for count record for today's date and inserting into database if value is not more than two per day.now problem is I want to insert into database if count for today is below 2.
$user_ip = getenv('REMOTE_ADDR');
$geo = unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=$user_ip"));
$city = $geo["geoplugin_city"];
$region = $geo["geoplugin_regionName"];
$img = $_POST['img'];
$amount = 5;
$sql = "SELECT COUNT(*) FROM `daily_uploads` WHERE DATE_FORMAT(`date`, '%Y-%m-%d') = CURDATE()";
$result = $conn->query($sql);
if ($result->num_rows > 2) {
echo"already exist";
echo "Error: " . $sql . "<br>" . $conn->error;
} else {
$sql = "INSERT INTO `daily_uploads` (img, geoplugin_city, geoplugin_regionName, amount)
VALUES ('$img', '$city', '$region','$amount')";
// echo "success";
}
You have forgotten to execute the insert $sql string, you can do it this way:
if ($conn->query($sql)) {
echo ('success');
} else {
echo ('error');
}
Below I have Php code that loops through an array and for each it checks if the value already exists in the database and if not, create it. The code itself is working but the loop itself can be insanely big, maximum of a couple tens thousand iterations.
How can I optimize this code? What to use and how to use. There should be a better way to insert this many times without looping through each individual.
foreach($arr as $value){
$checkID = mysqli_query($cenn, "SELECT item_id from items WHERE item_id = '$value'");
if (!$checkID) {
die("Query '$checkID' failed to execute for some reason");
}else{
if (mysqli_num_rows($checkID) > 0) {
$user = mysqli_fetch_array($checkID);
echo "item_id" . checkID . "exists already";
}
else{
echo "item_id: '$user_id' doesn't exist<br>";
$gw2Api = file_get_contents("https://api.guildwars2.com/v2/items/" . $user_id); //12452 30704
$gw2Api_result = json_decode($gw2Api,true);
/*Here would be some code to determine values that are being inserted*/
if (!array_key_exists("description",$gw2Api_result)) {
$description = 'No description available...';
} else{
if($gw2Api_result['description'] === ''){
$description = "No description available...";
} else {
$description = $gw2Api_result['description'];
}
}
$insertItem = "INSERT INTO items
(item_id, name, description,
AccountBindOnUse, AccountBound,
last_update
)
VALUES ('$user_id', '$gw2Api_result[name]', '$description',
'$AccountBindOnUse', '$AccountBound', CURRENT_TIMESTAMP)";
if ($cenn->query($insertItem) === true) {
echo "New record '$user_id' created successfully";
} else {
echo "Error: " . $sql . "<br>" . $cenn->error;
}
}
}
} // end foreach
The question: How to insert many values, new rows, into mysqli database as fast as possible.
Just use bulk insert.
Collect all the rows for insertion and pass it in one query.
echo 'hi';
if (!empty($arr)) {
echo 'ok';
$values = "'" . implode("', '", $arr) . "'";
$qExistingItemIds = mysqli_query($cenn, "SELECT item_id from items WHERE item_id IN($values)");
$existingItemIds = [];
while ($existingItemId = mysqli_fetch_array($qExistingItemIds)) {
$existingItemIds[] = $existingItemId['item_id'];
}
$arr = array_diff($arr, $existingItemIds);
$inserts = array();
$i = 0;
$ic = count($arr);
foreach ($arr as $value) {
$i++;
echo "item_id: $value doesn't exist<br>";
$gw2Api = file_get_contents("https://api.guildwars2.com/v2/items/" . $value); //12452 30704
$gw2Api_result = json_decode($gw2Api,true);
/*Here would be some code to determine values that are being inserted*/
if (!array_key_exists("description", $gw2Api_result)) {
$description = 'No description available...';
} else {
if ($gw2Api_result['description'] === '') {
$description = "No description available...";
} else {
$description = $gw2Api_result['description'];
}
}
$inserts[] = "
('$value', '$gw2Api_result[name]', '$description', '$AccountBindOnUse', '$AccountBound', CURRENT_TIMESTAMP)
";
if ($i == 50 OR $i == $ic) {
$inserts = implode(",", $inserts);
$insert = "
INSERT INTO items
(item_id, name, description, AccountBindOnUse, AccountBound, last_update)
VALUES
$inserts
";
if ($cenn->query($insert) === true) {
echo 'great';
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $cenn->error;
}
$ic -= 50;
$i = 0;
$inserts = array();
}
}
}
so now we have only 2 queries. not thousands
details about bulk insert:
http://www.geeksengine.com/database/data-manipulation/bulk-insert.php
If you use prepared statement you should reduce the round trips to the database server and only compile and optimise each query once instead of Number_of_inputs * 2 queries. This should reduce the workload.
I would be very interested to know by how much.
$sql = "SELECT item_id from items WHERE item_id = ?";
$db_select = $cenn->prepare($sql);
if ( ! $db_select ) {
echo $cenn->error;
exit;
}
$sql_insert = "INSERT INTO items
(item_id, name, description,
AccountBindOnUse, AccountBound, last_update)
VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)";
$db_insert = $cenn->prepare($sql);
if ( ! $db_insert ) {
echo $cenn->error;
exit;
}
foreach($arr as $value){
$db_select->bind_param('i', $value);
$res = $db_select->execute()
if ( $res === FALSE ) {
echo $cenn->error;
exit;
}
if ($db_select->num_rows > 0) {
// dont bother fetching data we already know all we need to
$user = $db_select->free();
echo "item_id $value exists already";
} else {
echo "item_id: $value doesn't exist<br>";
$gw2Api = file_get_contents("https://api.guildwars2.com/v2/items/" . $value);
$gw2Api_result = json_decode($gw2Api,true);
if ( ! array_key_exists("description",$gw2Api_result)
|| $gw2Api_result['description'] === '') {
$description = 'No description available...';
} else{
$description = $gw2Api_result['description'];
}
$db_insert->bind_param('issss', $value, $gw2Api_result[name],
$description, $AccountBindOnUse,
$AccountBound)
if ($cenn->query($insertItem) === true) {
echo "New record $value' created successfully";
} else {
echo "Error: " . $sql_insert . "<br>" . $cenn->error;
}
}
} // end foreach
I Am trying to check if the REF number added when creating a new mysql row is already in use. I don't have problems in adding a new row however, the script does not check the database first.
if ($_POST['add_new_bus']){
if (($_POST['add_ref'] != "")&&($_POST['add_name'] != "")&&($_POST['add_address'] != "")&&($_POST['add_area'] != "")){
$add_ref = $_POST['add_ref'];
$add_name = $_POST['add_name'];
$add_address = $_POST['add_address'];
$add_area = $_POST['add_area'];
$chech_sql = "INSERT INTO `Details` (`REF`) VALUES ('$add_ref')";
if (!($conn->query($chech_sql))) {
echo "REF is already in use";
}else{
mysqli_query($conn, "INSERT INTO `Details` (`REF`, `NAME`, `ADDRESS`, `AREA`) VALUES ('$add_ref', '$add_name', '$add_address', '$add_area')");
echo "<p style='float:right;'>" . $_POST['add_name'] . " " . "has been added to the register with REF number:" . " " . $_POST['add_ref'] . "</p>";
}
}
Any Idea how to check if the REF number is already in use?
For giving you a correct idea how to do it, Please check below code:-
<?php
if (isset($_POST['add_new_bus']){
if (($_POST['add_ref'] != "") &&($_POST['add_name'] != "")&&($_POST['add_address'] != "")&&($_POST['add_area'] != "")){
$add_ref = $_POST['add_ref'];
$add_name = $_POST['add_name'];
$add_address = $_POST['add_address'];
$add_area = $_POST['add_area'];
$chech_sql = "SELECT add_ref FROM Details WHERE add_ref = '".$add_ref."'";
$result = $conn->query($chech_sql);
if (mysqli_num_rows($result) > 0) {
echo "REF is already in use";
}else{
mysqli_query($conn, "INSERT INTO `Details` (`REF`, `NAME`, `ADDRESS`, `AREA`) VALUES ('$add_ref', '$add_name', '$add_address', '$add_area')");
echo "<p style='float:right;'>" . $_POST['add_name'] . " " . "has been added to the register with REF number:" . " " . $_POST['add_ref'] . "</p>";
}
}
}
?>
Note:- checking variables value and other things is up to you. because you only have them in your code.thanks.