I created a function to output a table row with data from a JS file. But I'd like to retrieve data from the MySQL database I made instead. Is it possible?
Function:
function outputCartRow(name, id, email, proj_title){
document.write('<tr>');
document.write('<td>'+name+'</td>');
document.write('<td>'+id+'</td>');
document.write('<td>'+email+'</td>');
document.write('<td>'+proj_title+'</td>');
document.write('</tr>');
}
I created a separate form that submits all the textfield input to the database, for reference:
PHP text:
<?php
$conn = mysqli_connect('127.0.0.1:3307', '', '');
if(!$conn){
echo 'Missing server';
}
if(!mysqli_select_db($conn,'fyp')){
echo 'Missing database';
}
$stud_name = $_POST['stud_name'];
$stud_id = $_POST['stud_id'];
$stud_email = $_POST['stud_email'];
$proj_title = $_POST['proj_title'];
$sql = "INSERT INTO student_assignment(stud_name, stud_id, stud_email, proj_title) values ('$stud_name', '$stud_id', '$stud_email', '$proj_title')";
if(!mysqli_query($conn, $sql)){
echo 'Update error';
}
else{
echo 'Update successful';
}
header("refresh:2; url=supervisor_pa.html");
?>
Is there a way to retrieve all the data and refer it to the function?
Related
I have a form where i save students login data to a database. The form includes the "admission_number", "username" and "password" fields. i want to show an error if the admission number is already existing and a user tries to add it again. Here's my php code for inserting the record.
<?php
if(isset($_POST['submit']))
{
$server = 'localhost';
$username = 'root';
$password = '';
$course_code=$_POST['course_code'];
$course_title=$_POST['course_title'];
$course_units=$_POST['course_units'];
$course_semester=$_POST['course_semester'];
$con=($GLOBALS["___mysqli_ston"] = mysqli_connect($server, $username, $password));
if(!$con)
{
exit('Error: could not establish connection to the server');
}
else
{
$con_db=((bool)mysqli_query($con, "USE esther"));
if(!$con_db)
{
exit('Error: Failed to connect to the database');
}
else
{
if(!empty($course_code) && !empty($course_title) && !empty($course_units) && !empty($course_semester))
{
$insert="INSERT INTO `course_table` VALUES('', '".$course_code."' ,'".$course_title."','".$course_units."','".$course_semester."')";
$query=mysqli_query($GLOBALS["___mysqli_ston"], $insert);
$dup_admission_number = mysql_query("SELECT admission_number FROM users_table WHERE admission_number = $admission_number");
}
if (#mysql_query($dup_admission_number)) {
echo 'Your admission number is already in our database.';
exit;
}
if($query)
{
echo 'course added successfully!';
header("location:add_course.php");
}
else { echo 'Error while adding Course.'; }
}
else
{
echo '*** fields cannot be blank ***.';
}
}
}
?>
To check admission number is unique or not you have to execute bellow query
$sql: "select id from student where admission_number = <> LIMIT 0,1";
if this query show result then you current form's admission number is not unique.
this process you can do using ajax request or you can check it before insert query being process.
or you can manage it in mysql by giving unique key constraint to admission number.
This is the Mysql Query
INSERT INTO sometable (data1, data2, data13)
SELECT 'username' FROM sometable
WHERE NOT EXISTS
(SELECT username FROM sometable WHERE login='someusername');
I'm sending my database a string to write into a database. I have 2 fields, one called num that's set to auto increment, and one called cards into which my string is written. So far I've been able to get my php to write the variable into the database, but now I would like it to return the num associated with it, so I can use it on my page. Can anyone help me how to write that, I'm new to php. I guess I need another sql query? (I want it to echo the num column of the row I've just written in, instead of "Records added successfully.").
php:
// Attempt MySQL server connection *
$link = mysqli_connect
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$cards = mysqli_real_escape_string($link, $_GET['cards']); //get data from javascript
$sql = "INSERT INTO drafts (cards) VALUES ('$cards')"; }
mysqli_query($link, $sql);
if(mysqli_query($link, $sql)){
echo mysqli_insert_id($link);
} else {
echo "failed!";
}
// Close connection
mysqli_close($link);
?>
js:
function writeDraft() {
$.ajax({
url: 'php/write.php',
type: 'get', //data type post/get
data: {
cards: output
},
complete: function (response) {
$('#draftNum').text(response.responseText);
},
error: function () {
console.log('Bummer: there was an error!');
}
});
return false;
}
writeDraft();
mysqli_insert_id() will do the job
if(mysqli_query($link, $sql)) {
echo "Records added successfully with id: ".mysqli_insert_id($link);
}
$sql = "SELECT * FROM drafts";
$result = mysqli_query($link, $sql);
$num = mysqli_num_rows($result);
$sql = "INSERT INTO drafts (cards) VALUES ('$cards')"; }
if(mysqli_query($link, $sql)){
echo $num+1, " Records added successfully.";
}
// Close connection
mysqli_close($link);
?>
Trying to create a simple cumulative addition script in PHP (or JS):
1) enter any integer(4 digits or less), click submit, number entered is displayed and saved on the same web page
2) enter another number, click submit, number entered is added to previous number and total is saved and displayed on the web page
Repeat …….
Example: the mantra counter at garchen.net
Below is the code I have so far
In Index.php:
<form method="post" action= "process-mantra-form-ami.php" >
<p><strong>Amitabha Million Mantra Accumulation: </strong><br></p>
<div style="margin-left: 20px;">
<p>OM AMI DEWA HRI</p>
<input type="text" name="accumulation" size="10" maxlength="6">
<input type="submit" value="Submit Your Mantra" name="B1"><br>
<span id="mani">Amitabha Mantra Count: <?php echo $newValue; ?> </span>
<p></p>
</div>
</form>
I am getting confused about the form processing php. Im attempting to use my local mamp server for the db. Do I create a connection, create a database, and a table, insert form data into table, and retrieve data back to index.php all at the same time in the process-mantra-form-ami.php file?
You guys made it seem easy in my last post, but there seems to be a lot to it. I know my code below is incomplete and not quite correct. Help!
PROCESS-MANTRA-FORM-AMI.PHP code below
<?php
// Create connection
$con=mysqli_connect("localhost:8888","root","root","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$accumulation = mysqli_real_escape_string($con, $_POST['accumulation']);
// Create database
$sql="CREATE DATABASE my_db";
if (mysqli_query($con,$sql)) {
echo "Database my_db created successfully";
} else {
echo "Error creating database: " . mysqli_error($con);
}
// Create table "Mantras" with one column 'Num'
$sql="CREATE TABLE Mantras (Num INT)";
if (mysqli_query($con,$sql)) {
echo "Table mantras created successfully";
} else {
echo "Error creating table: " . mysqli_error($con);
}
// Insert form data into table
$sql="INSERT INTO Mantras (Num INT)
VALUES ('$num')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
// update database
mysqli_query($con,"UPDATE Mantra SET Num = num + 1");
}
mysqli_close($con);
?>
<div>
<h2>Thank you for your <?php echo $num; ?> Amitabha Mantras!</h2>
<p>Remember to dedicate your merit.</p>
<p>Return to the main site</p>
</div>
try this out... (sorry, bored tonight)
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
$conn->query($sql)
$conn->prepare($sql)
$conn->error
http://php.net/manual/en/class.mysqli-stmt.php
$stmt->bind_param('ss',$val1,$val2)
$stmt->bind_result($res1,$res2)
http://php.net/manual/en/mysqli.construct.php
<?php
$host = 'localhost'; // localhost:8888
$user = 'root';
$pass = ''; // root
$dbnm = 'test';
$conn = mysqli_connect($host,$user,$pass,$dbnm)
or die('Error ' . $conn->connect_error);
// for testing.... so i can run the code over and over again and not
// get errors about things existing and stuff
run_statement($conn,"drop database if exists `my_db`;",'cleared old db');
run_statement($conn,"drop table if exists `mantras`;",'cleared old table');
run_statement($conn,"drop table if exists `two_col_table`;",'cleared old table');
// Create database
$sql = 'create database my_db';
$err = run_statement($conn,$sql,'Database creation');
if (!$err) $conn->select_db('my_db');
// Create table "Mantras" with one column 'Num'
$sql = 'create table mantras (num int)';
$err = run_statement($conn,$sql,'Table mantras');
if (!$err) {
$sql = 'insert into mantras (num) values ( ? )';
$stmt = $conn->prepare($sql);
$stmt->bind_param('d',$num); // d is for digit but s (string) would work too
$num = 1;
$stmt->execute();
$num = 2;
$stmt->execute();
$stmt->close();
echo ($conn->error) ? "insert errored: {$conn->error}" : 'insert ran succesfully';
// update database
$sql = 'update mantras set num = num + 1';
run_statement($conn,$sql,'Update database');
}
// Create table "test" with two columns
$sql = 'create table two_col_tbl (num int, txt varchar(10))';
$err = run_statement($conn,$sql,'Table two_col_tbl');
if (!$err) {
// demonstrating how to bind multiple values
$sql = 'insert into two_col_tbl values ( ?, ? )';
$stmt = $conn->prepare($sql);
$stmt->bind_param('ds',$num,$txt);
$num = 1; $txt = 'hello';
$stmt->execute();
$num = 2; $txt = 'world';
$stmt->execute();
$stmt->close();
// select statement
$sql = 'select num, txt from two_col_tbl';
$stmt = $conn->prepare($sql);
$stmt->bind_result($db_num, $db_txt);
$stmt->execute();
print '<table><tr><th colspan=2>two_col_tbl</tr><tr><th>num</th><th>txt</th></tr>';
while ($stmt->fetch()) {
print "<tr><td>$db_num</td><td>$db_txt</td></tr>";
}
print '<table>';
$stmt->close();
}
$conn->close();
function run_statement($conn,$statement,$descr) {
if ($conn->query($statement))
echo "$descr ran successfully";
else echo "$descr failed: {$conn->error}";
return $conn->error;
}
?>
<div>
<h2>Thank you for your <?php echo $num; ?> Amitabha Mantras!</h2>
<p>Remember to dedicate your merit.</p>
<p>Return to the main site</p>
</div>
i have code for save 3 textbox in one field in databse
no problem when i am enter 3 textbox , but when i fill 1 textbox and press ok
save another textbox in database as blank
i want just take the textbox is fulled and ignore the textbox empty
this is my code
<?php
include("connect.php");
$expert_name = trim($_POST['expert_name']);
$expert_name2 = trim($_POST['expert_name2']);
$expert_name3 = trim($_POST['expert_name3']);
// this is for arabic language.
mysql_query("SET NAMES utf8");
// Insert data into mysql
$sql="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name')";
$sql2="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name2')";
$sql3="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name3')";
$result=mysql_query($sql);
$result2=mysql_query($sql2);
$result3=mysql_query($sql3);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
}
else {
echo "ERROR";
echo "<br>";
// this for print error in insert process
echo mysql_error();
echo "<a href='expert_add.php'><br>Please try again </a>";
}
//mysql_close($con);
?>
back to form add
Execute your sql query only the variable value not equal to empty.
try this,
$expert_name = trim($_POST['expert_name']);
$expert_name2 = trim($_POST['expert_name2']);
$expert_name3 = trim($_POST['expert_name3']);
// this is for arabic language.
mysql_query("SET NAMES utf8");
// Insert data into mysql
if ($expert_name != "") {
$sql = "INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name')";
$result = mysql_query($sql);
}
if ($expert_name2 != "") {
$sql2 = "INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name2')";
$result2 = mysql_query($sql2);
}
if ($expert_name != "") {
$sql3 = "INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name3')";
$result3 = mysql_query($sql3);
}
// if successfully insert data into database, displays message "Successful".
if ($result || $result2 || $result3) {
echo "Successful";
echo "<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
} else {
echo "ERROR";
echo "<br>";
// this for print error in insert process
echo mysql_error();
echo "<a href='expert_add.php'><br>Please try again </a>";
}
//mysql_close($con);
?>
back to form add
You should also check $result2 and $result3. I added that in this answer
try this
if ( !empty($_POST['expert_name']) ){
$sql="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name')";
$result=mysql_query($sql);
}
if ( !empty($_POST['expert_name2']) ){
$sql2="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name2')";
$result2=mysql_query($sql2);
}
if ( !empty($_POST['expert_name3']) ){
$sql3 ="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name3')";
$result3 =mysql_query($sql3 );
}
Then you might want to check if the variable is empty().
<?php
include("connect.php");
$expert_name = trim($_POST['expert_name']);
$expert_name2 = trim($_POST['expert_name2']);
$expert_name3 = trim($_POST['expert_name3']);
// this is for arabic language.
mysql_query("SET NAMES utf8");
// Insert data into mysql
if(!empty($expert_name)) {
$sql="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name')";
$result=mysql_query($sql);
}
if(!empty($expert_name2)) {
$sql2="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name2')";
$result2=mysql_query($sql2);
}
if(!empty($expert_name3)) {
$sql3="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name3')";
$result3=mysql_query($sql3);
}
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
}
else {
echo "ERROR";
echo "<br>";
// this for print error in insert process
echo mysql_error();
echo "<a href='expert_add.php'><br>Please try again </a>";
}
Also note: You only check if $result is okay. If you only fill textbox 2 and leave 1 empty, the value of 2 it will get inserted but an error is shown.
I'd say your code need general review, but as it is for now you will have to do something like this each query:
if (!empty($expert_name2){
$result2=mysql_query($sql2)
}
But you should try to loop your queries in foreach rather than manually write every on query. And by the way:
if($result){
echo "Successful";
echo "<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
}
This code only return succes when 1st wuery success because you use $result which is set in 1st query only
The ID is probably NOT NULL AUTO_INCREMENT, so that won't accept NULL as value.
try sending blank value, such as:
$sql="INSERT INTO experts(id,expert_name) VALUES ('', '$expert_name')";
Also, build bulk insert, rather than multiple.
I will explain why, when you insert single insert into the database, the values being inserted, then, the DB engine flushes indexes (they written to disk), unless you have set delay_key_write=ALL in you my.cnf. Index flushing directly affects your db performance.
Please, check the reworked code out. The code adjusted for bulk insert, sql string escaping for security purposes and additional verification for post keys existence.
<?php
include("connect.php");
// this is for arabic language.
mysql_query("SET NAMES utf8");
$values = array();
$skipInsert = true;
$fields = array('expert_name', 'expert_name2', 'expert_name3');
$insert = "INSERT INTO experts(id,expert_name) VALUES ";
// Loop through predefined fields, and prepare values.
foreach($fields AS $field) {
if(isset($_POST[$field]) && !empty($_POST[$field])) {
$values[] = "('', '".mysql_real_escape_string(trim($_POST[$field]))."')";
}
}
if(0 < sizeof($values)) {
$skipInsert = false;
$values = implode(',', $values);
$insert .= $values;
}
if(false === $skipInsert) {
mysql_query($insert);
}
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful","<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
} else {
echo "ERROR","<br>",mysql_error(),"<a href='expert_add.php'><br>Please try again </a>";
}
HTH,
VR
if(!empty($textbox1_value)) {
//DO SQL
}
You can repeat this for multiple boxes however you wish, the empty operator checks if its empty, so if its not empty the "//DO SQL" area will get run.
I have a very simple script that pulls data from a mysql db, However when I run it there is no output, I am setting the get request to the correct value related to the row and when i run the SQL query in PHPmyadmin it runs as expected.
my code;
session_start();
require_once 'includes/sessions.inc.php';
require_once 'includes/config.inc.php';
if(!isLoggedIn())
{
echo "not logged in";
}
else
{
//Connect to DB
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($dbname);
$id = $_SESSION['userid'];
$contactid = $_GET['contactid'];
//Get Data from DB
$query = "SELECT id, First_name, Last_name, email_addres, phone_number, photo, owner FROM tbl_contcats where id = '$contactid';";
$result = mysql_query($query) or die(mysql_error());
echo '<img src="./contacts/'.$result['photo'].'"/><br>';
echo 'First name:'.$result['First_name'].'<br>';
echo 'Second name:'.$result['First_name'].'<br>';
echo 'Email Address:'.$result['First_name'].'<br>';
echo 'phone_number'.$result['First_name'].'<br>';
}
?>
ps; any feed back on how I can improve my code/clean it up is apericated
If you want to access the variables the way you're doing it, you'll first need to fetch an associative array of your results:
$rows = mysql_fetch_assoc($result);
Then you'll access the entries via
while ($row = mysql_fetch_assoc($result)) {
echo '<img src="./contacts/'.$row['photo'].'"/><br />';
echo 'First name:'.$row['First_name'].'<br />';
echo 'Second name:'.$row['First_name'].'<br />';
echo 'Email Address:'.$row['First_name'].'<br />';
echo 'phone_number'.$row['First_name'].'<br />';
}
What you're doing right now is trying to access variables from a MySQL resource that is returned by the query. The mysql_query itself doesn't return a raw result set. ;)