PHP: Do not create a row if it already exists [duplicate] - php

This question already has answers here:
sql if in insert statement without select
(4 answers)
Closed 7 years ago.
I'm trying to create a row only if one doesn't already exist. I'm trying to check if a row exists with the same steamid, If it exists, do nothing. Otherwise create the row.
Using the following code creates a row everytime I refresh the page.
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM Main WHERE steamid = ".$steamprofile[steamid];
//$sql = "SELECT setup FROM Main WHERE steamid = $steamprofile[steamid]";
$result = $conn->query($sql);
if(!isset($_SESSION['steamid'])) {
steamlogin(); //login button
} else {
include ('../core-auth/userInfo.php'); //To access the $steamprofile array
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if (($row["setup"]) == 1){
echo "<br><div class='container'><div class='jumbotron'><div align='center'>";
echo "<h4>You have already Setup your account!</h4><br>";
echo "<a href='../index.php' class='btn btn-success btn-block' role='button'><span class=' glyphicon glyphicon-ok' aria-hidden='true'></span> Back</a>";
exit;
}
}
} else {
$sql = "INSERT INTO Main (steamname, steamid, warns, notifi, setup)
VALUES ('$steamprofile[personaname]', '$steamprofile[steamid]', '0', '0', '1')";
if ($conn->query($sql) === TRUE) {
echo "Added user account.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
$conn->close();
?>

You forgot to add single quotes to the array variables. Please try the following updated code:
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM Main WHERE steamid = ".$steamprofile['steamid'];
//$sql = "SELECT setup FROM Main WHERE steamid = $steamprofile[steamid]";
$result = $conn->query($sql);
if(!isset($_SESSION['steamid'])) {
steamlogin(); //login button
} else {
include ('../core-auth/userInfo.php'); //To access the $steamprofile array
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if (($row["setup"]) == 1){
echo "<br><div class='container'><div class='jumbotron'><div align='center'>";
echo "<h4>You have already Setup your account!</h4><br>";
echo "<a href='../index.php' class='btn btn-success btn-block' role='button'><span class=' glyphicon glyphicon-ok' aria-hidden='true'></span> Back</a>";
exit;
}
}
} else {
$sql = "INSERT INTO Main (steamname, steamid, warns, notifi, setup)
VALUES ('".$steamprofile['personaname']."', '".$steamprofile['steamid']."', '0', '0', '1')";
if ($conn->query($sql) === TRUE) {
echo "Added user account.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
$conn->close();
?>
Hope this will help you. :)

Related

Current id and Next id

I am able to grab the current poll_id fine and get it to echo out the correct value.
I'm also trying to echo the value from the next row in the table at the moment just the number but it's so I can insert a link to the next poll.
I keep getting the Next Poll Not Available, although I know that there is a "next" poll.
What am I doing wrong?
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT poll_id, poll_question FROM poll_main LIMIT 5, 1";
$nxt = "SELECT poll_id FROM poll_main WHERE ID > ? LIMIT 1";
$result = $conn->query($sql);
$nxtres = $conn->query($nxt);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<input type='hidden' id='poll_id' value='" . $row["poll_id"]. "'/>";
}
} else {
echo "Current Poll Not Available";
}
if ($nxtres->num_rows > 0) {
while($row = $nextres->fetch_assoc()) {
echo $row["poll_id"];
}
} else {
echo "Next Poll Not Available";
}
$conn->close();

Another empty row with time stamp added with every entry in mysql database

another empty row with timestamp added in mysql database each time a new row with entries added ,
here is part of my code
$servername = "localhost";
$username = "root";
$password = "zaheer442";
$dbname = "76H";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "wooo connected";
}
$sql = "INSERT INTO 76Hlog (Device_ID, Response_status, Device_NO, Status, Time) VALUES ('$keywords[4]', '$keywords[8]', '$keywords[15]', '$keywords[17]', now())";
if(mysqli_query($conn, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
//displaying data
$sql = "SELECT Device_ID, Response_status, Device_NO, Status FROM 76H";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["Device_ID"]. " - Staus: " . $row["Response_status"]. " Devic No " . $row["Device_NO"]. " Mode " . $row["Status"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
[Entries Screenshot has also attached]

show echo if column is empty else show another echo

i wrote this code but there is some mistake its only shows the first echo even if the column is not empty.
i wnat the code to show echo "1" if the column subuser1 is empty
else to show echo "2" if the column subuser1 is not empty.
<?php
include_once 'dbconnect.php';
// Create connection
$conn = new mysqli(DBHOST,DBUSER,DBPASS,DBNAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql= ("SELECT subuser1 FROM users WHERE id=".$_SESSION['user'] );
$result = $conn->query($sql);
$subuser1 = $row["subuser1"];
if ($result->num_rows > 0) {
if (empty($subuser1)) {
echo "subuser1 is either 0, empty, or not set at all";
}
} else {
echo " subuser1 not empty";
I solve it like that it works perfect if anyone need it.
<?php
$userR= 0 ;
include_once 'dbconnect.php';
// Create connection
$conn = new mysqli(DBHOST,DBUSER,DBPASS,DBNAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql= ("SELECT * FROM users WHERE id=".$_SESSION['user'] );
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row["subuser1"] == NULL ){
echo ""; }
else {
echo " bla bla bla "
}
}
?>

Is it possible to assign sql table value to a variable in php?

Basically what I want is to assign the value of a field in my database to an variable. Can it be done in an effective way?
I was thinking something like:
$sql2 = mysql_query("SELECT * FROM rom WHERE idrom = 101");
while ($row = mysql_fetch_array($sql2)) {
$rom1 = $row['idrom'];
$status = $row['status'];
echo $rom1;
echo $status;
}
But this doesn't echo anything.
Edit:
I have gotten a bit longer on the way, now I am looking for a simpler way to assign the values to variables. As we speak I only need 4 values, but this still doesn't look like a very good way to accomplish what I want. Any better suggestions?
Heres what I got now:
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM rom WHERE idrom = 101";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$room101 = $row["idrom"];
$status101 = $row["status"];
echo "This is roomnumber ". $room101 . "!<br >";
echo "And the status of roomnumber ". $room101 ." is ". $status101 ."<br><br>";
}
} else {
echo "0 results";
}
$sql2 = "SELECT * FROM rom WHERE idrom = 102";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
// output data of each row
while($row = $result2->fetch_assoc()) {
$room102 = $row["idrom"];
$status102 = $row["status"];
echo "This is roomnumber ". $room102 . "!<br >";
echo "And the status of roomnumber ". $room102 ." is ". $status102 ."<br><br>";
}
} else {
echo "0 results";
}
You can use bind_result to do that.
Please try this simple example, hope it run well :
$mysqli = mysqli_connect('host', 'user', 'pass','dbase')or die('Could not connect: ' . mysqli_error());
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Because you provide an Id in where clause, you can use it for the new variable
$output = array();
$id = 101;
$sql = "select idrom,status from rom where idrom=?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('i',$id);
$stmt->execute();
if ($stmt->errno == 0) {
$stmt->store_result();
// $stmt->bind_result($idrom,$status); // way 1
$stmt->bind_result($output[$id],$output["status".$id]); // way 2
while ($stmt->fetch()) {
echo $output[$id]." -> ".$output["status".$id]."<br />"; // So, your output variable will be like $output[101] for way 2
// or you defined it here like :
// $output[$idrom] = $idrom;
// $output["status".$idrom] = $status; // For way 1
}
} else {
return "Error: " . $sql . "<br>" . $stmt->error;
}
$stmt->close();
$mysqli->close();

Displaying ALL data from sql table in PHP?

When I print my code it only prints the question and description of id = 1 but not the rest of the table.
here is my code.
Please show me how to print my entire table which has like 20 questions or so...and also please show me how to make it so that the questions stay on the browser (even when I refresh the page) because currently the data does not stay on the browser when i refresh the page.
Thanks So Much!
<?php
require_once "connection.php";
if(isset($_POST['submit'])) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
} else {
echo "Submit button connected to database!";
}
$question = $_POST['question'];
$description = $_POST['description'];
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if($conn->query($sql)) {
echo "it worked";
} else {
echo "error: " . $conn->error;
exit();
}
$query = "SELECT * FROM `ask` ";
if( $result = $conn->query($query)) {
$fetch = $result->fetch_assoc();
echo "<p>{$fetch['question']}</p>";
echo "<p>{$fetch['description']}</p>";
} else {
echo "failed to fetch array";
}
}
?>
You need a for each loop:
<?php
require_once "connection.php";
if(isset($_POST['submit'])) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
} else {
echo "Submit button connected to database!";
}
$question = $_POST['question'];
$description = $_POST['description'];
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if($conn->query($sql)) {
echo "it worked";
} else {
echo "error: " . $conn->error;
exit();
}
$query = "SELECT * FROM `ask` ";
if( $result = $conn->query($query)) {
$fetch = mysql_fetch_array($result, MYSQL_ASSOC);
foreach($fetch as $ques) {
echo "<p>" . $ques['question'] . "</p>";
echo "<p>" . $ques['description'] . "</p>";
}
} else {
echo "failed to fetch array";
}
}
?>
All I've done there is change:
$fetch = $result->fetch_assoc();
echo "<p>{$fetch['question']}</p>";
echo "<p>{$fetch['description']}</p>";
to:
$fetch = mysql_fetch_array($result, MYSQL_ASSOC);
foreach($fetch as $ques) {
echo "<p>" . $ques['question'] . "</p>";
echo "<p>" . $ques['description'] . "</p>";
}
fetch_assoc() — Fetch a result row as an associative array
so it gets only 1 row you need to loop through the rest of the rows check the examples reference from php docs

Categories