mySQL expects parameter to be string - php

Ok, so I basically have a form where users can fill out information, on form submission the information gets loaded into my SQL database.
There is an "administrator" page that displays all users that are in my User Table in my DB.
All is well and good that all works perfectly but my problem is that I made the userId's clickable so that when I click on the userId that specific entry will be loaded from the db.
I can't get the userId that I selected printed on the screen.
Here's my Admin page:
<html>
<head>
</head>
<body>
<?php
//Step 1: Set the connection object equal to our database
$conn = mysql_connect("localhost", "root", "") or die (mysql_error());
//Step 2: Set the databse you want to use
mysql_select_db("assignment_3", $conn);
//Step 3: Write sql that we want to run against the database
$sql = "select id, firstName, lastName, emailAddress from usertable";
//Step 4: Run the sql statement against the database connection object we created $conn
$result = mysql_query($sql, $conn) or die (mysql_error());
//STEP 5: Process the result set $result
print "<table border='1'>";
print "<tr>";
print "<td>id</td>";
print "<td>firstName</td>";
print "<td>lastName</td>";
print "<td>emailAddress</td>";
while ($row = mysql_fetch_assoc($result)) { // this is getting each row that was returned
$clickId = $row['id'];
print "<tr>";
print "<td><a href ='showUser.php?userId=$clickId'> $clickId </a></td>";
print "<td>$row[firstName]</td>";
print "<td>$row[lastName]</td>";
print "<td>$row[emailAddress]</td>";
}
print "</table>";
?>
</body>
</html>
If you run this page all the users in the db are loaded and displayed in a table and all of their userId's become clickable links when clicked take you to the showUser.php page which displays the information for the user that was selected.
Here is the code for the showUser.php page. I need to grab the userId with the GET method from the URL and then query the DB against that ID so show the user information.
I'm really stuck and need some help.
<html>
<head>
</head>
<body>
<?php
$id = filter_input(INPUT_GET, "userId");
//Make db connection
$conn=mysql_connect("localhost","root","")or die(mysql_error());
//Step 2: select your db to use
mysql_select_db("assignment_3",$conn);
//Step 3: Write the sql that we want to run against the database
$sql = mysql_query("select id, firstName, lastName, emailAddress, phoneNumber, underGradSchoolId, gradSchoolId, securityQuestionId from usertable where id='$id'");
$result = mysql_query($sql,$conn)or die(mysql_error());
print "<table border='1'>";
print "<tr>";
print "<td>id</td>";
print "<td>firstName</td>";
print "<td>lastName</td>";
print "<td>emailAddress</td>";
print "<tr>";
print "<td>id</td>";
print "<td>firstName</td>";
print "<td>lastName</td>";
print "<td>emailAddress</td>";
print "<td>phoneNumber</td>";
print "<td>underGradSchoolId</td>";
print "<td>gradSchoolId</td>";
print "<td>securityQuestionId</td>";
print "</table>";
?>
</body>
</html>

You are using mysql_query twice:
$sql = mysql_query("select id, ...");
$result = mysql_query($sql,$conn)or die(mysql_error());
Which should be (renamed so it is like the first code you posted)
$result = mysql_query("select id, ...") or die(mysql_error());
$row = mysql_fetch_assoc($result);
Now you can print the values like
print "<td>".$row['id']."</td>";
Also keep in mind that mysql_* functions are officially deprecated and hence should not be used in new code. You can use PDO or MySQLi instead. See this answer on SO for more information.

First verify that your getting the value you expect with $id. After step 3, print $sql and make sure it ends with "where id = '{selected id}'"

Related

Generate buttons with php that delete or edit a row in a table in db

I need to call database and a specific table, then display table values in rows and at the end of them have buttons 'edit' and 'delete' that allow me to edit that line or delete it completely.
At the moment I only manage to display the table and generate the buttons, but not 'tie' the buttons to that row.
I need to generate the buttons when displaying the table, and then 'tie' the buttons to corresponding row.
Edit:
if(!empty($_POST) && isset($_POST['show'])) {
$sel = "SELECT id, vardas, pavarde, amzius, miestas FROM zmogaus_info";
$res = mysqli_query($conn, $sel);
if(mysqli_num_rows($res)>0){
while($row = mysqli_fetch_assoc($res)){
echo "Id: ".$row["id"]." ".$row["vardas"]." ".$row["pavarde"]." ".$row["amzius"]."m."."<input type='submit' name='".$row['id']."' value='Delete'>"."<br>";
}
}
}
if(!empty($_POST) && isset($_POST[$row['id']])){
$sql = "DELETE FROM zmogaus_info WHERE id=".$row['id'];
mysqli_query($conn, $sql);
}
I think the problem might be with the way I use $row['id'] and i might need to make it into a global variable?
If you are able to var_dump($result) and there is data there from DB, then there is no need for a while loop.
Also research PDO, much safer method of data transfer to and from DB.
$sel = "SELECT id, vardas, pavarde, amzius, miestas FROM zmogaus_info";
$result = $mysqli -> query($sel);
// Define the associative array as $row
$row = $result -> fetch_assoc();
echo "Id: ".$row["id"]." ".$row["vardas"]." ".$row["pavarde"]." ".$row["amzius"]."m."."<input type='submit' name='".$row['id']."' value='Delete'>"."<br>";

Fetch data and display it in a table in with codeigniter

Could anyone help me fetch data from a database and view it in a table? I am new to codeigniter framework.
here is a short Code for fetching Data from an SQL-Table
First you create a Connection:
// Create connection
$db = mysqli_connect($host,$username,$password,$database)
or die('Error connecting to MySQL server.');
The Values:
$host = your host-ip or URL or localhost
$username = Your Database Username
$password = your Database Password
$database = your database's Name
Then you need to request(query) something from a Table in that Database
For Example like this:
$sql = "SELECT * FROM $table ORDER BY id DESC";
$res = mysqli_query($db, $sql) or die("Fehler:$sql");
while($row = mysqli_fetch_assoc($res))
{
}
Now this Code will get all the Data out of a Table and orders it by the ID Descending.
In that code $table stands for your Table-Name and $db is your Database Name, as PHP7 needs it by every Query.
The Results eg. ALL Data in the Table, ordered by ID is now stored in the single Variable $res. If you want you can use code to check 'if ($res = true)' in order to make sure that you actually get a result from the query and catch an exception.
The 'Method mysqli_fetch_assoc()' will now give you all the Data nice and easy.
All you have to do is use this While Loop like this:
while($row = mysqli_fetch_assoc($res))
{
$username = $row['username'];
$date= $row['date'];
}
Meaning, that every While Cycle goes through one Row of results in the order you chose to query it at.
And $row acts as an Array where the Idice, ([] text in these brackets) corresponds to the given Clumn Name in your Table
Hope i could help you out :)
And please in the future state your question a little more clear and detailed and show that you have actually worked on your Problem before asking
Spytrycer
Edit
I overread the table part :)
In order to view it in a Table you should do something like this:
echo"<table border = '1'>";
echo"<tr>";
//Do <td> and </td> for as many Columns as you have and write them between the td's
echo"<td>";
echo"Column Name";
echo"</td>";
//Then comes the Data part
$sql = "SELECT * FROM $table ORDER BY id DESC";
$res = mysqli_query($db, $sql) or die("Fehler:$sql");
while($row = mysqli_fetch_assoc($res))
{
//open new Row
echo"<tr>";
//Do this td, data, /td loop for as many Columns you have in your
Database. For a Database with id, username and Password for example:
echo"<td>";
echo"$row['id']";
echo"</td>";
echo"<td>";
echo"$row['username']";
echo"</td>";
echo"<td>";
echo"$row['password']";
echo"</td>";
echo"</tr>";
//Close row
}

How to echo specified data form sql database in php

I need to print data from users table for username that is logged in, for example, need to bring HP, attack, defence, gold... I found many answers here and after this I am sure I am gone ask more questions. Please help...
<?php
session_start()
if(isset($_SESSION['username'])){
echo "Welcome {$_SESSION['username']}";
}
require_once 'config.php';
$conn = mysql_connect($dbhost,$dbuser,$dbpass)
or die('Error connecting to mysql');
mysql_select_db($dbname);
$query = sprintf("SELECT ID FROM users WHERE UPPER(username) = UPPER('%s')",
mysql_real_escape_string($_SESSION['username']));
$result = mysql_query($query);
list($userID) = mysql_fetch_row($result);
echo "Health Points:".$row['HP'];
echo "Attack:";
echo "Defence:";
echo "Gold:";
?>
You have to query for all the information you actually want. So your query should look like this:
SELECT HP,Atk,Def,Gold FROM ...
This will retrieve the named fields from your database and not just the ID.
Also, you never assign your row, it should read
$row = mysql_fetch_row($result);
(But see my comment below).
1 - there is missing ; in the first line
2 - try "SELECT * " instead of "SELECT ID"
3 - $row is not defined , try :
$row = mysql_fetch_assoc($result);
instead of
list($userID) = mysql_fetch_row($result);
check the manual for the difference between mysql_fetch_row and mysql_fetch_assoc
mysql_fetch_assoc

mySQL database: printing specific row or rows from a db table

please assist. i have a database with a couple of tables and rows and i want the php to print specific rows as and when i want it to. at the moment it renders all the content of the spesific table on my webpage. in future, i would like it to display the contents of a specific table if a cirtain user is logged in so im going to do that when i understand if statements and get over this hurdle 1st. my code is as follows:
<?php
include 'connect-mysql.php';
echo "<br/>";
$query = "SELECT CUSTOMER_NAME, RAMSCODE FROM customer";
$result = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_array($result))
{
echo "{$row['CUSTOMER_NAME']} <br>" .
"RAMSCODE: {$row['RAMSCODE']} <br>" ;
}
?>
To fetch specific rows from a table you have to include a WHERE clause in your SQL statement.
For example:
$query = "SELECT CUSTOMER_NAME, RAMSCODE FROM customer WHERE customer_id = 2";
Match the WHERE xxxxx clause to any column in your table
You need to specifiy yor criteria as a where clause in the SQL
$query = "SELECT CUSTOMER_NAME, RAMSCODE FROM customer where RAMSCODE = %1";
$result = mysql_query($query,mysql_real_escape_string($yourcode)) or die (mysql_error());
Also you really need to Read the Manuals!
As far as i've get what you want is to display only that row from customers table, which customer is logged in. you can use some thing like this:
while($row = mysql_fetch_array($result))
{
if($row['CUSTOMER_NAME'] == " //Customer Logged In (customer name from session)"){
echo "{$row['CUSTOMER_NAME']} <br>" .
"RAMSCODE: {$row['RAMSCODE']} <br>" ;
}else{
//do nothing or continue with printing all
}
}
Hope this helps.

No results showing for mysql select all

Hello guys i am trying to show all the users pokemon were the table belongsto = there username here is my code
i have a connect on top of this has well
// Get all the data from the "example" table
$result = "SELECT * FROM user_pokemon WHERE
belongsto='".$_SESSION['username']."'
AND (slot='0')'";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo $row['pokemon'];
echo $row['id'];
}
i have print red the username and there username is in the username session .
i think i mite be missing a ' or something i add or mysql at the end of the query but then the pages dies with no error
You are not running the query and have an error in it. And you're not escaping strings going into query.
A proper version of the code would be
// escape a string going to query.
$username = mysql_real_escape_string($_SESSION['username']);
// create a query
$sql = "SELECT * FROM user_pokemon WHERE belongsto='$username' AND slot=0";
// run a query and output possible error for debugging purposes.
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
// keep getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo $row['pokemon'];
echo $row['id'];
}
It appears to me that the final query would be:
SELECT * FROM user_pokemon WHERE belongsto='NAME' AND (slot='0')'
where NAME is the name you pass in. If that is the case, there is an extra single quote at the end. I presume you are getting a SQL error?

Categories