Dynadot โ€” .com Registration $8.99

Lost in Php... no idea what I'm doing wrong

Spaceship Spaceship
Watch

Kage

Established Member
Impact
1
hey well Im working on this php for fun/class... and for the life of me... I dont know what Im doing wrong. to start off..... the table setup.
I dont know what I did... heres the code, it used to work.. and I dont know what I changed... but now it doesnt even make the table. So if you can help, please do.

db file for the include:
PHP:
<?
$username="name";
$password="pass";
$database="databasename";
?>
setup code:
PHP:
<?php
include("db.php");
$con = mysql_connect('localhost', $username, $password);
if (!$con) {
   die('Could not connect: ' . mysql_error());
}

echo 'Connected successfully';

$db_selected = mysql_select_db($database, $con);
if (!$db_selected) {
   die ('Can\'t use $database : ' . mysql_error());
}

$query="CREATE TABLE newspost
(id int(6) NOT NULL auto_increment,
newstitle varchar(50) NOT NULL,
loginname varchar(40) NOT NULL,
date varchar(100) NOT NULL,
news varchar(500) NOT NULL,
PRIMARY KEY (id),
UNIQUE id (id),
KEY id_2 (id))";
mysql_query($query);
mysql_close($con);
echo "Made the Database";
?>
 
0
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
Unstoppable DomainsUnstoppable Domains
The coding looks good, I will look further into this.
 
0
•••
you have news as a varchar(500) but the maximum for a varchar is 255 so the query is failling.

If you require longer then you should use TEXT
 
Last edited:
0
•••
@filth thank you so very much... I feel real stupid for diving into the code without learning some basic things like that.

now again.... for another stupid question, It seems not to input into the database..
the add form:
Code:
<form action="insert.php" method="post">
Title: <input type="text" name="newstitle"><br />
Name: <input type="text" name="loginname"><br />
News: <input type="text" name="news"><br />
<input type="Submit">
</form>

and then the inserting:
PHP:
<html>
<head>
<title> Insterting to the DB </title>
<meta http-equiv="refresh" content="5;url=index">
</head>
<body>
<?php
$newstitle = $_POST['newstitle'];
$loginname = $_POST['loginname'];
$date = date('l dS \of F Y h:i:s A');
$news = $_POST['news'];

include("db.php");
$connect = mysql_connect(localhost,$username,$password);

if (!$connect)
  {
  die('Could not connect: ' . mysql_error());
  }

$db_selected = mysql_select_db($database,$connect);

if (!$db_selected)
  {
  die ("Error : " . mysql_error());
  }

$query = "INSERT INTO 'newspost' ('newstitle','loginname','date','news') VALUES('$newstitle','$loginname','$date','$news')";
mysql_query($query);

mysql_close($connect);
echo "$query";
?>
</body>
 </html>

and then I might as well also ask if this is correct coding for displaying it
PHP:
<?php
include("db.php");
$connect = mysql_connect(localhost,$username,$password);
if (!$connect)
  {
  die('Could not connect: ' . mysql_error());
  }

$db_selected = mysql_select_db($database,$connect);

if (!$db_selected)
  {
  die ("Error : " . mysql_error());
  }

$query = "SELECT * FROM newspost";
$result = mysql_query($query,$connect);

$num = mysql_num_rows($result);

mysql_close($connect);
?>

<?php
$i=0;
while ($i < $num) {
$newstitle=mysql_result($result,$i,"newstitle");
$username=mysql_result($result,$i,"loginname");
$date=mysql_result($result,$i,"date");
$news=mysql_result($result,$i,"news");
?>
	<div id="newsbox">
	<div id="newstitle"> <?php echo "$newstitle"; ?> </div>
	<div id="posted">Post made by <?php echo "$loginname"; ?>, on <?php echo "$date"; ?></div>
	<div id="news"><?php echo "$news"; ?></div><br />
	</div>
<?php
++$i;
}
?>
 
Last edited:
0
•••
no problem at all everyone makes silly mistakes sometimes even the best coders do.

1 thing I would advise which I do most of the time. Echo the query and try it on a test database using phpmyadmin. phpmyadmin is quite good for things like that. The error message told me immediately about the length problem. Alternatively check the status of the query to see if it failed or not at present your code only executes it but does not ensure it was ok.
 
0
•••
Thanks, I had forgoten about phpmyadmin. I was looking at it.. very useful.

I think my problem is that after looking at code for a while it all looks the same, sorta like my writing.... anyways, meaning its hard for me to see my own stupid mistakes.
 
Last edited:
0
•••
All sorted now Kage or? :) Anyway, here's a little tip. Whenever inserting data into MySQL, or using any information gathered via PHP/forms etc to grab data from a db, it'd be wise to filter that input. Because you can NEVER trust user input. Here are three functions that are similar to what I use:

PHP:
//Use this on pretty much anything
function sanitize($value)
{
  $search = array('@<script[^>]*?>.*?</script>@si',
                  '@<applet[^>]*?>.*?</applet>@si',
                  '@<object[^>]*?>.*?</object>@si',
                  '@<iframe[^>]*?>.*?</iframe>@si',
                  '@<style[^>]*?>.*?</style>@si',
                  '@<form[^>]*?>.*?</form>@si',
                  '@<[\/\!]*?[^<>]*?>@si',
                  '@([\r\n])[\s]+@',
                 );
  $replace = array('','','','','','','','');
  $value = preg_replace($search, $replace, strip_tags($value));
  return $value;
}

//Call this one on any data we're adding to a db
function db_sanitize($value)
{
  $value = (!get_magic_quotes_gpc()) ? trim($value) : trim(stripslashes($value));
  $value = (function_exists('mysql_real_escape_string')) ? mysql_real_escape_string($value) : addslashes($value);
  return $value;
}

//Use this on the data you pull from a db for display
function clean($data)
{
  return trim(stripslashes($data));
}

//An example

/*Your typical form here*/
if(isset($_POST['submit']))
{
  $name = sanitize($_POST['name']);
  $email = sanitize($_POST['email']);

  if(!empty($name) && !empty($email))
  {
    $query = mysql_query("INSERT INTO people (name, email) VALUES('".db_sanitize($name)."', '".db_sanitize($email)."')") or die(mysql_error());
  }
  //bleh
}

//Displaying

$query = mysql_query("SELECT name, email FROM people") or die(mysql_error());

while($row = mysql_fetch_array($query))
{
  echo 'Name: '.clean($row['name']).'<br />E-mail: '.clean($row['email']).'<br />'."\n";
}

:)
 
0
•••
sorry for this post.. but those who might not know.. I edited my 8:05 post with more questions...
 
0
•••
the reason the inseting is not working i because you have quotes around your table name and field names.

you have

PHP:
$query = "INSERT INTO 'newspost' ('newstitle','loginname','date','news') VALUES('$newstitle','$loginname','$date','$news')";

which should be

PHP:
$query = "INSERT INTO `newspost` (`newstitle`,`loginname`,`date`,`news`) VALUES('$newstitle','$loginname','$date','$news')";

(notice the quotes have been replaces by back ticks)

Regarding the second question. I personally would use a foreach loop rather than a while loop alos i am not 100% sure about it but I think mysql_close will have to be after you have dealt with the results as when you close the database connection the result resource will no longer exist.
 
Last edited:
0
•••
wow thanks for all the help again. I never relized that those were to be back tics and not ' . The reason why I think I was doing that was because when I started this I was using a mono font stuff.... thus it looking really alike. Thanks again.
So yah I have everything working now, and I feel stupid forgetting to ask how to order then in the newest to oldest..
 
Last edited:
0
•••
for ordering add something like this at the end of the query:-

PHP:
ORDER BY `newstitle` ASC
(for the opposite order use DESC instead of ASC)
 
0
•••
Thanks very much again. I dont know what I would have done without your help.
 
0
•••
Dynadot โ€” .com Registration $8.99Dynadot โ€” .com Registration $8.99
Unstoppable Domains
Domain Recover
NameMaxi - Your Domain Has Buyers
  • The sidebar remains visible by scrolling at a speed relative to the pageโ€™s height.
Back