I am currently making a Register Page, I coded the layout with html, and I get value from the html input(<input)
and insert into database. It did sucessfully inputed into the database but when I "select * from dbo.user" the value are showing blank
<?php
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
mysql_free_result($result);
?>
SOURCE: http://au2.php.net/manual/en/function.mysql-fetch-assoc.php
Related
I am new to .NET, Hope to get some suggestions on my below scenario:
Scenario: I have an external Excel file, which should be read and loaded into the database using C#.
So, For that I have created two tables:
Staging table (A temporary table which reads the data from excel file before loading into the Final Table).
Final Table (Contains the verified data).
At the staging table, I need to write a program to validate the datatypes and prompt the user by displaying the error message.(Eg: where an excel column contains only the numeric values and if any cell contains the text/string in that particular column , C# Program should result in displaying the message( “ Text not allowed , please enter numeric value”).
In order to achieve the above, I want to write a stored procedure which stores the error messages in temporary table and C# program execute the stored procedure to read the error messages from temporary table.
I tried the above procedure by giving the non-numeric/text (“ABC”) value into the numeric column. But I did not receive an error message as it is taking as null rather than displaying error message
OLEDB Connection String :
string STR_OLEDBCONNECTION = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + PATH + "';Extended Properties='Excel 12.0 Xml;HDR=Yes';IMEX = 1";
Below is the SQL Stored Procedure to read the error messages into temporary table.
USE [EXCEL_DATABASE]
GO
CREATE PROCEDURE [dbo].[spexcel]
AS
BEGIN
--SET NOCOUNT ON added to prevent extra result sets from
--interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #count int
IF OBJECT_ID('tempdb..#TempResult') IS NOT NULL DROP TABLE #TempResult
CREATE TABLE #TempResult
(
[Messages] nvarchar(max) NULL
)
--Incremental Table 1
INSERT INTO #TempResult
SELECT '[Incremental File 1] Column [Units] at Row: ' + CONVERT(nvarchar(255),(SCOPE_IDENTITY() + 1)) + ' is not in correct date format' FROM [dbo].[Staging_OEM]
WHERE [Units] IS NOT NULL AND TRY_CONVERT(float, [Units]) IS NULL
SELECT #count = COUNT(*) FROM #TempResult
IF #count = 0
BEGIN
INSERT INTO [dbo].[Final_OEM] ([Source], [Geography], [Product Type], [Period], [Period Format],[Year], [Device Type], [Segment Type], [Platform], [Units],[Other Software Units],[Revenue],[Budget Units],[Budget Revenue],[Hardware Units],[Brand],[Price Band],[Segment],[Prod Rollup])
SELECT [Source], [Geography], [Product Type], [Period], [Period Format],[Year], [Device Type], [Segment Type], [Platform],CONVERT(float, [Units]),[Other Software Units],CONVERT(float,[Revenue]),CONVERT(float,[Budget Units]),CONVERT(float,[Budget Revenue]),[Hardware Units],[Brand],[Price Band],[Segment],[Prod Rollup] FROM [dbo].[Staging_OEM]
END
SELECT * FROM #TempResult
END
C# Program to read Temporary table messages:
static bool checkNumeric(SqlConnection SQLConnection,string fileLabel)
{
bool result = true;
var errMsg = "";
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "[EXCEL_DATABASE].[dbo].[spExcel]";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = SQLConnection;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
errMsg += reader[0].ToString() + Environment.NewLine;
}
cmd.Dispose();
reader.Close();
}
if (errMsg != "")
{
Common.writeToError("[" + DateTime.Now.ToString() + "] Error encountered while reading " + fileLabel + Environment.NewLine + errMsg);
result = false;
}
else
{
Common.writeToLog("[" + DateTime.Now.ToString() + "] Reading " + fileLabel + " is successful.");
}
return result;
}
}
}
how to check for duplicate entry on a form using php?my front end is c#windows application
I am adding a new user to database using c# and php file.
I have created the following:
my project in c# (form1):
c# coding:
private void btncreate_Click(object sender, EventArgs e)
{
var request = (HttpWebRequest)WebRequest.Create("http://***.**.***.***/response.php");
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
using (var stream = request.GetRequestStream())
{
var buffer = Encoding.UTF8.GetBytes("userid= " + txtUserid.Text + " & password=" + txtConformpassword.Text + " & first_name=" + txtFirstname.Text + " & last_name=" + txtLastName.Text + "& role= " + cmbRole.Text + "& active=" + cmbActive.Text + "");
stream.Write(buffer, 0, buffer.Length);
}
var response = (HttpWebResponse)request.GetResponse();
string result = String.Empty;
using (var reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
txtMessage.Text = result;
}
my PHP file :response.php
<?php
$uid = $_POST['userid'];
$pass = $_POST['password'];
$fname = $_POST['first_name'];
$lname = $_POST['last_name'];
$rol = $_POST['role'];
$act = $_POST['active'];
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql= "INSERT INTO aster(userid,password,first_name,last_name,role,active)
VALUES('$uid', '$pass', '$fname','$lname','$rol','$act');";
if ($conn->query($sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
it add data successfully but when i enter the same userid in textbox and click create button i need to get an error message in txtmessage as userid already exists.
i search through googling but i did not got any thing about duplicate entry please refer me some coding
You could extend your response.php to do a select statement before the insert. If you are able to select a record with the given ID, then yield a response (essentially an error code) which your C# application will then interpret and display to the user.
As a side note, since the ID field appears to be numeric, you can simply omit it from your form and let the DB increment it automatically. This would also mean that the user will not have to guess which ID values are available.
you just want that the ID which you have entered should not be inserted at the next time . for that you just need to do one thing. make your id as a primary key in your database table creation , after doing this you will be not able to insert that id again or duplicate entries are not allowed in a primary key.
lemme know if it is useful.
It may not help as much, but I think my explanation will point you to the right direction.
What I would do is:
I would use SQL query to check if record exist and if exist then print "Record Exists" Else "Record does not exist". Below the code I post, 'Justin Yen' on PHP posting a quote, make sure you assign that to the field of inputting the username. In your case it's $uid.
On PHP, assign the result of sql query to a variable.
Create a string variable "Record Exists" and "Record does not exist".
compare the string variable you create on step 3 to the result on step 2.
I don't know any PHP coding, but you can try to find a way to compare string. But here's an example of checking record exist in SQL:
Declare #Username varchar(MAX) = 'Justin Yen'
IF EXISTS(select Username from EmployeTable where Username = #Username)
begin print 'Record Exists' end
else
begin print 'Record does not exist' end
Now all you have to do is if variable match then prompt "Cannot create record because Record created." Else use the add record codes you have in php.
You can simply try to add the contraints(UNIQUE/PRIMARY) to the column 'userid'.
ALTER TABLE aster ADD CONSTRAINT MyUniqueKey UNIQUE KEY(userid)
I have a PHP file and a C# app.
In the php file it returns a Array of the rows that i selected from a mysql table.
I want to read that Array and deserialize it so the result of a row can be parsed inside a textBlock.
My PHP script:
<?php
mysql_connect("-----", "------", "-----") or
die("Could not connect: " . mysql_error());
mysql_select_db("------");
$list = array();
$query = "SELECT SongName,ArtistName,Thumbnail,MediaLink FROM Library";
$resource = mysql_query($query);
while($row = mysql_fetch_assoc($resource))
{
$list['SongName' . (1 + count($list))] = $row['SongName'];
}
$list = array('row' => count($list)) + $list;
echo json_encode(array($list));
?>
How do i get the ArtistName, Thumbnail and medialink inside the array?
How do i read this in C# so my textblock will show: ArtistName.
Technologies:
Windows 10 Store apps(C#, XAML)
If somebody could help that'd be great,
Christos K
Simple, you pull all the required data from the database and return it as an array, just put the whole $row into the array you are about to return
<?php
mysql_connect("-----", "------", "-----") or
die("Could not connect: " . mysql_error());
mysql_select_db("------");
$list = array();
$query = "SELECT SongName,ArtistName,Thumbnail,MediaLink FROM Library";
$resource = mysql_query($query);
while($row = mysql_fetch_assoc($resource))
{
$list[] = $row;
}
echo json_encode($list);
?>
Now you should receive all the data you want in the javascript. Just use the javascript debugger to see what it looks like
I have this query:
SELECT COUNT(date) FROM patients WHERE date= 2012/02/23
If that COUNT returns 10, there will be an alert that tells to the user that it cannot accept more visit.
How do i validate that? How can i know that?
In php i just have to do this:
<?php
$QUERY = "SELECT COUNT(date) AS count_results FROM patients WHERE date= 2012/02/23";
$execute_query = $CONEXION ->prepare($query);
$execute_query->execute();
$results = execute_query->fetch(PDO::FETCH_ASSOC);
if(results['count_results ']==10)
{
echo "Cannot accept know visit.";
}else{
echo "Ok";
}
?>
But i have no idea of how to do that in ASP.NET C#.
Help??
Perform a check in the page_load event, if you are validating the logged in user. Or if you need to validate depending on a user value that you are attempting to insert, use the button_click event for record being inserted.
SqlCommand cmdEvent = new SqlCommand("SELECT COUNT(date) FROM patients WHERE date= '2012/02/23'", yourSqlConnection);
object myCount;
if (yourSqlConnection.State == ConnectionState.Closed){ yourSqlConnection.Open(); }
myCount = cmdEvent.ExecuteScalar();
if (yourSqlConnection.State == ConnectionState.Open){ yourSqlConnection.Close(); }
if (myCount != null)
{
if ((int)myCount >= 10)
{
// Logic here e.g myLabel.Text = "You have reached your maximum of 10 visits!";
return;
}
}
I am trying to delete entries by ID. I want to notify user that ID they try to delete doesn't exist. It doesn't create any problems, but I want to make everything clear.
How to do that? Do I have to use SQL string to do so?
I am using MS Access 2007 and this is how I delete item:
string SQL = "DELETE FROM PersonalData WHERE DataID = " + txtEntryID.Text;
private void DeleteData(string SQL)
{
// Creating an object allowing me connecting to the database.
// Using parameters in command will avoid attempts of SQL injection.
OleDbConnection objOleDbConnection = new OleDbConnection();
// Creating command object.
objOleDbConnection.ConnectionString =
"Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + filePath + ";" +
"Persist Security Info=False;" +
"Jet OLEDB:Database Password=" + pass + ";";
OleDbCommand objOleDbCommand = new OleDbCommand();
objOleDbCommand.CommandText = SQL;
// Assigning a connection string to the command.
objOleDbCommand.Connection = objOleDbConnection;
try
{
// Open database connection.
objOleDbConnection.Open();
objOleDbCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
// Displaying any errors that
// might have occured.
MessageBox.Show("Error: " + ex.Message);
}
finally
{
// Close the database connection.
objOleDbConnection.Close();
}
// Refreshing state of main window.
mainWindow.DisplayFileContent(filePath);
MessageBox.Show("Data was successfully deleted.");
// Clearing text box field.
txtEntryID.Clear();
}
In VBA code, you could use the DCount() function.
You can also just delete the records with a SQL statement and inform the user after the fact; from the user's point of view there's no difference:
Dim id As Long
id = GetAnIdFromTheUser()
With CurrentDb
Do
.Execute "DELETE FROM [TableName] WHERE ID = " & id
If .RecordsAffected > 0 Then
Goto Done
End If
MsgBox "That ID doesn't exist; please try another."
id = GetAnIdFromTheUser()
Loop
Done:
.Close
End With
EDIT:
In ADO.NET you can follow the same approach by examining the return value of ExecuteNonQuery. For example, you could declare your function as bool TryDeleteData(string SQL) and do something like
...
if (objOleDbCommand.ExecuteNonQuery() == 0)
return false;
...
You could use the DCount function of VBA:
DCount("*", "SomeTable", "ID = 1")
If this is 0 then you know the record doesn't exist and can inform the user.
Your question isn't clear enough, so I'm guessing that what you'd like to do is execute the DELETE query and then return whether records were deleted or not. If that's what you want to do you could do it like this:
DECLARE #deletedID AS INT
SELECT #deletedID = id FROM your_table WHERE id = <the id supplied by user>
DELETE FROM your_table
WHERE your_table.id = <the id supplied by user>
RETURN #deletedID
If the requested ID does not exist this will return NULL
EDIT
Based on the clarification in your comments, the following query should work just fine:
SELECT COUNT(DataId) as Cnt
FROM PersonalData WHERE DataId = <user_specified_id>
This query will produce a single column, single row result set (i.e. a scalar-value). The value is going to be either 1 or 0 (assuming only one entry may have the same id). If the count is 0 the entry does not exist.
P.S.
The way you are executing the query you're opening yourself to SQL injection attacks. Basically, someone could give you the following DataID: 0 OR 1 = 1 and guess what's going to happen - all the PersonalData records will be deleted!
A much better approach would be to use prepared statements. Or at the very least, make absolute sure that you sanitize and validate the user input before concatenating it into the query text.