looked around, saw a lot of MySQL answers but not MySQLi..
Im attempting to return 1 line of my choosing.
at the moment I can return only the first line.
What im trying to get to is, have my main database be linked by ID, when you click the ID, a closer look at the record is on another page..
<?php
$connect = mysqli_connect("localhost", "root", "", "mydb");
$query = "SELECT name, surname FROM info ORDER BY id";
$record = mysqli_query($connect, $query);
#$num_results = mysqli_num_rows($record);
$row = mysqli_fetch_assoc($record);
$fname = $row['name'];
$surname = $row['surname'];
print $fname;
print $surname;
?>
In order to do what you're asking, first create a list of users:
$connect = mysqli_connect("localhost", "root", "", "mydb");
$query = "SELECT name, surname FROM info ORDER BY id";
$record = mysqli_query($query, $connect);
while($row = mysqli_fetch_assoc($record)){
$user = $row['name'] . ' ' . $row['surname'];
echo '' .$user . '</br>';
}
The will create a list of all your users which look like:
Bart Simpson</br>
Matt Damon</br>
And so on.
When you click the user's link in the original page, it should be processed by the code in user.php:
$connect = mysqli_connect("localhost", "root", "", "mydb");
$query = "SELECT name, surname FROM info WHERE id = ?"; // returns one line identified by id - you can use something else if you're guarateed the value is unique in your table
$stmt = mysqli_prepare($connect, $query);
mysqli_stmt_bind_param($stmt, 'i', $_GET['uid']);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $name, $surname);
mysqli_stmt_fetch($stmt);
I'll bet you can guess what happens now, can't you? That's right, you can echo out the data for the individual user on this page:
$user = $name . ' ' . $surname;
echo $user;
NOTES:
The connection code could be placed in a separate file and included in pages where needed.
You could write a function to handle every query you write.
In order to prevent the possibility of SQL Injection I have used prepared statements for MySQLi. Even escaping the string is not safe!
Generally I would be a lot more consistent with my coding, performing queries the same way each and every time. doing so will reduce troubleshooting time as well as making your code easier for others to read.
Related
I'm not sure my question makes much sense so I will try my best to explain. Basically, I want the $_GET['quote_id'] to be a condition in the query but it is displaying on the web page instead, I'll post a picture as an example.
Code.php
<?php
$connect = mysqli_connect("localhost", "root", "", "quote");
$query = "select * from `quote` where quote_id = '". $id = print_r($_GET['quote_id'])."'";
$result = mysqli_query($connect, $query);
?>
As you can see, it is displaying on the web page instead of being a part of the query which is my goal
Thanks for your help,
I dont know why you used print_r (a function that prints human-readable information about a variable), this is why the output is showing on your page.
Try change to this, first dont attribute and use a variable at same, do only one thing at time for readability, second use filter_input to sanitize your inputs or prepared statements to avoid SQL Injection attacks:
<?php
$id = filter_input($_GET['quote_id'], FILTER_SANITIZE_NUMBER_INT);
$connect = mysqli_connect("localhost", "root", "", "quote");
$query = "select * from `quote` where quote_id = '". $id ."'";
$result = mysqli_query($connect, $query);
?>
I have tested everything and nothing works here's my code
<?php
session_start();
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) { die('Invalid id'); }
$conn = mysqli_connect("redacted", "redacted", "redacted", "redacted");
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$id = (int)$_GET['id'];
"UPDATE affiliate SET clicks WHERE ID='$id' = clicks + 1";
header("Location: https://discord.gg/CjzZRBq");
?>
and after I want it to echo on the users dashboard this is what I have
<h1>Clicks</h1>
<br />
<br />
You have gotten: <?php $conn = mysqli_connect("localhost",
"id2278622_jonny", "Fencing1", "id2278622_affiliate");
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
$sql = "SELECT clicks FROM affiliate WHERE ID='$ID'";
echo "$sql";
?> Clicks!
but it just echos the sql code
You haven't actually sent your query to the database. You've just built a query string. A string that you didn't even save to a variable.
$id = (int)$_GET['id'];
"UPDATE affiliate SET clicks WHERE ID='$id' = clicks + 1";
header("Location: https://discord.gg/CjzZRBq");
Should be:
$id = (int)$_GET['id'];
$qry= "UPDATE affiliate SET clicks = clicks+1 WHERE ID='$id'";
conn->query($qry);
header("Location: https://discord.gg/CjzZRBq");
You should also look up SQL Injection. Casting to an int mitigates risk, but you should definitely be using bind variables.
The problem is you're just echoing $sql (which is the query string), rather than passing that SQL command to your database. Also note that your current script is vulnerable to SQL injection. To avoid this, use prepared statements:
// Retrieve the number of existing clicks
$stmt = $conn->prepare("SELECT clicks FROM affiliate WHERE ID = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($clicks); // Store the result in the $clicks variable
$clicks++; // Increment clicks
// Update the table
$stmt2 = $conn->prepare("UPDATE affiliate SET clicks = ? WHERE ID = ?");
$stmt2->bind_param("si", $clicks, $id);
$stmt2->execute();
// Close the connection once finished
$conn->close();
Hope this helps! :)
I'm trying to create a very simple web app that checks if an element is inside the database.
If the element is located at least one time in the DB, then echo "YES", otherwise if the element doesn't exist just echo "NO".
Here's my code :
$mysql = mysqli_connect(/* can't share anything here */) or die ("ERROR CONNECTING TO THE DB");
if(isset($_POST['submit'])) {
$theAddress = $_POST['url'];
$result = "SELECT * FROM data WHERE url = " . $theAddress;
$query = mysqli_query($mysql, $result);
if (!$query) {
printf("Error");
} else {
printf("NO ERROR");
}
The problem here is that PHP always echo "Error". Why?
In order to execute SQL queries successfully you need to put the string values inside quote.
So your query will be:
$result = "SELECT * FROM data WHERE url = '" . $theAddress . "'";
You need quotes around the value because it's a string.
$result = "SELECT * FROM data WHERE url = '" . $theAddress . "'";
But it would be better if you learned to use prepared queries with mysqli_stmt_bind_param(), then you don't have to worry about this.
Try with prepared statements like this:
$stmt = mysqli_stmt_init($mysql);
if (mysqli_stmt_prepare($stmt, 'SELECT * FROM data WHERE url = ?')) {
mysqli_stmt_bind_param($stmt, "s", $theAddress);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
}
Documentation:
http://us.php.net/manual/en/mysqli-stmt.prepare.php
http://us.php.net/manual/en/mysqli-stmt.get-result.php
Trying to follow a tutorial, but i get a database error on line six of the executable php file (second code below)
<?php
mysql_connect("localhost","root","") or die("Error: ".mysql_error()); //add your DB username and password
mysql_select_db("beyondmotors");//add your dbname
$sql = "select * from `TestTable` where ID = 1";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)){
$id = $row['ID'];
$fname = $row['FName'];
$lname = $row['LName'];
$phone = $row['PHON'];
//we will echo these into the proper fields
}
mysql_free_result($query);
?>
<html>
<head>
<title>Edit User Info</title>
</head>
<body>
<form action="updateinfo.php" method="post">
userid:<br/>
<input type="text" value="<?php echo $id;?>" name="id" disabled/>
<br/>
Last Name:<br/>
<input type="text" value="<?php echo $fname;?>" name="fname"/>
<br/>
Last Name:<br/>
<input type="text" value="<?php echo $lname;?>" name="lname"/>
<br/>
Phone Number:<br/>
<input type="text" value="<?php echo $phone;?>" name="phon"/>
</br>
<input type="submit" value="submit changes"/>
</form>
</body>
</html>
and here is the executable
<?php
mysql_connect("localhost","root","") or die("Error: ".mysql_error()); //add your DB username and password
mysql_se lect_db("beyondmotors");//add your dbname
//get the variables we transmitted from the form
$id = $_POST[''];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$phon = $_POST['phon'];
//replace TestTable with the name of your table
$sql = "UPDATE `TestTable` SET `FName` = '$fname',`LName` = '$lname',
`PHON` = '$phon' WHERE `TestTable`.`ID` = '$id' LIMIT 1";
mysql_query($sql) or die ("Error: ".mysql_error());
echo "Database updated. <a href='editinfo.php'>Return to edit info</a>";
?>
everything is good until i hit submit changes; than i get error on line 6. I'm new to database so please be specific if possible. Thank you! also if anyone could point me to a similar, "working" tutorial that would help ALOT!
trying to follow this tutorial: http://teamtutorials.com/web-development-tutorials/editing-mysql-data-using-php
i'm using wamp server, so the database log in is correct. I mean it displays the data, just doesn't edit it..
The error i'm getting is :
Notice: Undefined index: ID in C:\wamp\www\test\updateinfo.php on line 6
i get that even if i change post to $id = $_POST['ID'];
Ok I changed the $_POST['']; to $_POST['id']; , still had the same error.
Than I read online to add a # to the front so now it looks like this: #$_POST['id'];
That too off all the errors. but not my data base is not been updated. Everything goes through with no errors but no data is been changed??
Also when i tried to remove backticks I get this error:
Parse error: syntax error, unexpected T_STRING in C:\wamp\www\test\updateinfo.php on line 12
So i left them the way they were...
Could it be because i'm using a local server? This should be all simple not sure what i'm doing wrong here.. I mean i literary copied everything over from the tutorial.
First and foremost, you should be warned that your code is completely vulnerable against sql injections. Escaping your POST data before inserting it into the database is a good start in protecting your database.
Also, learning the mysql extension is useless for new systems because it is deprecated. You might think about looking into the PDO interface or the mysqli extension. There are many beginner tutorials for both and you will gain much more.
Now, as for your error
Make sure you are defining which ID you want to update in your database. In your second block of code you have:
//get the variables we transmitted from the form
$id = $_POST[''];
needs to change to:
$id = $_POST['id'];
You said you get the error even if you change post to $id = $_POST['ID'], but if you look at your form, the id input has name = 'id' and PHP is case sensitive.
Now, in your sql query, all of those back ticks are unnecessary. Also, there is no point in specifying which table ID because this is all being done in ONE table, TestTable.
//replace TestTable with the name of your table
$sql = "UPDATE TestTable SET FName = '$fname',LName = '$lname',
PHON = '$phon' WHERE ID = '$id' LIMIT 1";
EDIT:
Although the query above is syntactically correct, you should consider using mysqli or PDO due to reasons mentioned above. Below are examples using mysqli and PDO.
Mysqli
mysqli Manual
/* connect to the database */
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
/* build prepared statement */
$stmt = $mysqli->prepare("UPDATE TestTable SET FName=?, LName=?, PHON=? WHERE ID=?)");
/* bind your parameters */
$stmt->bind_param('sssi', $fname, $lname, $phon, $id);
/* execute prepared statement */
$stmt->execute();
/* close connection */
$stmt->close();
PDO
PDO Manual
/* connect to the database */
$dbh = new PDO('mysql:host=localhost;dbname=database', $user, $pass);
/* build prepared statement */
$stmt = $dbh->prepare("UPDATE TestTable SET FName = :fname, LName = :lname, PHON = :phon WHERE ID = :id");
/* bind your parameters */
$stmt->bindParam(':fname', $fname);
$stmt->bindParam(':lname', $lname);
$stmt->bindParam(':phon', $phon);
$stmt->bindParam(':id', $id);
/* update one row */
$fname = 'John'; # or use your $_POST data
$lname = 'Doe';
$phon = '123-456-7890';
$id = 1;
/* execute prepared statement */
$stmt->execute();
/* use it again!1! */
$fname = 'Jane';
$lname = 'Doe';
$phon = '123-456-7890';
$id = 2;
/* execute prepared statement */
$stmt->execute();
/* close connection */
$dbh = null;
Remove backticks:
UPDATE TestTable SET FName = '$fname',LName = '$lname',PHON ='$phon'
WHERE TestTable.ID = '$id' LIMIT 1";
I have the code below which links to a page called deletepage.php which is in my FTP in the right directory. It adds the variable on the end from a database query, that bit works and it opens the page correctly:
X
But now I have this code to run a query on that in the MySQL database but it doesn't actually delete it when it should be deleting it:
$con = mysql_connect("localhost", "will", "blahblah");
if (!$con) {
die('Could not connect: '.mysql_error()); //check for database errors
}
$username = $_GET['user'];
mysql_select_db("themacsp_clipboy", $con);
$sql = ("DELETE * FROM links WHERE link = ".(int)$_GET['plink'] AND username='$username');
mysql_query($sql);
header("location: http://themacsplash.com/userfiles/$username");
?>
I get an error:
Parse error: syntax error, unexpected '=' in >/data/www/vhosts/themacsplash.com/httpdocs/ClipBoy/deletepage.php on line 10
Line 10 is the $sql line ($sql = ("DELETE * FROM links WHERE link = ".(int)$_GET['plink'] AND username='$username');)
How would I fix this?
You were missing some quotes again.
You should probably be doing it step by step, since it's less confusing:
$plink = (int)$_GET['plink'];
$sql = "DELETE FROM links WHERE link=$plink AND username='$username'";
Line should be
$sql = ("DELETE * FROM links WHERE link = ".(int)$_GET['plink'] . "AND username='$username'");
Also you should sanitize those $_GET strings with mysql_real_escape_string() to help avoid SQL injection hacks.
$sql = "DELETE * FROM links WHERE link = ".(int)$_GET['plink']." AND username='".$username."';";
You concatenated the strings and the variables in a wrong way. This'll do.
i think it is in this line
<?php
//replace
//$sql = ("DELETE * FROM links WHERE link = ".(int)$_GET['plink'] AND username='$username');
//with
$sql = "DELETE * FROM links WHERE link = ".(int)$_GET['plink']. "AND username='".$username."'";
?>