I am trying to pass a MySQL query into a variable but it is not storing it correctly. I am wanting the query result to be stored as a string.
Here is my attempt:
$authorid = $db->query("SELECT Author_ID FROM Authors WHERE Author_Name = '$author'");
The query works correctly in PHPMyAdmin so I know it is returning the correct information but I am unsure if this is the correct way to store it.
I am trying to use it for this:
$authoredquery = $db->query("SELECT Author_ID, Article_ID
FROM Articles_Authored
WHERE Author_ID = '$authorid' AND Article_ID ='$articleid'");
All of the query is spelled correctly. I was under the impression that this stored the query result as a string....
Here is a portion of the php code that runs after a form is submitted:
$dbHost = "localhost";
$dbUsername = "admin";
$dbPassword = "qegc0Qfs";
$dbName = "webdb";
// Create connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
} else {
// Post PHP variables
$journal = $_POST['journal_radio'];
$article_name = $_POST['article_name'];
$author1 = $_POST['author1_name'];
$author1uni = $_POST['author1_university'];
$author2 = $_POST['author2_name'];
$author2uni = $_POST['author2_university'];
$author3 = $_POST['author3_name'];
$author3uni = $_POST['author3_university'];
$author4 = $_POST['author4_name'];
$author4uni = $_POST['author4_university'];
$author5 = $_POST['author5_name'];
$author5uni = $_POST['author5_university'];
$author6 = $_POST['author6_name'];
$author6uni = $_POST['author6_university'];
$year = $_POST['year'];
$security = $_POST['is_security'];
function authorinfoinsert($author, $number, $authoruni, $articleid, $article, $db){
//check if Author already exists
$authorquery = $db->query("SELECT Author_Name FROM Authors WHERE Author_Name = '$author'");
if($authorquery->num_rows != 0) {
echo '<a href="> New Input </a><br />';
echo 'Author ' . $number . ' - ' . $author . ' - already present<br />';
} else {
//insert author if doesnt exist
$authorinsert = "INSERT INTO Authors (Author_Name) VALUES ('$author')";
if ($db->query($authorinsert) === TRUE) {
echo 'Author ' . $number . ' - ' . $author . ' - created successfully.<br />';
} else {
echo 'Error: ' . $authorinsert . '<br />' . $db->error . '<br />';
}
}
// store Author Author_ID value
$authorid = $db->query("SELECT Author_ID FROM Authors WHERE Author_Name = '$author'");
//check if Author University exists
$authoruniquery = $db->query("SELECT University_Name FROM University WHERE University_Name = '$authoruni'");
if($authoruniquery->num_rows != 0) {
echo ' New Input <br />';
echo 'Author ' . $number . ' University already present <br />';
} else {
//insert university if doesnt exist
$uniinsert = "INSERT INTO University (University_Name) VALUES ('$authoruni')";
if ($db->query($uniinsert) === TRUE) {
echo 'Author ' . $number . ' University - ' . $authoruni . ' - created successfully.<br />';
} else {
echo 'Error: ' . $uniinsert . "<br>" . $db->error . '<br />';
}
}
// store Author University_ID value
$authoruniid = $db->query("SELECT University_ID FROM University WHERE University_Name = '$authoruni'");
echo $authoruniid;
//Enter Author and Article in Articles_Authored
$authoredquery = $db->query("SELECT Author_ID, Article_ID FROM Articles_Authored WHERE Author_ID = '$authorid' AND Article_ID ='$articleid'");
if($authoredquery->num_rows != 0) {
echo ' New Input <br />';
echo 'Article Authored entry for Author ' . $number . ' - ' . $author . ' - already present<br />';
} else {
$articlesauthoredinsert = "INSERT INTO Articles_Authored (Article_ID, Author_ID, Name_Authored_As) VALUES ('$articleid','$authorid','$author')";
if ($db->query($articlesauthoredinsert) === TRUE) {
echo 'Article Authored - Author ' . $number . ' - created successfully <br />';
} else {
echo 'Error: ' . $articlesauthoredinsert . "<br>" . $db->error . '<br />';
}
}
//Enter Author University instance in Author_University
$authoruniinsert = "INSERT INTO Author_University (Article_ID, Author_ID, University_ID) VALUES ('$articleid','$authorid','$authoruniid')";
if ($db->query($authoruniinsert) === TRUE) {
echo 'University instance for Author ' . $number . ' created successfully<br />';
} else {
echo 'Error: ' . $authoruniinsert . "<br>" . $db->error . '<br />';
}
}
And I pass the args to the function like this:
authorinfoinsert($author1, 1, $author1uni, $articleid, $article, $db);
Here is all of the code if that helps. Sorry I know its a lot:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Input Form - Research Ranker</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#article_name" ).autocomplete({
</head>
<body>
<?PHP
if(!isset($_POST['submit'])){
print '
<div class="container-fluid ui-widget">
<form class="form-horizontal" method="post" action="test.php" onsubmit="return confirm("Is all of your data correct?");">
<fieldset>
<!-- Article Input -->
<legend>Article Input</legend>
<!-- Journal Radio Buttons (value is journal ISSN)-->
<div class="form-group">
<label class="col-md-4 control-label" for="journal_radio">Journal</label>
<div class="col-md-4">
<div class="radio">
<label for="journal_radio-0">
<input type="radio" name="journal_radio" id="journal_radio-0" value="2162-9730" checked="checked">
MIS Quarterly
</label>
</div>
<div class="radio">
<label for="journal_radio-1">
<input type="radio" name="journal_radio" id="journal_radio-1" value="1047-7047">
Information Systems Research
</label>
</div>
<div class="radio">
<label for="journal_radio-2">
<input type="radio" name="journal_radio" id="journal_radio-2" value="0742-1222">
Journal of Management Information Systems
</label>
</div>
<div class="radio">
<label for="journal_radio-3">
<input type="radio" name="journal_radio" id="journal_radio-3" value="1536-9323">
Journal of the Association for Information Systems
</label>
</div>
<div class="radio">
<label for="journal_radio-4">
<input type="radio" name="journal_radio" id="journal_radio-4" value="1476-9344">
European Journal of Information Systems
</label>
</div>
<div class="radio">
<label for="journal_radio-5">
<input type="radio" name="journal_radio" id="journal_radio-5" value="1365-2575">
Information Systems Journal
</label>
</div>
<div class="radio">
<label for="journal_radio-6">
<input type="radio" name="journal_radio" id="journal_radio-6" value="0963-8687">
Journal of Strategic Information Systems
</label>
</div>
<div class="radio">
<label for="journal_radio-7">
<input type="radio" name="journal_radio" id="journal_radio-7" value="0268-3962">
Journal of Information Technology
</label>
</div>
<div class="radio">
<label for="journal_radio-8">
<input type="radio" name="journal_radio" id="journal_radio-8" value="0167-9236">
Decision Support Systems
</label>
</div>
<div class="radio">
<label for="journal_radio-9">
<input type="radio" name="journal_radio" id="journal_radio-9" value="0378-7206">
Information and Management
</label>
</div>
</div>
</div>
<!-- Article Name Input-->
<div class="form-group">
<label class="col-md-4 control-label" for="article_name">Article Name:</label>
<div class="col-md-5">
<input id="article_name" name="article_name" type="text" placeholder="Article Name" class="form-control input-md" required="">
</div>
</div>
<!-- Author 1-->
<div class="form-group">
<label class="col-md-4 control-label" for="author1_name">Author 1:</label>
<div class="col-md-4">
<input id="author1_name" name="author1_name" type="text" placeholder="Author Name" class="form-control input-md" required="">
</div>
</div>
<!-- Author 1 University -->
<div class="form-group">
<label class="col-md-4 control-label" for="author1_university">University:</label>
<div class="col-md-4">
<input id="author1_university" name="author1_university" type="text" placeholder="Author University" class="form-control input-md" required="">
</div>
</div>
<!-- Author 2-->
<div class="form-group">
<label class="col-md-4 control-label" for="author2_name">Author 2:</label>
<div class="col-md-4">
<input id="author2_name" name="author2_name" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Author 2 University-->
<div class="form-group">
<label class="col-md-4 control-label" for="author2_university">University:</label>
<div class="col-md-4">
<input id="author2_university" name="author2_university" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Author 3-->
<div class="form-group">
<label class="col-md-4 control-label" for="author3_name">Author 3:</label>
<div class="col-md-4">
<input id="author3_name" name="author3_name" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Author 3 University-->
<div class="form-group">
<label class="col-md-4 control-label" for="author3_university">University:</label>
<div class="col-md-4">
<input id="author3_university" name="author3_university" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Author 4-->
<div class="form-group">
<label class="col-md-4 control-label" for="author4_name">Author 4: </label>
<div class="col-md-4">
<input id="author4_name" name="author4_name" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Author 4 University-->
<div class="form-group">
<label class="col-md-4 control-label" for="author4_university">University:</label>
<div class="col-md-4">
<input id="author4_university" name="author4_university" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Author 5-->
<div class="form-group">
<label class="col-md-4 control-label" for="author5_name">Author 5:</label>
<div class="col-md-4">
<input id="author5_name" name="author5_name" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Author 5 University-->
<div class="form-group">
<label class="col-md-4 control-label" for="author5_university">University:</label>
<div class="col-md-4">
<input id="author5_university" name="author5_university" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Author 6-->
<div class="form-group">
<label class="col-md-4 control-label" for="author6_name">Author 6:</label>
<div class="col-md-4">
<input id="author6_name" name="author6_name" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Author 6 University-->
<div class="form-group">
<label class="col-md-4 control-label" for="author6_university">University:</label>
<div class="col-md-4">
<input id="author6_university" name="author6_university" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Select Year Published -->
<div class="form-group">
<label class="col-md-4 control-label" for="year">Year Published</label>
<div class="col-md-4">
<select id="year" name="year" class="form-control">
<option value="2010">2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
</select>
</div>
</div>
<!-- Is Security Checkbox -->
<div class="form-group">
<label class="col-md-4 control-label" for="is_security"></label>
<div class="col-md-4">
<label class="checkbox-inline" for="is_security-0">
<input type="checkbox" name="is_security" id="is_security" value="1">
Security Related
</label>
</div>
</div>
<!-- Submit Form Button -->
<div class="form-group">
<div class="col-md-4 control-label">
<button id="submit" name="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</fieldset>
</form>
</div>';
} else {
$dbHost = "localhost";
$dbUsername = "admin";
$dbPassword = "qegc0Qfs";
$dbName = "webdb";
// Create connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
} else {
// Post PHP variables
$journal = $_POST['journal_radio'];
$article_name = $_POST['article_name'];
$author1 = $_POST['author1_name'];
$author1uni = $_POST['author1_university'];
$author2 = $_POST['author2_name'];
$author2uni = $_POST['author2_university'];
$author3 = $_POST['author3_name'];
$author3uni = $_POST['author3_university'];
$author4 = $_POST['author4_name'];
$author4uni = $_POST['author4_university'];
$author5 = $_POST['author5_name'];
$author5uni = $_POST['author5_university'];
$author6 = $_POST['author6_name'];
$author6uni = $_POST['author6_university'];
$year = $_POST['year'];
$security = $_POST['is_security'];
function authorinfoinsert($author, $number, $authoruni, $articleid, $article, $db){
//check if Author already exists
$authorquery = $db->query("SELECT Author_Name FROM Authors WHERE Author_Name = '$author'");
if($authorquery->num_rows != 0) {
echo ' New Input <br />';
echo 'Author ' . $number . ' - ' . $author . ' - already present<br />';
} else {
//insert author if doesnt exist
$authorinsert = "INSERT INTO Authors (Author_Name) VALUES ('$author')";
if ($db->query($authorinsert) === TRUE) {
echo 'Author ' . $number . ' - ' . $author . ' - created successfully.<br />';
} else {
echo 'Error: ' . $authorinsert . '<br />' . $db->error . '<br />';
}
}
// store Author Author_ID value
$authorid = $db->query("SELECT Author_ID FROM Authors WHERE Author_Name = '$author'");
//check if Author University exists
$authoruniquery = $db->query("SELECT University_Name FROM University WHERE University_Name = '$authoruni'");
if($authoruniquery->num_rows != 0) {
echo ' New Input <br />';
echo 'Author ' . $number . ' University already present <br />';
} else {
//insert university if doesnt exist
$uniinsert = "INSERT INTO University (University_Name) VALUES ('$authoruni')";
if ($db->query($uniinsert) === TRUE) {
echo 'Author ' . $number . ' University - ' . $authoruni . ' - created successfully.<br />';
} else {
echo 'Error: ' . $uniinsert . "<br>" . $db->error . '<br />';
}
}
// store Author University_ID value
$authoruniid = $db->query("SELECT University_ID FROM University WHERE University_Name = '$authoruni'");
echo $authoruniid;
//Enter Author and Article in Articles_Authored
$authoredquery = $db->query("SELECT Author_ID, Article_ID FROM Articles_Authored WHERE Author_ID = '$authorid' AND Article_ID ='$articleid'");
if($authoredquery->num_rows != 0) {
echo ' New Input <br />';
echo 'Article Authored entry for Author ' . $number . ' - ' . $author . ' - already present<br />';
} else {
$articlesauthoredinsert = "INSERT INTO Articles_Authored (Article_ID, Author_ID, Name_Authored_As) VALUES ('$articleid','$authorid','$author')";
if ($db->query($articlesauthoredinsert) === TRUE) {
echo 'Article Authored - Author ' . $number . ' - created successfully <br />';
} else {
echo 'Error: ' . $articlesauthoredinsert . "<br>" . $db->error . '<br />';
}
}
//Enter Author University instance in Author_University
$authoruniinsert = "INSERT INTO Author_University (Article_ID, Author_ID, University_ID) VALUES ('$articleid','$authorid','$authoruniid')";
if ($db->query($authoruniinsert) === TRUE) {
echo 'University instance for Author ' . $number . ' created successfully<br />';
} else {
echo 'Error: ' . $authoruniinsert . "<br>" . $db->error . '<br />';
}
}
//check if article exist
$articlequery = $db->query("SELECT Article_Title, ISSN FROM Articles WHERE Article_Title = '$article_name' AND ISSN = '$journal'");
if($articlequery->num_rows != 0) {
echo ' New Input <br />';
echo "<script type= 'text/javascript'>alert('Article Already Present');</script>";
} else {
//insert article if doesn't exist
$articleinsert = "INSERT INTO Articles (ISSN, Year_Published, Is_Security, Article_Title)
VALUES ('$journal','$year','$security','$article_name')";
if ($db->query($articleinsert) === TRUE) {
echo 'New Article - ' . $article_name . ' - created successfully<br />';
} else {
echo 'Error: ' . $articleinsert . "<br>" . $db->error . '<br />';
}
// store Article_ID value
$articleid = $db->query("SELECT Article_ID FROM Articles WHERE Article_Title = '$article_name' AND ISSN = '$journal'");
//insert author 1 info
authorinfoinsert($author1, 1, $author1uni, $articleid, $article, $db);
//check if Author 2 has input
if (isset($author2)){
authorinfoinsert($author2, 2, $author2uni, $articleid, $article, $db);
}
//check if Author 3 has input
if (isset($author3)){
authorinfoinsert($author3, 3, $author3uni, $articleid, $article, $db);
}
//check if Author 4 has input
if (isset($author4)){
authorinfoinsert($author4, 4, $author4uni, $articleid, $article, $db);
}
//check if Author 5 has input
if (isset($author5)){
authorinfoinsert($author5, 5, $author5uni, $articleid, $article, $db);
}
//check if Author 6 has input
if (isset($author6)){
authorinfoinsert($author6, 6, $author6uni, $articleid, $article, $db);
} else{
$db->close();
}
}
}
}
?>
</body>
</html>
Okay so from what you've told me, you're trying to use the object as a string, which is why it's not working.
$authorid is just $db->query(); which returns an object that you need to do something with. In this case, you need to grab the results from it like so:
$result = $db->query("SELECT Author_ID FROM Authors WHERE Author_Name = '$author'");
$row = $result->fetch_assoc();
$authorid = $row['Author_ID'];
Try that :)
My best guess is that it's returning an array rather than a string, which is why "echo" and "print" won't work.
You might try print_r($authoruniid) to see the structure of the array, then access your data through there.
I think you need to use mysqli fetch_assoc() to getting result of query
you must change your code to:
$dbHost = "localhost";
$dbUsername = "admin";
$dbPassword = "qegc0Qfs";
$dbName = "webdb";
// Create connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
} else {
// Post PHP variables
$journal = $_POST['journal_radio'];
$article_name = $_POST['article_name'];
$author1 = $_POST['author1_name'];
$author1uni = $_POST['author1_university'];
$author2 = $_POST['author2_name'];
$author2uni = $_POST['author2_university'];
$author3 = $_POST['author3_name'];
$author3uni = $_POST['author3_university'];
$author4 = $_POST['author4_name'];
$author4uni = $_POST['author4_university'];
$author5 = $_POST['author5_name'];
$author5uni = $_POST['author5_university'];
$author6 = $_POST['author6_name'];
$author6uni = $_POST['author6_university'];
$year = $_POST['year'];
$security = $_POST['is_security'];
function authorinfoinsert($author, $number, $authoruni, $articleid, $article, $db) {
//check if Author already exists
$authorquery = $db->query("SELECT Author_Name FROM Authors WHERE Author_Name = '$author'");
if ($authorquery->num_rows != 0) {
echo ' New Input <br />';
echo 'Author ' . $number . ' - ' . $author . ' - already present<br />';
} else {
//insert author if doesnt exist
$authorinsert = "INSERT INTO Authors (Author_Name) VALUES ('$author')";
if ($db->query($authorinsert) === TRUE) {
echo 'Author ' . $number . ' - ' . $author . ' - created successfully.<br />';
} else {
echo 'Error: ' . $authorinsert . '<br />' . $db->error . '<br />';
}
}
// store Author Author_ID value
$authorid = $db->query("SELECT Author_ID FROM Authors WHERE Author_Name = '$author'");
while ($row = $authorid->fetch_assoc()) {
/
echo $row['Author_ID'];
}
//check if Author University exists
$authoruniquery = $db->query("SELECT University_Name FROM University WHERE University_Name = '$authoruni'");
if ($authoruniquery->num_rows != 0) {
echo ' New Input <br />';
echo 'Author ' . $number . ' University already present <br />';
} else {
//insert university if doesnt exist
$uniinsert = "INSERT INTO University (University_Name) VALUES ('$authoruni')";
if ($db->query($uniinsert) === TRUE) {
echo 'Author ' . $number . ' University - ' . $authoruni . ' - created successfully.<br />';
} else {
echo 'Error: ' . $uniinsert . "<br>" . $db->error . '<br />';
}
}
// store Author University_ID value
$authoruniid = $db->query("SELECT University_ID FROM University WHERE University_Name = '$authoruni'");
while ($row = $authorid->fetch_assoc()) {/// better use this in a while loop to getting all records
echo $row['University_ID'];
}
//Enter Author and Article in Articles_Authored
$authoredquery = $db->query("SELECT Author_ID, Article_ID FROM Articles_Authored WHERE Author_ID = '$authorid' AND Article_ID ='$articleid'");
if ($authoredquery->num_rows != 0) {
echo ' New Input <br />';
echo 'Article Authored entry for Author ' . $number . ' - ' . $author . ' - already present<br />';
} else {
$articlesauthoredinsert = "INSERT INTO Articles_Authored (Article_ID, Author_ID, Name_Authored_As) VALUES ('$articleid','$authorid','$author')";
if ($db->query($articlesauthoredinsert) === TRUE) {
echo 'Article Authored - Author ' . $number . ' - created successfully <br />';
} else {
echo 'Error: ' . $articlesauthoredinsert . "<br>" . $db->error . '<br />';
}
}
//Enter Author University instance in Author_University
$authoruniinsert = "INSERT INTO Author_University (Article_ID, Author_ID, University_ID) VALUES ('$articleid','$authorid','$authoruniid')";
if ($db->query($authoruniinsert) === TRUE) {
echo 'University instance for Author ' . $number . ' created successfully<br />';
} else {
echo 'Error: ' . $authoruniinsert . "<br>" . $db->error . '<br />';
}
}
for more information about mysql_fetch_assoc() click here
Related
Im working on a Opencart project and Im having trouble getting input data into db table. Currently when i submit it enters an empty record into the db.
I have a form that has several inputs and a save button. The query from the model works just fine when entered in phpmyadmin so Im having issues between the view and controller. This is a large pr0ject is overly confusing to me. Any help would be appreciated
html:
" class="btn btn-primary">
<form method="post" enctype="multipart/form-data" id="form-campaign" class="form-horizontal">
<div class="form-group">
<div class="col-sm-5 col-sm-push-1 form-group required>
<label class="col-sm-2 control-label" for="input-campaign-name"><?php echo $entry_name; ?></label>
<input type="text" name="name" value="" placeholder="<?php echo $entry_name; ?>" id="input-campaign-name" class="form-control" />
<?php if (isset($error_name[$language['language_id']])) { ?>
<div class="text-danger"><?php echo $error_name[$language['language_id']]; ?></div>
<?php } ?>
</div>
</div>
<div class="col-sm-5 col-sm-push-1 form-group required>
<label class="col-sm-2 control-label" for="input-campaign-goal"><?php echo $entry_goal; ?></label>
<input type="text" name="goal" value="" placeholder="<?php echo $entry_goal; ?>" id="input-campaign-goal" class="form-control" />
<?php if (isset($error_name[$language['language_id']])) { ?>
<div class="text-danger"><?php echo $error_name[$language['language_id']]; ?></div>
<?php } ?>
</div>
</div>
</form>
php: controller
public function add() {
$this->load->language('campaigns/campaign');
$this->document->setTitle($this->language->get('heading_title'));
$this->load->model('campaigns/campaign');
if (($this->request->server['REQUEST_METHOD'] == 'POST')) {
$this->model_campaigns_campaign->addCampaign($this->request->post);
$this->session->data['success'] = $this->language->get('text_success');
$url = '';
if (isset($this->request->get['filter_campaign_id'])) {
$url .= '&filter_campaign_id=' . $this->request->get['filter_campaign_id'];
}
if (isset($this->request->get['filter_campaign_name'])) {
$url .= '&filter_campaign_name=' . urlencode(html_entity_decode($this->request->get['filter_campaign_name'], ENT_QUOTES, 'UTF-8'));
}
if (isset($this->request->get['filter_campaign_goal'])) {
$url .= '&filter_campaign_goal=' . $this->request->get['filter_campaign_goal'];
}
if (isset($this->request->get['order'])) {
$url .= '&order=' . $this->request->get['order'];
}
if (isset($this->request->get['page'])) {
$url .= '&page=' . $this->request->get['page'];
}
$this->response->redirect($this->url->link('campaigns/campaign', 'token=' . $this->session->data['token'] . $url, true));
}
$this->getForm();
}
php: model
public function addCampaign() {
$this->db->query("INSERT INTO " . DB_PREFIX . "campaigns SET campaign_name = '" . $this->db->escape($data['campaign_name']) . "', campaign_giving_goal = '" . (float)$data['campaign_giving_goal']
. "', campaign_giving_count_goal = '" . (float)$data['campaign_giving_count_goal'] . "', campaign_owner = '" . $this->db->escape($data['campaign_owner']). "'");
$this->cache->delete('campaign');
return $campaign_id;
}
I am getting this error message when I am submitting the changes of the user info.
Do I have to change the connection of the other page code:
I user to use mysqli_real_escape_string() and it was working fine:
mysqli_connect.php
<?php
/* # suppresses error messages*/
class Database
{
private $LOCAL_DB=0;
protected $dbc = NULL;
public function getConnection()
{
if (!$this->LOCAL_DB){
if($this->dbc==NULL)
$this->dbc = mysqli_connect('localhost','root',NULL,'TestProject');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die('b0ther');
}
}
else
{
$this->dbc = #mysqli_connect(localhost,'root','','test');
////# is an error suppression operator
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die('b0ther');
}
}
return $this->dbc;
}
public function closeDB()
{
mysqli_close($this->dbc);
}
}
/* this file should be stored outside of the web directory for security purposes - this will
* prevent a web browser from being able to see it
*/
//print_r($dbc);
/*$mySQL = 'SELECT * from test.Users;';
$res = mysqli_query($mySQL, $dbc);
if($res == FALSE)
echo "Query Failed";
mysqli_close($dbc) or die('close db failed');
*/
?>
EditProfile.php
<?php
$page_title = 'Edit User Profile User';
include 'header.php';
echo '<h1>Edit Profile</h1>';
include "mysqli_connect.php";
$db = new Database();
$dbc = $db->getConnection();
$id = $_SESSION['userID'];
if (isset($_POST['submitted'])) {
$userFname;
$userLname;
$userAddress1;
$userAddress2;
$userAddress3;
$userPhone;
$userImage;
$userEmail;
$userName;
$errorMsg;
$dbc = null;
$errors = array();
if (empty($_POST['userFname']))
$errors[] = 'You must enter a first name';
else
$userFname = mysqli_real_escape_string($dbc, trim($_POST['userFname']));
if (empty($_POST['userLname']))
$errors[] = 'You must enter a last name';
else
$userLname = mysqli_real_escape_string($dbc, trim($_POST['userLname']));
if (empty($_POST['userName']))
$errors[] = 'You must enter a username';
else
$userName = mysqli_real_escape_string($dbc, trim($_POST['userName']));
if (empty($_POST['userEmail']))
$errors[] = 'You must enter email address';
else
$userEmail = mysqli_real_escape_string($dbc, trim($_POST['userEmail']));
if (empty($_POST['userPhone']))
$errors[] = 'You must enter a phone number';
else
$userPhone = mysqli_real_escape_string($dbc, trim($_POST['userPhone']));
if (empty($_POST['userAddress1']))
$errors[] = 'You must enter address line 1';
else
$userAddress1 = mysqli_real_escape_string($dbc, trim($_POST['userAddress1']));
if (empty($_POST['userAddress2']))
$errors[] = 'You must enter address line 2';
else
$userAddress2 = mysqli_real_escape_string($dbc, trim($_POST['userAddress2']));
if (empty($_POST['userAddress3']))
$errors[] = 'You must enter address line 3';
else
$userAddress3 = mysqli_real_escape_string($dbc, trim($_POST['userAddress3']));
if (!empty($errors)) {
echo '<p class="error"> The following errors occurred: <br />';
foreach ($errors as $err) {
echo "$err <br />";
}
echo '</p>';
} else { //update the user
$q = "update users set userFname='$UserFname', userLname='$userLname',userName='$userName', userEmail='$UserEmail',userPhone='$UserPhone',userAdress1='$userAdress1', userAdress2='$userAdress2',userAdress3='$userAdress3',where userID = $id";
$r = mysqli_query($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) {
//print success message
echo '<p class="info"> User information updated Successfully!</p>';
} else {
echo '<p class="error"> Error occured - User not updated</p>';
echo '<p>' . mysqli_error($dbc) . '</p>';
echo '<p>' . $q . '</p>';
}
}
} // end if submitted conditional
//else
//always show form {
$q = "SELECT userFname, userLname, userName, userEmail, userImage, userPhone, userAddress1 , userAddress2, userAddress3 from users where userID = $id";
echo '<br>';
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r);
$userPic = $row[4];
//show avatar
echo '<center> <img src="' .'./images/'. $userPic . '"height="150" width="150" ></center><br><br>';
//print form
echo'
<div id="stylized" class="myform">
<form action="EditProfile.php" method="post">
<div align="center">
<fieldset>
<h3>Edit User: ' . $row[0] . ' ' . $row[1] . '</h3>
<br />
<label>First Name</label> <input type="text" name="userFname" value="' . $row[0] . '" />
<br> <label>Last Name</label> <input type="text" name="userLname" value="' . $row[1] . '"/>
<br> <label>User Name</label> <input type="text" name="userName" value="' . $row[2] . '"/>
<br> <label>Email Address</label> <input type="text" name="userEmail" value="' . $row[3] . '"/>
<br> <label>Phone number</label> <input type="text" name="userPhone" value="' . $row[5] . '"/>
<br> <label>Address 1</label> <input type="text" name="userAddress1" value="' . $row[6] . '"/>
<br> <label>Address 2</label> <input type="text" name="userAddress2" value="' . $row[7] . '"/>
<br> <label>Address 3</label> <input type="text" name="userAddress3" value="' . $row[8] . '"/>
';
echo'
<div align="center">
<input type="submit" name="submit" value="Update" class ="DB4Button" align ="center" />
<input type ="hidden" name="submitted" value="TRUE">
<input type ="hidden" name="id" value="' . $id . '"/>
</div>
</fieldset>
</form>
</div>';
echo '<br />';
echo '<h2>Change Avatar</h2>';
echo '<img src=" pass.png "height="30" width="40" >Change Password';
include 'footer.html';
?>
I am trying to store the form data into database using ajax but it doesn't shows any success neither any error.
Here is my code.
<form method="POST" id="add_user" name='reg' >
<fieldset>
<legend>Student information:-</legend>
<ul>
<li>
<label> FirstName: </label><input type="text" id="name" name="name" required>
<span id='error' style="display:none;color:red;"> Only alphabets </span>
</li>
<li>
<label> LastName: </label><input type="text" id="lname" name="lname" required>
<span id='error1' style="display:none;color:red;"> Only alphabets </span>
</li>
<li>
<label>Username:</label>
<input type="text" id="username" name="username"/>
< /li>
<li>
<label>Password:</label>
<input type="password" id="password" name="password"/>
</li>
<label>
Gender: </label>
<input type="radio" id='gender' name="gender" value="male" required> Male
<input type="radio" name="gender" id='gender' value="female" required> Female
<input type="radio" name="gender" id='gender' value="other" required> Other
<li>
<label>
Email: </label>
<input id="email" type="text" name="email" required>
<span id='error2' style="display:none;color:red;"> Invalid email </span>
</li>
<li>
<label> Mobile:</label>
<input id="mobile" type="text" maxlength="10" name="mobile" required >
<span id='error3' style="display:none;color:red;"> only digits </span>
</li>
<li>
address: <textarea name="address" type="text" rows="3" cols="40"> </textarea>
</li>
</ul>
<p><button class = 'button' type="submit" id='submit'>Add User</button></p>
</fieldset>
</form>
This form in which i enter any values it got stored into database.
Here is my js file which uses ajax function to send data inext file which stores the result into database
serve.js
$(document).ready(function(){
$(document).on('submit','#add_user',function(e){
var form_data = $('#add_user').serialize();
var request = $.ajax({
url: 'fun.php?job=add',
cache : false,
data : form_data,
dataType : 'json',
contentType : 'application/json; charset=utf-8',
type : 'get'
});
request.done(function(output){
if (output.result == 'success'){
var name = $('#fname').val();
show_message("User '" + name + "' added successfully.", 'success' );
}, true);
} else{
show_message('Add request failed','error');
};
});
});
fun.php
if ($job != ''){
// Connect to database
$db_connection = mysqli_connect($db_server, $db_username, $db_password, $db_name);
if (mysqli_connect_errno()){
$result = 'error';
$message = 'Failed to connect to database: ' . mysqli_connect_error();
$job = '';
}
if ($job == 'add'){
/ / Add user
$query = "INSERT INTO oops ";
if (isset($_GET['name'])) { $query .= "name = '" . mysqli_real_escape_string($db_connection, $_GET['name']) . "', "; }
if (isset($_GET['lname'])) { $query .= "lname = '" . mysqli_real_escape_string($db_connection, $_GET['lname']) . "', "; }
if (isset($_GET['username'])) { $query .= "username = '" . mysqli_real_escape_string($db_connection, $_GET['username']) . "', "; }
if (isset($_GET['password'])) { $query .= "password = '" . mysqli_real_escape_string($db_connection, $_GET['password']) . "', "; }
if (isset($_GET['gender'])) { $query .= "gender = '" . mysqli_real_escape_string($db_connection, $_GET['gender']) . "', "; }
if (isset($_GET['email'])) { $query .= "email = '" . mysqli_real_escape_string($db_connection, $_GET['email']) . "', "; }
if (isset($_GET['mobile'])) { $query .= "mobile = '" . mysqli_real_escape_string($db_connection, $_GET['mobile']) . "', "; }
if (isset($_GET['address'])) { $query .= "address = '" . mysqli_real_escape_string($db_connection, $_GET['address']) . "'"; }
$query = mysqli_query($db_connection, $query);
if (!$query){
$result = 'error';
$message = 'query error';
} else {
$result = 'success';
$message = 'query success';
}
}
// Close database connection
mysqli_close($db_connection);
}
// Prepare data
$data = array(
"result" => $result,
"message" => $message,
"data" => $mysql_data
);
// Convert PHP array to JSON array
$json_data = json_encode($data);
print $json_data;
?>
Am I missing something please help if you found any fault in my code.
because you are using post method in your form:
<form method="POST" id="add_user" name='reg' >
and trying to receive params via get:
isset($_GET['name'])
just use post method everywhere
and also in jQuery you need to set:
type: "POST"
As i am newbie to PHP kindly pardon me if i looks silly ,
I created a form in php , while i do the update part of the form the update reflects in db whereas in the form it still shows the same old value . i tried refresh and force refresh but nothing changes .
Whereas if i logout and login again , the form shows the updated value .
I tried using die(); after mysql_close($link); but it logs out the session and needs to re-login .
Kindly help me on viewing the changes while i am still inside the login .
My code is as follows :
<?php
if(isset($_POST['update'])) {
$name_a = $_POST['name'];
$email_a = $_POST['email'];
$pass_a = $_POST['password'];
$sql = "UPDATE admin SET a_name = '$name_a', a_email = '$email_a', password = '$pass_a' where aid='$update_id' ";
$retval = mysql_query($sql,$link);
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($link);
}else {
?>
<!-- Widget: user widget style 1 -->
<div class="box box-widget widget-user-2">
<!-- Add the bg color to the header using any of the bg-* classes -->
<div class="widget-user-header bg-yellow">
<div class="widget-user-image">
<?php echo '<img src="' . $img . '" class="img-circle" alt="User Image">'; ?>
</div>
<!-- /.widget-user-image -->
<h3 class="widget-user-username"><?php echo "$name"; ?></h3>
<h5 class="widget-user-desc"><?php echo "$role"; ?></h5>
</div>
<div class="box-footer no-padding">
<form role="form" method = "post" action = "<?php $_PHP_SELF ?>">
<div class="box-body">
<div class="form-group">
<label for="exampleInputName1">Name</label>
<input type="text" class="form-control" id="exampleInputName1" name="name" value="<?php echo "$name"; ?>">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" name="email" value="<?php echo "$email"; ?>">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" name="password" value="<?php echo "$password"; ?>">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="update" id="update" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
<!-- /.widget-user -->
<?php
}
?>
SOLUTION
1) use the updated value like $name_a instead of $name because $name_a contain updated value and $name contain old value
2) reload page after update and get new value from database on page load and store that value in $name , $email etc variable (if new data update successfully in database then only you get new value )
3) if You store your data in session or cookie then update session and cookie value also when you update in database
Try this:
<?php
$name = '';
$email = '';
$password = '';
$update_id = '';
//$img = '';
//$role = '';
//$link = null;
if(
isset($_POST['update']) &&
isset($_POST['id']) &&
isset($_POST['name']) &&
isset($_POST['email']) &&
isset($_POST['password'])
) {
$update_id = mysql_real_escape_string($_POST['id']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
$sql = 'UPDATE admin SET a_name = \'' . $name . '\', a_email = \'' . $email . '\', password = \'' . $password . '\' WHERE aid = \'' . $update_id . '\'';
$result = #mysql_query($sql, $link);
if(!$result)
die('Could not update data: ' . mysql_error($link));
echo 'Updated data successfully', "\n";
}
elseif(isset($_GET['id'][0])) {
$update_id = mysql_real_escape_string($_GET['id']);
$sql = 'SELECT a_name,a_email,a_password FROM admin WHERE aid = \'' . $update_id . '\'';
$result = #mysql_query($sql, $link);
if($result) {
$result = mysql_fetch_row($result);
$name = $result[0];
$email = $result[1];
$password = $result[2];
}
else {
echo 'Could not find the id.' . "\n";
$update_id = '';
}
}
unset($result);
if(isset($update_id[0])) {
mysql_close($link);
?>
<!-- Widget: user widget style 1 -->
<div class="box box-widget widget-user-2">
<!-- Add the bg color to the header using any of the bg-* classes -->
<div class="widget-user-header bg-yellow">
<div class="widget-user-image">
<img src="<?php echo htmlspecialchars($img); ?>" class="img-circle" alt="User Image">
</div>
<!-- /.widget-user-image -->
<h3 class="widget-user-username"><?php echo htmlspecialchars($name); ?></h3>
<h5 class="widget-user-desc"><?php echo htmlspecialchars($role); ?></h5>
</div>
<div class="box-footer no-padding">
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="hidden" name="id" value="<?php echo htmlspecialchars($update_id); ?>">
<div class="box-body">
<div class="form-group">
<label for="exampleInputName1">Name</label>
<input type="text" class="form-control" id="exampleInputName1" name="name" value="<?php echo htmlspecialchars($name); ?>">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" name="email" value="<?php echo htmlspecialchars($email); ?>">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" name="password" value="<?php echo htmlspecialchars($password); ?>">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="update" id="update" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
<!-- /.widget-user -->
<?php }
else {
$sql = 'SELECT aid,a_name FROM admin';
$result = #mysql_query($sql, $link);
if($result) {
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '' . $row['a_name'] . '<br />' . "\n";
}
}
mysql_close($link);
}
?>
As #DivyeshSavaliya mentioned in the comment the issue is ,
I didn't Used Select query after update . Once done that the issue solved
The new working code is
<?php
if(isset($_POST['update'])) {
$name_a = $_POST['name'];
$email_a = $_POST['email'];
$pass_a = $_POST['password'];
$sql = "UPDATE admin SET a_name = '$name_a', a_email = '$email_a', password = '$pass_a' where aid='$update_id' ";
$retval = mysql_query($sql,$link);
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
}
$result = mysql_query("SELECT * FROM admin where aid='$update_id' ",$link);
while($row = mysql_fetch_array($result)){
$name = $row['a_name'];
$email = $row['a_email'];
$password = $row['password'];
}
mysql_close($link);
?>
Thanks to #DivyeshSavaliya
I have a form as part of a custom plugin, but it is not retaining the data when submitted. It saves in the database, and if I refresh the page it shows the information, but I want it to stay in the form first time.
I know it must be something really stupid, I just don't seem to find it... Thanks in advance!
This is the code:
<?php
global $guarantor_details;
add_shortcode('guarantorForm', 'guarantor_form');
function guarantor_form()
{
$output = "";
global $current_user;
$current_user = wp_get_current_user();
$guarantor_details = getGuarantorData();
$message = (isset($_POST["guarantor_save"])) ? saveGuarantor() : false;
if ($message) $output .= '<div class="success">' . $message . '</div>';
$message = (isset($_GET["resend"]) == "true") ? generateGuarantorEmail($guarantor_details) : false;
if ($message) $output .= '<div class="success">' . $message . '</div>';
if($current_user->ID){
$output .= '
<h1>Guarantor Details</h1>
<form action="" method="POST" class="profileForm">
<div class="formField">
<label for="guarantor_title">Title</label>
<select name="guarantor_title">
<option value="Mr">Mr</option>
<option value="Miss">Miss</option>
<option value="Mrs">Mrs</option>
<option value="Ms">Ms</option>
</select>
</div>
<div class="formField">
<label for="guarantor_name">Guarantor Full Name</label>
<input name="guarantor_name" type="text" required
value="' . $guarantor_details->guarantor_name . '"/>
</div>
<div class="formField">
<label for="guarantor_relationship">Relationship to student</label>
<input name="guarantor_relationship" type="text" required
value="' . $guarantor_details->guarantor_relationship . '"/>
</div>
<div class="formField">
<label for="guarantor_address1">Address 1</label>
<input name="guarantor_address1" type="text" required
value="' . $guarantor_details->guarantor_address1 . '"/>
</div>
<div class="formField">
<label for="guarantor_address2">Address 2</label>
<input name="guarantor_address2" type="text" value="' . $guarantor_details->guarantor_address2 . '"/>
</div>
<div class="formField">
<label for="guarantor_city">City</label>
<input name="guarantor_city" type="text" required
value="' . $guarantor_details->guarantor_city . '"/>
</div>
<div class="formField">
<label for="guarantor_county">County</label>
<input name="guarantor_county" type="text" required
value="' . $guarantor_details->guarantor_county . '"/>
</div>
<div class="formField">
<label for="guarantor_postcode">Postcode</label>
<input name="guarantor_postcode" type="text" required
value="' . $guarantor_details->guarantor_postcode . '"/>
</div>
<div class="formField">
<label for="guarantor_country">Country</label>
<select name="guarantor_country">
' . countryList() . '
</div>
<div class="formField">
<label for="guarantor_mobile">Mobile</label>
<input name="guarantor_mobile" type="tel" required
value="' . $guarantor_details->guarantor_mobile . '"/>
</div>
<div class="formField">
<label for="guarantor_confirm_mobile">Confirm Mobile</label>
<input name="guarantor_confirm_mobile" id="confirm_mobile" type="tel" required value="' . $guarantor_details->guarantor_mobile . '"/>
</div>
<div class="formField">
<label for="guarantor_telephone">Telephone</label>
<input name="guarantor_telephone" type="tel" required
value="' . $guarantor_details->guarantor_telephone . '"/>
</div>
<div class="formField">
<label for="guarantor_email">Email</label>
<input name="guarantor_email" type="email" required
value="' . $guarantor_details->guarantor_email . '"/>
</div>
<div class="formField">
<input name="guarantor_save" type="submit" value="Save"/>
</div>
<div class="formField alignRight">
Lost the email with the link? Resend Email
</div>
</form>
';}
else{
$output = 'You must login to fill in guarantor details.';
}
return $output;
}
function getGuarantorData()
{
global $current_user;
global $wpdb;
$table = $wpdb->prefix . 'vebra_tenants';
$guarantor_details = $wpdb->get_row(
"
SELECT *
FROM $table
WHERE tenant_user_id = $current_user->ID
"
);
return isset($guarantor_details) ? $guarantor_details : false;
return $guarantor_details;
}
//save guarantor details
function saveGuarantor()
{
global $wpdb;
global $current_user;
$guarantor_details = getGuarantorData();
$details = $_POST;
unset($details["guarantor_save"]); //no submit
unset($details["guarantor_confirm_mobile"]); //no submit
if ($guarantor_details) {
$wpdb->update(
$wpdb->prefix . 'vebra_tenants',
$details,
array('tenant_user_id' => $current_user->ID));
} else {
$details['tenant_user_id'] = $current_user->ID;
$wpdb->insert($wpdb->prefix . 'vebra_tenants', $details);
$guarantor_details = getGuarantorData();
}
//let db know details updated
update_user_meta($current_user->ID, 'vebra_guarantor_details', true );
//send email if not already sent
if ($guarantor_details->guarantor_hash == "") {
generateGuarantorEmail($guarantor_details);
return "The guarantor details have been saved and an email has been sent to your guarantor to accept the agreement. They have seven days to respond.";
}
//set status percentage of that property
$pcode = get_user_meta($current_user->ID, 'vebra_pcode', true);
saveStatusProgress($pcode);
return "The guarantor details have been saved";
}
function generateGuarantorEmail($guarantor_details)
{
global $current_user;
global $wpdb;
$code = md5($guarantor_details->guarantor_name);
$wpdb->update($wpdb->prefix . 'vebra_tenants',
array('guarantor_hash' => $code,
'guarantor_sent' => date('Y-m-d h:m:s')),
array('tenant_user_id' => $current_user->ID,
));
$message = "Hello " . $guarantor_details->guarantor_name . "\n\n";
$message .= "Your name has been listed as a guarantor for a student let for " . $guarantor_details->tenant_firstname . " " . $guarantor_details->tenant_surname;
$message .= "\n\nIf you have agreed to being the guarantor, please click on the link below to go to a secure area of our website. There you will find a copy of the Assured Tenancy Agreement for the property, and the guarantor form. Please print off the guarantor form, sign and have it witnessed and then return it to us as soon as you can.";
$message .= "\n\n" . get_permalink(get_option('vebra_confirmPermalink')) . "?confirm=" . $guarantor_details->guarantor_hash;
$message .= "\n\n If you have not agreed to being a guarantor, would you please email us to let us know.";
$message .= "\n\n Thank you for your help.\n\n \n\n";
sendEmailToPublic($guarantor_details->guarantor_email, ' ', 'Guarantor Proposal', $message);
return "An email has been sent to the guarantor with a link for them to activate and accept to be a guarantor";
}
You might not getting database stored values inside $guarantor_details object.
so please check are you getting something in $guarantor_details->guarantor_name
if not then try to resolve it,
OR
If you just want to display submitted data then, you can simply print the post data in your case for guarantor_mobile its
<input name="guarantor_mobile" type="tel" required value="'. $_POST["guarantor_mobile"].'"/>
Thanks for the answers, but I solved this in a different way, had to load $guarantor_details = getGuarantorData(); just before building the form to make sure the data was displayed correctly.