http://jsfiddle.net/Fd9wx/
I made this to help solve my problem
so I have some php code and html code that should send sql Query's to the database upon the html table I have created like to set up new databases but then I fill out my form and click run it does not want to work for me. I did some google research and got nothing back now before you say "use PDO and This is no longer supported" PDO is hard for me to use because I dont understand some of it I will use it later on but not now, also I did make this script here from hand so dont say "contact script dev" if some one could point me in right direction to solving my problem or just way to make my sql errors show in my script? like the line what to remove and all
here is main part of my script
$tablename=$_POST['tablename'];
$value=$_POST['value'];
$type=$_POST['type'];
$length=$_POST['length'];
$collation=$_POST['collation'];
$attributes=$_POST['attributes'];
$null=$_POST['null'];
$extra=$_POST['extra'];
// Insert data into mysql
$sql="CREATE TABLE `a7972613_db`.`$tablename` (
`field1` $type( $length ) $null $extra
) ENGINE = MYISAM";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
}
else {
echo "Please Go Back And Check Your Errors!";
}
thats my main part
The problem with your code is you have not selected the database.
$host = "xxxxx";
$database = "xxxxx";
$user = "xxxx";
$password = "xxxxx";
// Connect to server and select database.
mysql_connect("$host", "$user", "$password")or die("cannot connect");
Use below code for selecting database
// Connect to server and select database.
$conn = mysql_connect("$host", "$user", "$password")or die("cannot connect");
mysql_select_db($database,$conn);
and another problem is when your query fails, you have hardcoded the error,but use below code for checking where is the problem in your query
$result=mysql_query($sql) or die(mysql_error());
Change your query to
$result = mysql_query($sql) or die("Error with $sql: " . mysql_error());
with mysql_error(), you will see what your problem is.
You can dump your $sql string in order to see, whether it is correct
echo $sql;
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm developing a banning sytem for my web site and all the values are correct and I get no errors on the page, but the data does not go into the table. Here's the code for database connectivity.
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="PyroStudio"; // Database name
$tbl_name="banned"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
Here is the actual banning system itself
if ($_POST['post'])
{
//get data
$bannuser = $_POST['bannuser'];
$TypeBan = $_POST['TypeBan'];
$Reviewed = $_POST['Reviewed'];
$ModNote = $_POST['ModNote'];
$Reason = $_POST['Reason'];
$OffenItem = $_POST['OffenItem'];
$BanLengthMssg = $_POST['BanLengthMssg'];
$ReleaseMssg = $_POST['ReleaseMssg'];
$AppealMssg = $_POST['AppealMssg'];
//Connect To The Database
$connect = mysql_connect("localhost","root","");
mysql_select_db("PyroStudio");
$namecheck = mysql_query("SELECT bannuser FROM $tbl_name WHERE bannuser='$bannuser'");
$count = mysql_num_rows($namecheck);
if($count!=0)
{
die("This User Is Already Banned! <a href='home.php'>[Home]</a>");
}
//check for existance
if ($bannuser)
{
if(strlen($bannuser)>25||strlen($bannuser)<6)
{
echo "<b>Length Of Username Is Must Be Between 6 and 25 Characters Long!</b>";
}
else
{
$queryreg = mysql_query("
INSERT INTO $tbl_name VALUES ('$bannuser','$TypeBan','$Reviewed','$ModNote','$Reason','$OffenItem','$BanLengthMssg','$ReleaseMssg','$AppealMssg')
");
die ("<b>The Moderation Report Has Been Submitted! The User Is Now Banned!</b> <b><a href='home.php'>[Home]</a></b>");
}
}
}
?>
I've used this system before and now I dont know why it doesn't want to work. If you can help, that would be great.
mysql_query("SELECT bannuser FROM $tbl_name WHERE bannuser='$bannuser'");
Just don't. This is a giant gaping security hole. Also, your code may be failing because of unescaped $_POST data getting into SQL statement and breaking it. Or because you had missed something with INSERT query, since you hadn't even specified a column list. If you're interested in what is the issue, check MySQL server logs for those or the result of mysql_error() function.
Anyway, consider the following approach:
$db = new PDO("mysql:host=localhost;dbname=PyroStudio", "root", "");
$bannuser = $_POST["bannuser"];
if (strlen($bannuser) > 25 || strlen($bannuser) < 6) {
die("Invalid username.");
}
$count = $db->prepare("SELECT COUNT(*) FROM bannuser WHERE bannuser = ?")
->execute(array($bannuser))
->fetchColumn();
if ($count > 0) {
die("Already banned.");
}
$stmt = $db->prepare("INSERT INTO bannuser (bannuser, typeban, …) VALUES (:bannuser, :typeban, …)");
$stmt->bindParam("bannuser", $bannuser);
$stmt->bindParam("typeban", $_POST["typeban"]);
…
$stmt->execute();
This is not a complete code (in particular, I'm too lazy to type every inserted parameter out there) but just a rough sketch I've did from memory to get you started.
<?php
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="hsp_property"; // Database name
$tbl_name="project_directory"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
//Get values from form
$id = $_POST['id'];
$hospital = $_POST['hospital'];
$project = $_POST['project'];
$state = $_POST['state'];
$status = $_POST['status'];
$da_status = $_POST['da_status'];
$pm = $_POST['pm'];
$budgett = $_POST['budgett'];
$budgetat = $_POST['budgetat'];
$pdapproval = $_POST['pdapproval'];
$pdcs = $_POST['pdcs'];
$pdcd = $_POST['pdcd'];
$pdcf = $_POST['pdcf'];
$pnm = $_POST['pnm'];
$prm = $_POST['prm'];
$comments = $_POST['comments'];
// update data in mysql database
$sql="UPDATE $tbl_name SET Hospital='$hospital', Project='$project', State='$state',Project_Status='$status',DA_Status='$da_status',Project_Manager='$pm',Budget_Total='$budgett',Budget_Approved='$budgetat',Project_Approval_Dates='$pdapproval',Project_Contstruction_Dates='$pdcs',Project_Contract_Dates='$pdcd',Project_Current_Dates='$pdcf',Program_Next_Milestone='$pnm',Program_Milestone='$prm',Comments='$comments' WHERE id='$id'";
$result=mysql_query($sql);
// if successfully updated.
if ($result) {
header ('Location: ../project_directory.php');
}
else {
echo 'Error';
}
?>
The above is some code to update a MySQL db, i'm running WAMP to test the website before I'll upload.
I've been using the phpeasysteps tutorial as php and mysql is new to me. It's been working all ok until now.
Would love to know what i'm doing wrong, the PhpEasySteps tutorial might be a tad old as i've had to update a few elements of the initial code to get it to work..
Replace echo 'Error'; with echo mysql_error(); to see why you didn't get a result and then slap yourself for misspelling a column name or something most likely easily overlooked. If you still can't figure it out, post the error. And if you go that far, post the result of SHOW CREATE TABLE project_directory
You need to add $link_identifier to your mysql_select_db database selection,
Syntax: bool mysql_select_db ( string $database_name [, resource $link_identifier = NULL ] )
$link = mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name", $link)or die("cannot select DB");
You can use mysql_error(); function to find the mysql related errors.
I have a PHP form that should insert data into my SQL database on hostgator. However it is not adding any data but the id field keeps incrementing. I do not receive any error message when submitting the form and when i go to the database the other fields are just empty thus not displaying any data.
I am pulling my hair and cant figure out what the problem is. Can someone please help me
Thanks
<?php
$host="localhost"; // Host name
$username="xxxxxx"; // Mysql username
$password="xxxxxx"; // Mysql password
$db_name="rob1124_inventory"; // Database name
$tbl_name="data"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get values from form
$qty=$_POST['qty'];
$product=$_POST['product'];
$price=$_POST['price'];
$totalprice=$_POST['totalprice'];
$seller=$_POST['seller'];
$city=$_POST['city'];
// Insert data into mysql
$sql="INSERT INTO $tbl_name(qty, product, price, totalprice, seller,city)
VALUES('$qty', '$product', '$price', '$totalprice', '$seller', '$city')";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='insert.php'>Back to main page</a>";
}
else {
echo "ERROR";
}
?>
<?php
// close connection
mysql_close();
?>
Change to utf-8 from all varchar fields of your table and
try to get mysql_error().
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
mysql_query("set names 'utf8'");
//You codes....
// Insert data into mysql
$sql="INSERT INTO $tbl_name(qty, product, price, totalprice, seller,city)
VALUES('$qty', '$product', '$price', '$totalprice', '$seller', '$city')";
$result=mysql_query($sql) or die(mysql_error());
//Your codes...
Since the id is incrementing atleast the form and the DB connect, it tries to enter data.
One usually occurring error is that the data types in the databases columns don't match with the type of data recieved. Like trying to insert chars into ints etc. Or the length of the data is to large for the assigned size in the database. Check to see that the types are correct and try again.
But still, those that are correct should be inserted. Hard to tell without knowing more about the database design.
i know this is a beginner's question .I am working on a bloodbank database project with html,php and mysql. Here as an administrator,i am trying to send messages to users.At first i am trying to see if the user with the username is present in the database.if he is present i am inserting the username and messages into the table called usermessages But i am not able to insert the data.i am getting the message "message sent successfully",but in reality it is not getting updated in the database.So here is my code,i can assure all that no spelling mistake is present in database or in phpcode.
<?php
session_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="bloodbank"; // Database name
$tbl_name="users"; // Table name
$tblname="usermessages";
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and messages is sent from form
$username=$_POST['username'];
$sql="SELECT * FROM $tbl_name WHERE username='$username'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
if($count==1)
{
$mysql="INSERT INTO tblname(username, messages)
VALUES
('$_POST[username]','$_POST[messages]')";
echo "Message Sent Successfully";
}
else
{
echo "No user with that username found in the database";
}
?>
Try to execute the query
$mysql="INSERT INTO $tblname(username, messages)
VALUES ('$_POST[username]','$_POST[messages]')";
$return = mysql_query($my_sql);
echo "Message Sent Successfully";
You just forgotted to execute this insert query
And my advice is dont use mysql_* functions as they are depricated,use either mysqli_* functions or PDO Statements,and while you are playing with the post variables try to escape them like
mysql_real_escape_string($_POST['messages']);
Your query is good but you haven't executed it. Use mysql_query to execute your query.
Second please be careful about sql injection. Your code is shouting that come and hack me.
I am trying to see if there is a match from a form to my database. here is my php code:
<?php
$host="localhost"; // Host name
$username="****"; // Mysql username
$password="*****"; // Mysql password
$db_name="*****"; // Database name
$tbl_name="public"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$door=$_POST['door'];
$postcode=$_POST['postcode'];
// To protect MySQL injection (more detail about MySQL injection)
$door = stripslashes($door);
$postcode = stripslashes($postcode);
$door = mysql_real_escape_string($door);
$postcode = mysql_real_escape_string($postcode);
$sql="SELECT * FROM $tbl_name WHERE door ='$door' AND postcode='$postcode' AND active = 'not_activated' AND ref = '". $_SESSION['ref']."'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1){
header("location:securityquestion.php");
}
?>
the error message i am getting is as follows:
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in /home/jahedhus/public_html/system/checkdetails.php on line 36
line 36 is $count=mysql_num_rows($result);
what am i doing wrong here?
Because, just like many, many others here, the code blindly assumes that the query succeeded and everything is fine. Check for errors after each operation. Most of the functions return false when they fail.
Because your query failed.
php.net/mysql-query: "For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error."
Try this:
$result=mysql_query($sql) or die(mysql_error());
You need to do two things:
Find out what the MySQL error is, as already suggested
$result=mysql_query($sql) or die(mysql_error());
You need to sanitize everything that goes into the query. Although you sanitize $door and $postcode, you don't sanitize $_SESSION['ref']. You should and run it through mysql_real_escape_string(). I don't know what you are storing in it, but perhaps that's where the code is breaking because of unescaped characters?
In theory I guess $_SESSION is stored server side, but personally I still wouldn't trust it, and I'd escape everything that goes into a MySQL query.
I think answer lies in the curly braces:
$sql="SELECT * FROM $tbl_name WHERE door ='{$door}' AND postcode='{$postcode}' AND active = 'not_activated' AND ref = '". $_SESSION['ref']."'";
$result=mysql_query($sql);