I'm trying to add new filed in my datbase!
but i'm getting error in the mysql_query part!
he is the code
<?php
$link = mysql_connect('localhost','user','pass','data');
if(!$link)
die('Could not connect: ' . mysql_error());
$sql = "INSERT INTO content(`id`, `writer`, `title`, `subject`) VALUES(NULL,'11','22','33')";
if (!mysql_query($link,$sql))
{
die('Invalid query: ' . mysql_error());
}
echo "1 record added";
mysql_close($link);
?>
When i run this page i get
Invalid query:
and An Empty reason
any ideas?
You have your parameters to mysql_query backwards.
It should be mysql_query($sql, $link).
P.S. You don't even need to pass $link. You can just do mysql_query($sql). PHP will use the last link opened via mysql_connect.
Whats your table definiton? I think "id" is your primary key (PK). A PK must not be NULL.
If it's auto_increment just leave the coloum away and write
"INSERT INTO content(`writer`, `title`, `subject`) VALUES('11','22','33')";
Related
I have a small script that will insert two tables in a database, which works fine unless the user has changed the default prefix. I am wondering how I can call and use the "prefix" from the config file. Here is my code.
<?php
include("../../Config/config.php");
$link = mysql_connect($CONFIG['host'], $CONFIG['login'], $CONFIG['password'];
$db = ($CONFIG['database']);
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("$db", $link);
$sql = 'INSERT INTO settings '.
'(id, field, value) '.
'VALUES ("NULL", "show_thumbs_down", "1")';
$exec = mysql_query($sql, $link);
if (!$exec) die(mysql_error());
mysql_close($link);
?>
You can see that I call "config.php" to get the database info. That would also work to get the prefix but I'm not sure how to implement the "prefix" with the rest of the code.
FYI: I'm a newbie :)
Thanks.
I got it, here's what worked.
<?php
require_once ("../../Config/config.php");
$link = mysql_connect($CONFIG['host'], $CONFIG['login'],$CONFIG['password']);
$table_prefix = ($CONFIG['prefix']);
$db = ($CONFIG['database']);
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("$db", $link);
$sql = 'INSERT INTO ' . $table_prefix . 'settings'.
'(id, field, value) '.
'VALUES ("NULL", "show_thumbs_down", "1")';
$exec = mysql_query($sql, $link);
if (!$exec) die(mysql_error());
mysql_close($link);
?>
Thanks for the help BK435
Welcome!
I am assuming you can get the prefix and store it in variable. When calling your sql add this to your code ' . $TABLE_PREFIX . '. so your above insert would look something like:
$sql = 'INSERT INTO ' . $TABLE_PREFIX . 'settings '.
'(id, field, value) '.
'VALUES ("NULL", "show_thumbs_down", "1")';
How do i do this. Here is my code`
$insert = "REPLACE INTO drinks SET
name='".$name2."', category=' ".$category2." ', date=CURDATE()";
if (#mysql_query($insert)) {
echo '<h4 class="alert_info">Drinks added</h4>';
} else {
echo 'Error adding event: ' .
mysql_error() . '';
}
Generally, what you are looking for is called "upsert" (ie UPdate or inSERT). From this link apparently for MySQL the syntax is:
INSERT ... ON DUPLICATE KEY UPDATE
With more info from the MySql manual.
I want to thank everyone here for the help I have recieved so far. My next question is a bit more complicated.
So I have a database set up on my server, and I have a form on my website where I am submitting data to my MYSQL database.
After I submit the data, I am having trouble searching for it, displaying possible results, and then making those results HYPERLINKED so that the user can find out more about they are looking for.
My "common.php" script is set up like this:
<?php
$username = "XXX";
$password = "XXX";
$hostname = "XXX";
$database = "XXX";
mysql_connect($hostname, $username, $password, $database) or die
("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
?>��
My "insertdata.php" script is set up like this:
<?php
require("common.php");
// connect with form
$name=$_POST['firstname'];
$lastname=$_POST['lastname'];
$city=$_POST['city'];
$state=$_POST['state'];
$zip=$_POST['zip'];
$phone=$_POST['phone'];
$email=$_POST['email'];
$various=$_POST['various'];
$other=$_POST['other'];
// insert data into mysql
$query="INSERT INTO datatable
(
firstname,
lastname,
city,
state,
zip,
phone,
email,
various,
other,
)
VALUES
(
'$firstname',
'$lastname',
'$city',
'$state',
'$zip',
'$phone',
'$email',
'$various',
'$other',
)";
$result=mysql_query($query);
// if successfull displays message "Data was successfully inserted into the database".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='insert.php'>Back to main page</a>";
}
else {
echo "ERROR... data was not successfully insert into the database";
}
mysql_close();
?>��
From there, I want to make the inserted data searchable.
My problem is, when the search is completed, I want to only display the First Name and Last Name in two separate columns.
From there, I want a link displayed in a third separate column with a link in each row that says "View Record Details."
Finally, when "View Record Details" in clicked, it brings me to the correct record, formatted again in an HTML table.
The closest I have come to a solution is:
<?php
require("common.php");
$query="SELECT * FROM datatable";
$result=mysql_query($query);
$num=mysql_numrows($result);
$i=0;
while ($i < $num) {
$firstname=mysql_result($result,$i,"firstame");
$lastname=mysql_result($result,$i,"lastname");
$i++;}
?>
As an additional question, when I use PDO, does that change my HTML?
Switch to PDO. Your code will look something like this:
$conn = new PDO('mysql:host=db_host;dbname=test', $user, $pass);
$sql = 'SELECT * FROM datatable';
foreach ($conn->query($sql) as $row) {
print $row['firstname'] . "\t";
print $row['lastname'] . "\n";
}
EDIT:
To link back for details add this line after the 2nd print:
print "<a href='somephp.php?idx=" . $row[ 'idx' ] . "'>link here</a>";
You'll need another php file called 'somephp.php':
$conn = new PDO('mysql:host=db_host;dbname=test', $user, $pass);
$idx = $_REQUEST[ 'idx' ];
$sql = 'SELECT * FROM datatable where idx = ?';
$stmt = $conn->prepare( $sql );
$stmt->bindParam( 1, $idx );
$stmt->execute();
$row = $stmt->fetch();
// now print all the values...
print $row['firstname'] . "\t";
print $row['lastname'] . "\t";
print $row['address'] . "\t";
and so on...
NOTE: This depends on each record having a unique key 'idx'. I don't see this in your values above so you'll have to find a way to incorporate it if you want to use this code.
ALSO: You ask - does this change the HTML and does this handle table formatting - No to both. You do all the HTML formatting via the print statements. All PHP does it output lines to the browser.
So I'm getting this error:
Error: Column count doesn't match value count at row 1
(Very common, and I've checked through google, and my issue is that most of the issues are actual comlumn mismatches as it describes)
My location table has "user", "latitude", "longitude", "posttext", user and posttext are both varchar, and lat and long are int. For the time being, I'm just trying to insert values with user and posttext values. I've taken the query out of my php, and run it in the SQL part of phpmyadmin and it runs fine, so I'm not sure why I'm getting the error.
A php form supplies the post data from text boxes, and this is the php processing code:
<?php
error_reporting(E_ALL);
$username = $_POST['user'];
$textToPost = $_POST['textToPost'];
$con = mysql_connect("127.0.0.1","*","*");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test");
$sql= "INSERT INTO location(user, posttext)
VALUES ('.$username.,.$textToPost.')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
echo $username;
echo $textToPost;
?>
So I'm hoping it's a very basic syntax error on my part, but could someone help?
You're missing some quotes:
$sql= "INSERT INTO location(user, posttext)
VALUES ('".$username."','".$textToPost."')";
Shouldn't the query be like this?
$sql= "INSERT INTO location(user, posttext)
VALUES ('".$username."','".$textToPost."')";
Try with
$sql= "INSERT INTO location(user, posttext)
VALUES ('".$username."','".$textToPost."')";
Remember you MUST always sanitize user input before using it in a query!!
It could be better using prepared statements...
I am having an issue were my code appears to be correct and am getting no errors querying or connecting to my database. "ErrorNumber 0:..."
But when i check phpMyAdmin it clearly has not queried. I have check all of my titles and table names, database name and everything is fine. My query will just not run or insert. here is my code:
mysql_connect('localhost', 'root', 'root', 'aliendatabase');
if (!$dbc) {
die('Error connecting to MySQL server.' . mysql_error());
}
$query = "INSERT INTO aliens_abduction(first_name, last_name, when_it_happened, how_long, how_many, alien_description, what_they_did, fang_spotted, other, email)" .
"VALUES('$first_name', '$last_name', '$when_it_happened', '$how_long', '$how_many', '$alien_description', '$what_they_did', '$fang_spotted', '$other', '$email')";
mysql_query($query, $aliendatabase);
echo "error number" . mysql_errno() . ": " . mysql_error() . "\n";
echo 'Connected Successfully';
mysql_close($dbc);
what is $dbc ?
It should rather be $dbc = mysql_connect(...) to test the connection.