MySQL column mismatch error on very basic query - mysql

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...

Related

mysqli_stmt_bind_param is inserting zeros in my

i`m trying to make a login form using prepare statements, but the code is includin in my sql only zeros in the fields here is my code, thank you for helping me!
$con=mysqli_connect('localhost','mupcku', '123', 'dbproject');
mysqli_set_charset($con, 'utf8');
if(!$con){
echo mysqli_connect_error($con);
echo 'Cannot connect to database!';
exit;
}
$sql="INSERT INTO users (user_name, pass) VALUES (user_name=?, pass=?)";
$stmt=mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 'ss', $username, $pass);
mysqli_stmt_execute($stmt);
if(!$stmt){
echo 'Грешка!';
die(mysqli_error($stmt));
}
This is the error which i can see Warning: mysqli_stmt_bind_param() expects parameter 1 to be mysqli_stmt, boolean given in C:\xampp\htdocs\dbproject\reg.php
Also i use this
if(isset($_POST['username']) && isset($_POST['pass'])){
$username= trim($_POST['username']);
$pass= trim($_POST['pass']);
to assign values.

Fetching data from database in php file

I am trying to fetch data from table. Table contains the data and query is true. Even why following query says $u and $t are not define. While condition becoming false.
I manually checked in database, it was showing results.
$url = "http://paulgraham.com/";
$user_id = "123";
$con = mysqli_connect('127.0.0.1', 'root', '', 'mysql');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$result = mysqli_query($con,"SELECT * FROM post_data WHERE userid =".$url." and url=".$user_id."");
while ($row = #mysqli_fetch_array($result))
{
echo "hi";
$t = $row['title'];
$u = $row['url'];
}
echo "title is : $t";
echo "url is : $u";
Giving your SQL query :
"SELECT * FROM post_data WHERE userid =".$url." and url=".$user_id.""
You can see you are mixing url and userid... Change to :
"SELECT * FROM post_data WHERE userid =".$user_id." and url=".$url.""
Also define your $t and $u variables before your loop in case you have no record.
Next time, try to var_dump your generated query to test it.
If you were able to see the errors the DBMS is reporting back to PHP then you'd probably be able to work out what's wrong with the code.
Before the 'while' loop try...
print mysql_error();
(the obvious reason it's failing is that strings mut be quoted in SQL, and you've got the parameters the wrong way around)

mysql_query: Unknown error

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')";

Displaying MYSQL data in a HTML table AFTER a search

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.

What is causing the error in the selecting part of my script?

Im getting the following error: Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'country FROM countries WHERE idcountry=4 VALUES ('','Almelo')' at line 1
Thanks in advance for helping me with this problem because im trying to fix it for 3 days now.
Im getting 2 data pieces from my form through $POST. This is the form:
form action="inc/add/addcity.php" method="post">
Select country:
$query="SELECT idcountry,country FROM countries ORDER BY country ASC";
$result = mysql_query ($query);
echo "<select name='countrybox' id='countrybox' value=''>Country</option>";
while($nt=mysql_fetch_array($result)){
echo "<option value=$nt[idcountry]>$nt[country]</option>";}
echo "</select>";<br>
City to add: <input type="text" name="addcity" id="addcity"/>
<input type="submit" name="sumit" value"sumit"/>
</form>
The option value's are coming from my database
Now the action php file
include 'addmysql.php';
$data = $_POST;
$citypost = $data['addcity'];
$cityselected = $data['countrybox'];
$cityselected1 = "SELECT country FROM countries WHERE idcountry=$cityselected";
$citytable = "cities";
$citytable .= "$cityselected1";
$sql= "INSERT INTO $citytable VALUES ('','$citypost')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "<script type='text/javascript'>window.location='../../add.php'; </script>"
I think this line:
$citytable .= "$cityselected1";
is causing grief. $citytable ends up with the SELECT query sandwiched inside of the INSERT. That is the reason for the specific error you're seeing.
However, I'm not sure I fully understand what you want this code to do.