I am trying to make a comment section on my hand made site, using PHP and MySQL. I have got the comments stored in my database, but when I try to SELECT them my site throws up this error,
mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 9 in /home/a9210109/public_html/comments.php on line 16
My code so far is below
<?php
$comment = $_POST['comment'];
$mysql_host = "";
$mysql_database = "";
$mysql_user = "";
$mysql_password = "";
mysql_connect($mysql_host,$mysql_user,$mysql_password);
#mysql_select_db($mysql_database) or die( "Unable to select database");
$CreateTable = "CREATE TABLE comments (comment VARCHAR(255), time VARCHAR(255));";
mysql_query($CreateTable);
$UseComment = "INSERT INTO comments VALUES ('$comment')";
mysql_query($UseComment);
$SelectComments = "SELECT * FROM comments";
$comments = mysql_query($SelectComments);
$num=mysql_numrows($comments);
$variable=mysql_result($comments,$i,"comment");
mysql_close();
?>
Show/Hide Comments
<?php
$i=0;
while ($i < $num) {
$comment=mysql_result($comments,$i,"comment");
echo "<div id='hidden' style='display:none'><h3>$comment</h3></div>";
$i++;
}
?>
change
$num=mysql_numrows($comments);
to
$num=mysql_num_rows($comments);
the right syntax is mysql_num_rows not mysql_numrows
$i is not set in the first php part:
$variable=mysql_result($comments,$i,"comment");
Fix the above!
There are no records in data base.
$UseComment = "INSERT INTO comments VALUES ('$comment')"; is wrong.
Change it as
$UseComment = "INSERT INTO comments(comment) VALUES ('$comment')";
Thanks.
Firstly, you may check this question.
Regarding with your code, you did not have $i before the line 16 which caused the error:
$variable=mysql_result($comments,$i,"comment");
You should check if there is any result before issuing mysql_result:
$SelectComments = "SELECT * FROM comments";
$comments = mysql_query($SelectComments);
if( $num = mysql_num_rows($comments) ){
$variable = mysql_result($comments, 0, "comment");
}
I would personally write a COUNT query to get the total number of comments:
$sql = 'SELECT COUNT(*) total FROM comments';
$comments = mysql_query($sql);
$row = mysql_fetch_assoc($comments);
$totalComments = $row['total'];
In this case, you don't need to check with mysql_num_rows() because the COUNT query will definitely return one result "0" or whatever.
Related
Using PHP + Oracle 12c
I'm trying to insert many rows but i got an error "oci_execute(): ORA-00001: unique constraint (S95417.FIRMA__IDX)" This is strange for me because in loop i'm getting last id and incrementing it.
I used debbuger and (On INSERT) i'm getting last id but incrementing is not working.
Could you tell me why?
Data which i added
INSERT INTO FIRMA VALUES(18,MICROSOFT,2432213715,2020-03-26,23)
INSERT INTO FIRMA VALUES(19,APPLE,7512202082,2020-03-26,42)
SELECT NVL(MAX(firmaid),0)+1
I made code very similar using that for other tables and it's working fine.
My code:
$ile_razy = $_POST['liczba_powtorzen'];
$firma = "SELECT * FROM FIRMA";
$c = oci_connect($username, $password, $database);
if (!$c) {
$m = oci_error();
trigger_error('Could not connect to database: '. $m['message'], E_USER_ERROR);
}
$file = 'firma.txt';
$current = file_get_contents($file);
for ($i = 1; $i <= $ile_razy; $i++) {
$nazwa = randCompanyName();
$nip = randNIP();
$dataWspolpracy = date("Y-m-d");
$ids_array = array();
$adresid = "SELECT adresid FROM ADRES";
$stmtt = oci_parse($c, $adresid);
$result = oci_execute($stmtt);
while($row = oci_fetch_array($stmtt))
{
$ids_array[] = $row['ADRESID'];
}
$randIndex = array_rand($ids_array);
$adresId = $ids_array[$randIndex];
// HERE IS PROBLEM
$firmaQuery = "INSERT INTO FIRMA SELECT NVL(MAX(firmaid),0) + 1,'$nazwa', '$nip', '$dataWspolpracy', '$adresId' from FIRMA";
$ex = oci_parse($c,$firmaQuery);
// "zapytanie" is working fine
$zapytanie = "SELECT NVL(MAX(firmaid),0)+1 from FIRMA";
$stmt = oci_parse($c, $zapytanie);
$results = oci_execute($stmt);
while($row = oci_fetch_assoc($stmt)){
$rowid = $row["NVL(MAX(FIRMAID),0)+1"];
}
$firmaIdForTxt = "INSERT INTO FIRMA VALUES(".$rowid.",".$nazwa.",".$nip.",".$dataWspolpracy.",".$adresId.")";
echo $rowid. ", ";
oci_execute($ex);
$current .= $i. ".".$firmaIdForTxt."\n";
file_put_contents($file, $current);
}
In my db
I have changed that but error still appears
You can make your FIRMAID an identity column : Oracle will handle the increment internally, and it is much more safer for your data.
Then you can insert your data with this query :
INSERT INTO FIRMA(nazwa, nip, datawspolpracy, adresid) VALUES('$nazwa', '$nip', '$dataWspolpracy', '$adresId')
NOTE : this is for a quick answer, for a safer solution and avoid SQL injections, use prepared statements : PHP oci examples (See example #2)
I am trying to create a guestbook that shows comments people have posted through an SQL query. I have successfully connected to the SQL database, but the query isn't showing anything. What is wrong here?
</form>
<h2>Current Posts</h2>
";
$sql = "SELECT * FROM 'guest_booklet' LIMIT 0, 30 ";
if ($numrows > 0) {
echo "$rows ['email']";
while ( $row = mysql_fetch_row($result) ){
$id = $row ['id'];
$name = $row['name'];
$email = $row['email'];
$message = $row['message'];
$message = n12br($message);
echo "<div>
$name - and email is $email <hr/>
$message
<div>";
}
}
mysql_close();
?>
</body>
</html>
1) Change
$sql = "SELECT * FROM 'guest_booklet' LIMIT 0, 30 ";
To
$sql = "SELECT * FROM `guest_booklet` LIMIT 0, 30 ";
=> Use Backtick instead of single quotes for enclosing table name.
2) You missed $result = mysql_query($sql);
3) You Missed $numrows = mysql_num_rows($result);.
4) Remove echo "$rows ['email']"; line. It's suspense from where it comes.
Mysql (Updated Code)
<?php
$sql = "SELECT * FROM `guest_booklet` LIMIT 0, 30 ";
$result = mysql_query($sql);
$numrows = mysql_num_rows($result);
if ($numrows > 0) {
while ( $row = mysql_fetch_row($result) ){
$id = $row ['id'];
$name = $row['name'];
$email = $row['email'];
$message = n12br($row['message']);
echo "<div>".$name." - and email is ".$email." <hr/>.".$message."<div>";
}
}
mysql_close();
?>
[Note: The mysql_* functions are deprecated, they have been removed from PHP 7, your code will stop working when you upgrade to that version. You should not write new code using them, use mysqli_* or PDO instead.]
Click To Know How can I prevent SQL-injection in PHP?
Mysqli (Updated Code)
<?php
//Connection
$servername = "YOUR-VALUES";
$dbname = "YOUR-VALUES";
$user = "YOUR-VALUES";
$password = "YOUR-VALUES";
$connection = mysqli_connect($servername,$user,$password,$dbname);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `guest_booklet` LIMIT 0, 30 ";
$result = mysqli_query($connection,$sql);
$numrows = mysqli_num_rows($result);
if ($numrows > 0) {
while ( $row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$id = $row ['id'];
$name = $row['name'];
$email = $row['email'];
$message = n12br($row['message']);
echo "<div>".$name." - and email is ".$email." <hr/>.".$message."<div>";
}
}
mysqli_close($connection);
?>
You are missing a lot of stuff here.
You are closing the PHP tag but not opening it: <?php
You are never actually executing the query, you are missing a call to $result = mysql_query($sql);
You are using $numRows but never actually setting its value: `$numRows = mysql_num_rows($result);
You are using $row = mysql_fetch_row(...) but latter you are reading the resulting row as an associative array instead of a numeric index. You have to use mysql_fetch_assoc instead.
You are never actually connecting to the DB and selecting a schema, I assume you do that somewhere else, but you close the connection at the end. So make sure you are actually connecting.
It seems like you copied this from somewhere else but didn't do it right.
Things that are wrong
The syntax is not within PHP tags so won't do anything
Using single quote marks around a table name is invalid, you need backticks
(or nothing at all)
The $sql statement is never actually run
I assume $numrows is never set, so it will never be over 0
$rows['email'] is not set so it wont echo
$result is never set, so
you won't be able to iterate through it's rows
Original (incorrect) answer
Because you have LIMIT 0, 30. You are telling MySql to give you 0 results starting at index 30.
Also you are using mysql_fetch_row on a query string not a result set, you need to first actually run the query.
-- And indeed i am wrong with my assumption, here is the right thing you need to do:
"; //What is this?
$sql = "SELECT * FROM 'guest_booklet' LIMIT 0, 30 ";
$result = mysql_query($sql); //you need to add this
$sql = "SELECT count(id),soft_name from table_name GROUP BY soft_name";
$d = mysqli_fetch_assoc(mysqli_query($db_name, $sql));
$c = array_shift($d);
The result is always 2, but the database contains more than 3000 items. What could be the problem?
Records are not pulled the way you are pulling for that you have to use similar to following code:
if($result = mysqli_query($db_name, $sql)){
while($d = mysqli_fetch_assoc($result){
echo $d['count'];
}
}
More reference here.
I want to count the rows in the users table with specific name and pwd which should be 1 if existed.
but the result always return null(not 0),no matter whether the user existed or not.
I even change the query simple to "SELECT * FROM users", and it ended with the same result.
And I am pretty sure that the name of the DATABASE and TABLE are true,and the table is not empty!
By the way,why I have to use "#" symbol before "mysqli_query" in order to get rid of error?
thx!
enter code here
<?php
#$mysql_db_hostname = "localhost";
$mysql_db_hostname = "127.0.0.1";
$mysql_db_user = "root";
$mysql_db_password = "";
$mysql_db_database = "smartFSUsers";
$con = mysqli_connect($mysql_db_hostname, $mysql_db_user, $mysql_db_password,$mysql_db_database);
if (!$con) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
$name = $_GET["name"];
$password = $_GET["password"];
$query = "SELECT * FROM users WHERE name='$name' AND password='$password'";
$result =#mysqli_query($query,$con);
echo($result);
$row=#mysqli_num_rows($result);
echo"the row num is $row \n";
?>
RTM: http://php.net/mysqli_query
$result =#mysqli_query($query,$con);
You've got your parameters reversed. $con MUST come first:
$result = mysqli_query($con, $query) or die(mysqli_error());
If you had bothered adding error correction to your code, you'd have been told about this. But nope, you opted for # to hide all those error messages.
I am having a problem with mysql. My php code is not working.
<?php
mysql_connect("localhost", "root", "root") or die("Unable to connect to the database");
mysql_select_db("visitor_counter") or die("Database is not created");
$find_counts = mysql_query("SELECT * FROM user_count");
while($row = mysql_fetch_assoc($find_counts))
{
$current_count = $row['counts'];
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE 'visitor_counter' . 'user_count' SET
'counts'=$new_count");
}
?>
I have tested putting some echo on my codes. Once i put the echo code on the while loop the echo doesnt work. Can anyone help me.
Try this :
mysql_connect("localhost", "root", "root") or die("Unable to connect to the database");
mysql_select_db("visitor_counter") or die("Database is not created");
$find_counts = mysql_query("SELECT * FROM user_count");
$current_count = 0;
while($row = mysql_fetch_assoc($find_counts))
{
$current_count = $row['counts'];
}
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE 'visitor_counter' . 'user_count' SET
'counts'=$new_count");
Check if your SELECT query works by change the code:
mysql_query("SELECT * FROM user_count") or die(mysql_error());
Check if there is data in de table user_count and edit the query:
while($row = mysql_fetch_assoc($find_counts))
{
print_r($row); //to print the database row
$current_count = $row['counts'];
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE user_count SET counts=".$new_count); // no need to specify the database, you already did with mysql_select_db.
}
Dont need to specify DB, and quotes are wrong, change to:
$update_count = mysql_query("UPDATE user_count SET counts = $new_count");
You also might want to specify a page:
$update_count = mysql_query("UPDATE user_count SET counts = $new_count WHERE page = '$this_page'");
what are you trying here ?
mysql_query("UPDATE 'visitor_counter' . 'user_count' SET 'counts'=$new_count");
whats the table name ?
i guess your tablename is user_count
or do you have more than one tablename you like to update ?!?!?
if tablenam eis user_count it should look like
$update_count = mysql_query("UPDATE user_count SET counts={$new_count}");
so the total while would be
while($row = mysql_fetch_assoc($find_counts))
{
$current_count = $row['counts'];
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE user_count SET counts={$new_count}");
}
Important
Dont use
'tablename'
in your sql query... if you like to declair a tablename use
`tablename`
Use single query:
UPDATE `visitor_counter`.`user_count` SET `counts`=`counts`+1;
then do your SELECT ... FROM
because passing variable into sql query for this kind of operations are not always safe
and here is Your code:
<?php
mysql_connect("localhost", "root", "root") or die("Unable to connect to the database");
mysql_select_db("visitor_counter") or die("Database is not created");
mysql_query("UPDATE `visitor_counter`.`user_count` SET `counts`=`counts`+1");
$counts = array();
$result = mysql_query("SELECT * FROM user_count");
while($data = mysql_fetch_assoc($result)) {
$counts[$data['id']] = $data['counts'];
}
?>
I'm really surprised to see everybody here posts code using the old and deprecated mysql functions (although some of them stated this is wrong). I would like to advice you AGAINST using mysql functions - they are deprecated as of version 5.5. You should use either mysqli or PDO instead. In my opinion, you should be using PDO as it provides support for almost all databases and you could use prepared statements.
Now to your code - I'm not quite sure why would use a cycle to count all of the records in the counts column. A much better way to do this is by using atomic increment - it will also guarantee your counter is properly incremented in case two queries are trying to increment the value simultaneously. Although you haven't posted your table structure, I believe something like this should do the work:
<?php
// Database connection settings
$db_host = '127.0.0.1';
$db_name = 'visitor_counter';
$db_user = 'root';
$db_pass = 'root';
// Try to connect to the database
try {
$dsn = 'mysql:host='.$db_host.';dbname='.$db_name;
$db = new PDO($dsn, $db_user, $db_pass);
} catch ( PDOException $e ){
// Do something if connection could not be established
throw new ErrorException("Could not connect to database!",0,1,__FILE__,__LINE__,$e);
}
// Find counts
// Assuming you have a user_id column in your `user_count` table.
$user_id = 1;
// Update counter
$update = $db->prepare('UPDATE user_count SET counter=(counter+1) WHERE user_id = :user_id');
$update->bindValue(':user_id', $user_id, PDO::PARAM_INT);
$update->execute();
?>
P.S. In this code I'm assuming you're saving the visitor counter in the user_count.counter column and whenever somebody visits that user, the counter column is incremented for that specific user, rather than updating the counter for all users (as your code suggests).