Using mySql to retrieve a certain value based on a condition - php

I'm currently doing a computing project which requires me to use an id(which is a primary key in one table) as a secondary key for another table. I want to use sessions to keep track of the variable using commands like this
$id=$_SESSION['id'];
However I'm currently having the problem of getting id from the table it's the primary key in. This is the mysql statement I'm using.
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
$sql='INSERT INTO user(email,pass) VALUES ("'.$email.'","'.$pass.'")';
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sql='SELECT id FROM user WHERE user(email)="'.$email'"'
I've done a bit of looking but haven't found any examples of how to do this. The information is being sent to the database and id's are being generated and I will add validation once it all works. However I can't retrieve the specific id's from the database. Also is there a specific variable I have to use (like $result) or do I just do $id=$sql after the query is completed?

Instead of running another query, the mysqli provides a way to get the primary key from the last insert using a property of the connection called insert_id like this
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO user(email,pass) VALUES('$email','$pass'");
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
// get the id
$lastId = $conn->insert_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

Try this :
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
$sql='INSERT INTO user(email,pass) VALUES ("'.$email.'","'.$pass.'")';
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$lastId = mysqli_insert_id($con);

Related

Can PHP or mysqli capture equivalent of mysql console responses? [duplicate]

This is the code I'm using for deleting row from my DB:
<?php
$eid = $_GET['eid'];
$con = mysqli_connect("localhost", "root", "","project") or die("Connection failed");
echo "connection is done";
$query = "delete from exam where eid='$eid'";
if ($con->query($query)==TRUE)
{
echo " record deleted";
}
else
{
echo "Error: " . $query . "<br>" . $con->error;
}
$con->close();
?>
The else statement is not getting executed. It displays "record deleted" for every value even if the value is not found in the database.
Why is this happening? how can I verify that my record has been deleted from my DB?
You can use mysqli.affected-rows.
Consider the following:
$query="delete from exam where eid='$eid'";
if ($con->query($query)==TRUE && $con->affected_rows > 0) {
echo " record deleted";
} else {
echo "Error: " . $query . "<br>" . $con->error;
}

Getting a Value to use in an update script in php

I am trying to pass a value from a select into an update script. I have a page that keeps a members information. I would like to keep the user name and password on a different table. However I am having problems getting the id from the member table to pass to the user id table. Here is what I am doing. The first query is working fine and adding the member information to the member table. It is where I try to do the select and the second update is where I am having problems.
$user_id;
$sql = "INSERT INTO member_contact (mem_first_name, mem_last_name, mem_address_1, mem_address_2, mem_city, mem_state, mem_zip, mem_phone, mem_email)
VALUES ('$_POST[mem_fn]','$_POST[mem_ln]','$_POST[mem_add1]','$_POST[mem_add2]','$_POST[mem_city]','$_POST[mem_st]','$_POST[mem_zip]','$_POST[mem_ph]','$_POST[mem_email]')";
if ($conn->query($sql) === TRUE) {
//echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$selsql = "select mem_id into $user_id from member_contact
where mem_first_name = '$_POST[mem_fn]'
and mem_last_name = '$_POST[mem_ln]'";
if ($conn->query($selsql) === TRUE) {
echo 'mem_id';
} else {
echo "Error: " . $selsql . "<br>" . $conn->error;
}
$insql = "insert into user_info (mem_id, user_id, user_pass)
values('$user_id','$_post[us_id]','$_post[us_pass]')";
if ($conn->query($insql) === TRUE) {
echo 'User name added';
} else {
echo "Error: " . $insql . "<br>" . $conn->error;
}
$conn->close();
Here is the error I am getting with this code.
Error: select mem_id into from member_contact where mem_first_name = 'Andy' and mem_last_name = 'D'
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 'from member_contact where mem_first_name = 'Andy' and mem_last_name = 'D'' at line 1User name added
Thanks for any help.

SQL and POST requests

How do I handle variables from POST requests? Lets say I have tables like this And I want to update the votes variable wherever a specific id is.
So for the code I have this
$vote = $_POST["votes"];
$sentid = $_POST["sentid"];
along with something like this
UPDATE `my_exampleo202s`.`President Candidates` SET votes = votes + 1 WHERE `President Candidates`.`id` = sentid
And in the post request I send the sentid with a number. sentid=3
This doesn't work though. I'm not able to give any errors or anything because I'm not viewing it from a browser.
Any idea what the proper way is that I'm supposed to do this?
(Here's the code I have right now if it's needed)
<?php
$vote = $_POST["votes"];
$sentid = $_POST["sentid"];
$conn = new mysqli("localhost","exampleo202s","","my_exampleo202s");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE `my_exampleo202s`.`President Candidates` SET votes = votes + 1 WHERE `President Candidates`.`id` = sentid";
if ($conn->query($sql) === TRUE) {
echo "<br>Record updated successfully <br>";
} else {
echo "<br>Error updating record: <br>" . $conn->error;
}
$conn->close();
?>
UPDATE
<?php
$vote = $_POST["votes"];
$sentid = $_POST["sentid"];
$conn = new mysqli("localhost","jusavoting10rxx9s3","","my_jusavoting10rxx9s3");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE `my_jusavoting10rxx9s3`.`President Candidates` SET votes = votes + 1 WHERE `President Candidates`.`id` = $sentid";
if ($conn->query($sql) === TRUE) {
echo "<br>Record updated successfully <br>";
} else {
echo "<br>Error updating record: <br>" . $conn->error;
}
$conn->close();
?>
Try echo your $_POST value if it doesn't work:
<?php
$vote = $_POST["votes"];
$sentid = $_POST["sentid"];
$conn = new mysqli("localhost","exampleo202s","","my_exampleo202s");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE `my_exampleo202s`.`President Candidates` SET votes = votes + 1 WHERE `President Candidates`.`id` = $sentid";
if ($conn->query($sql) === TRUE) {
echo "<br>Record updated successfully <br>";
} else {
echo "<br>Error updating record: <br>" . $conn->error;
}
$conn->close();
?>

Insert data to database from CSV file. Only inserts last row

I read in data from a csv file, and want to insert it into my database. The issue is that it only inserts the last row in the CSV file each time. However when i print my $sq1 to screen it shows all 48 inserts with the different values that they should have. Could anyone tell me why it only inserts one row into the database?
<?php
// Did modify login values for privacy
$servername = "10.100.";
$username = "myusername";
$password = "abc123";
$dbname = "informationdata";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$file = fopen("ALMGrade.csv","r");
while(! feof($file)){
$ar =fgetcsv($file);
$sql = "INSERT INTO gradetable_copy (Grade, Grade1, Grade2, Grade3, Grade4, Grade5, Grade6)
VALUES ('$ar[0]', '$ar[1]', '$ar[2]', '$ar[3]', '$ar[4]', '$ar[5]', '$ar[6]' )";
echo $sql;
echo "<br>";
}
fclose($file);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
move the execution of query ($conn->query($sql) ) inside while:
while(! feof($file))
{
$ar =fgetcsv($file);
$sql = "INSERT INTO gradetable_copy (Grade, Grade1, Grade2, Grade3, Grade4, Grade5, Grade6)
VALUES ('$ar[0]', '$ar[1]', '$ar[2]', '$ar[3]', '$ar[4]', '$ar[5]', '$ar[6]' )";
echo $sql;
echo "<br>";
if ($conn->query($sql) === TRUE)
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
fclose($file);

Import data from a txt file in a MySQL database with PHP on visit

I'm using PHPMyAdmin to run my MySQL database.
Suppose we have this txt file "people.txt", a MySQL database and a PHP page in which are showed the data from the database. Suppose that data in the text file are stored with this syntax:
2015/16/01|Alex|Paris
2015/13/01|Johnny|Berlin
2015/11/01|Mary|Oslo
You can notice that each field is separated with a |
Is there any way to import these data using a PHP script? I want to show you a different script that, when the page is visited, send data to the database:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO `People` (data, name, city)
VALUES ('2015/10/01', 'Will', 'Rome')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo "OK!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
I want to emulate this script in order to let check, each time the page is visited, the txt file. Any help?
I tried to merge the PHP script that shows my data and the one that import them from the txt file but it doesn't seem to work properly..
<?php
$con=mysqli_connect("localhost","username","","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed: " . mysqli_connect_error();
}
$sql = "
LOAD DATA INFILE 'people.txt'
INTO TABLE `People`
FIELDS TERMINATED BY '|'
";
$result = mysqli_query($con,"SELECT * FROM `People`");
echo "<table class='people'>
<tr class='titles'>
<th>Data</th>
<th>Name</th>
<th>City</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Data'] . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['City'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Use the "LOAD DATA INFILE" statement to just load the data into the table every time the page is visited.
$sql = "
LOAD DATA INFILE 'people.txt'
INTO TABLE `People`
FIELDS TERMINATED BY '|'
";
One part of the SQL to look into are the REPLACE or IGNORE option, which determines what will happen if the script tries to insert a row that duplicate an existing unique key, if your table has any.
Also, if your input file has fields in a different order than your database table, then you can provide a list of columns at the end of the SQL, like (data, name, city).
Other than those things, I think you should simply be able to replace the $sql variable in your posted code with something like the above SQL, then run (as in your original code):
if ($conn->query($sql) === TRUE) {
echo "OK!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

Categories